<?php

namespace Meramo\mrm_be\Hooks\TCE;

use DOMDocument;
use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use \TYPO3\CMS\Core\Database\Connection;
use \TYPO3\CMS\Core\Service\FlexFormService;
use \TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
use TYPO3\CMS\Extbase\Utility\DebuggerUtility;

use \Meramo\mrm_be\Mongoer as Mongoer;

require_once GeneralUtility::getFileAbsFileName('typo3conf/ext/mrm_be/Resources/Private/PHP/phpqrcode/qrlib.php');

class TCEMainHook
{
  protected $imageSizes = array(
    'mrm_be_cm_publication' => array(
      'passthru' => array(
        'small' => array('width' => 256),
        'big' => array('width' => 512)
      )
    ),
    'mrm_be_cm_homeheaderinfo' => array(
      'i_1_1' => array(
        'i_1_1' => array('width' => 140, 'height' => 140),
      ),
      'i_16_9' => array(
        'i_16_9' => array('width' => 140, 'height' => 79),
      ),
      'default' => array(
        'default' => array('width' => 140, 'height' => 94),
      )
    ),
    'mrm_be_cm_explorerbox' => array(
      'i_1_1' => array(
        'img' => array('width' => 500, 'height' => 500),
      )
    ),
    'mrm_be_cm_statementbox' => array(
      'i_1_1' => array(
        'img' => array('width' => 160, 'height' => 160),
      )
    ),
    'mrm_be_cm_checklist-radiorange' => array(
      'i_1_1' => array(
        'img' => array('width' => 160, 'height' => 160),
      )
    ),
    'mrm_be_cm_tileoverview' => array(
      'default' => array(
        'default_hero_lte600' => array('width' => 560, 'height' => 373),
      )
    ),
    'mrm_be_cm_heroimage' => array(
      'default' => array(
        'lte600' => array('width' => 560, 'height' => 373),
        'gt600' => array('width' => 408, 'height' => 272)
      ),
    ),
    'mrm_be_cm_imageplus' => array(
      'default' => array(
        'ratio32' => array('width' => 439, 'height' => 293)
      ),
      'i_16_9' => array(
        'ratio169' => array('width' => 727, 'height' => 409)
      ),
      'i_21_9' => array(
        'ratio219' => array('width' => 984, 'height' => 422)
      )
    ),
    'mrm_be_cm_contentimage' => array(
      'i_1_1' => array(
        'content_image' => array('width' => 160, 'height' => 160),
        'content_image_maximized_lte600' => array('width' => 560, 'height' => 560),
        'content_image_maximized_gt600' => array('width' => 460, 'height' => 460),
      ),
    ),
    'mrm_be_cm_rawimage' => array('passthru' => true),
    'mrm_be_cm_animation' => array('passthru' => true),
    'mrm_be_cm_picturechoice' => array(
      'i_1_1' => array(
        'pic' => array('width' => 300, 'height' => 300)
      )
    ),
    'overview_image' => array(
      'default' => array(
        'home_topics_lte767' => array('width' => 725, 'height' => 484),
        'home_topics_gt767' => array('width' => 313, 'height' => 209),
        'sidebar_banner_lte840' => array('width' => 100, 'height' => 66),
        'rubrik_overview' => array('width' => 318, 'height' => 212),
        'default_hero_lte600' => array('width' => 560, 'height' => 373),
        'default_hero_gt600' => array('width' => 408, 'height' => 272, 'allowed_doktypes' => ['102']),
      ),
      'i_1_1' => array(
        'home_rubrik' => array('width' => 95, 'height' => 95),
        'archive_block' => array('width' => 160, 'height' => 160),
        'square_big' => array('width' => 520, 'height' => 520),
      ),
      'i_16_9' => array(
        'og' => array('width' => 1200, 'height' => 675),
        'sidebar_banner_gt840' => array('width' => 282, 'height' => 159),
      ),
      'i_21_9' => array(
        'flat_tile' => array('width' => 400, 'height' => 171),
        'flat_big' => array('width' => 700, 'height' => 300),
      ),
    )
  );

  private $imageService;
  private $resourceFactory;
  private $fileRepository;
  private $environmentService;
  private $queryBuilder;
  private $pageQueryBuilder;
  private $pageRepository;
  private $linkService;
  private $connection;

  function __construct()
  {
    $this->environmentService = GeneralUtility::makeInstance("TYPO3\CMS\Extbase\Service\EnvironmentService");
    $this->resourceFactory = GeneralUtility::makeInstance('TYPO3\CMS\Core\Resource\ResourceFactory');
    $this->imageService = GeneralUtility::makeInstance("TYPO3\CMS\Extbase\Service\ImageService");
    $this->fileRepository = GeneralUtility::makeInstance('TYPO3\CMS\Core\Resource\FileRepository');
    $this->pageRepository = GeneralUtility::makeInstance('TYPO3\CMS\Frontend\Page\PageRepository');
    $this->linkService = GeneralUtility::makeInstance('TYPO3\CMS\Core\LinkHandling\LinkService');

    $connection = GeneralUtility::makeInstance(ConnectionPool::class);
    $this->connection = $connection;

    $this->queryBuilder = $connection->getQueryBuilderForTable('tt_content');
    $this->queryBuilder->getRestrictions()->removeAll()
      ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
      ->add(GeneralUtility::makeInstance(HiddenRestriction::class));

    $this->pageQueryBuilder = $connection->getQueryBuilderForTable('pages');
    $this->pageQueryBuilder->getRestrictions()->removeAll();
  }

  public function processDatamap_beforeStart($pObj)
  {
    if (!isset($pObj->datamap['pages'])) return;

    foreach ($pObj->datamap['pages'] as $pid => &$_d) {
      if (!$pid || $pid < 0) continue;
      $starttime = $_d["starttime"];
      if ($starttime != 0)
        $_d["starttime"] = $this->startOfDay($starttime, null, true, true);
      $endtime = $_d["endtime"];
      if ($endtime != 0)
        $_d["endtime"] = $this->endOfDay($endtime, null, true, true);

      switch ($_d["red_status"]) {
        case "-1": //neu angelegt
        case "1": //in Bearbeitung
        case "2": //vorbereitet
        case "3": //geprüft
        case "21": //gesperrt
        case "22": //archiviert
          $_d["hidden"] = 1;
          break;
        case "11": //frei
        case "12": //online
          $_d["hidden"] = 0;
          break;
        default:
          break;
      }
    }
  }

  public function processCmdmap_afterFinish(\TYPO3\CMS\Core\DataHandling\DataHandler &$pObj)
  {
    if (!isset($pObj->datamap['pages'])) return;

    foreach ($pObj->datamap['pages'] as $pid => $_d) {
      if (!$pid || $pid < 0) continue;
      $this->log('processing PID: ' . $pid);

      $pageStatement = $this->pageQueryBuilder
        ->select('*')
        ->from('pages')
        ->setMaxResults(1)
        ->where(
          $this->pageQueryBuilder->expr()->eq('uid', $this->pageQueryBuilder->createNamedParameter($pid))
        )
        ->execute();

      $post = $pageStatement->fetchAll();
      $post = $post[0];

      if (!$post) continue;

      if ($post['doktype'] == 254) {
        $this->processFolderContent($post);
        continue;
      }

      if ($post['hidden'] == 1 || $post['deleted'] == 1) {
        Mongoer::sendRequest("pages", "delete", array("pageuid" => $pid));
        Mongoer::sendRequest("abialtcache", "delete", array("pageuid" => $pid));
        Mongoer::sendRequest("search", "delete", array("pageuid" => $pid));
        Mongoer::sendRequest("security", "delete", array("pageuid" => $pid));

        // DELETE existing page PDF
        $this->deletePagePDFIfExists($post['slug']);
        //continue;
      }

      $rootlineutil = GeneralUtility::makeInstance('TYPO3\CMS\Core\Utility\RootlineUtility', $pid);
      $rootline = array_reverse($rootlineutil->get($pid));

      $processedImages = array();
      $slugData = $this->constructSlug($pid);
      if (!$slugData) {
        $this->log($pid . " slugData empty");
        continue;
      }

      $qrfilename = '/var/www/html/public/typo3temp/' . mt_rand(0, 0xffffff) . '_' . mt_rand(0, 0xffffff) . '.svg';
      \QRcode::svg("https://abi.de" . $slugData, $qrfilename);
      $qrsvg = file_get_contents($qrfilename);
      unlink($qrfilename);

      $statement = $this->queryBuilder
        ->select('*')
        ->from('tt_content')
        ->where(
          $this->queryBuilder->expr()->eq('pid', $this->queryBuilder->createNamedParameter($pid))
        )
        ->execute();

      $fetchedTTContent = array();
      $pageType = "article";
      //$this->log($post["doktype"]);
      if ($post["doktype"] == 100) $pageType = "event-page";
      if ($post["doktype"] == 101) $pageType = "blog-page";
      if ($post["doktype"] == 102) $pageType = "blogger-page";
      if ($post["doktype"] == 103) $pageType = "archive";
      if ($post["doktype"] == 104) $pageType = "video-page";
      if ($post['is_siteroot'] == 1) $pageType = "home";
      // $overview_image = null;

      while ($row = $statement->fetch()) {
        $fetchedTTContent[] = $row;
        $row["doktype"] = $post["doktype"];
      }

      /* look for overview_image start */
      if ($pageType == "blogger-page" || $pageType == "video-page") {
        $overview_image = $this->processImagesTTContent($post, 'overview_image', 'pages', 'overview_image');
        $overview_image = $overview_image[0] ? $overview_image[0] : null;
      }

      if (!$overview_image) {
        $x = $this->findFirstAppearingElementByType("mrm_be_cm_postimage", $fetchedTTContent, "CType");
        if ($x) {
          $overview_image = $this->processImagesTTContent($x, 'overview_image');
          $overview_image = $overview_image[0] ? $overview_image[0] : null;
        }
      }

      if (!$overview_image) {
        foreach ($fetchedTTContent as $row) {
          if (!$overview_image && ($row['CType'] == "mrm_be_cm_heroimage" || $row['CType'] == "mrm_be_cm_contentimage" || $row['CType'] == "mrm_be_cm_rawimage")) {
            $overview_image = $this->processImagesTTContent($row, 'overview_image');
            $overview_image = $overview_image[0] ? $overview_image[0] : null;
          }
        }
      }

      /* look for overview_image end */

      if ($pageType != "home") {
        $initialContent = $this->createContentElement($pageType, array(), (object) array(), array());
        $initialH1Attribs = array();
        if ($post["roof"] && $post["roof"] != '') $initialH1Attribs["roof"] = $post["roof"];
        if ($post["title"] && $post["title"] != '') $initialH1Attribs["text"] = $post["title"];
        if (sizeof($initialH1Attribs) > 0) $initialContent["subElements"][] = $this->createContentElement("h1", array(), $initialH1Attribs);
      }

      $processedData = array(
        'pageuid' => $pid,
        'documentLanguage' => $post['documentlanguage'],
        'url' => $slugData,
        'shareableUrl' => "https://abi.de" . $slugData,
        'title' => ($post['roof'] != '' ? $post['roof'] . ": " : "") . $post['title'],
        'activeMenuPage' => $post['targetgroup'],
        'overviewImage' => $overview_image,
        'teasers' => array(
          'teaserHome' => $post['teaserHome'],
          'abstract' => $this->removeLinebreaks($post['abstract']),
          'teaserOverview' => $post['teaserOverview'],
          'title' => $post['title'],
          'roof' => $post['roof'],
          'intro' => ($pageType == 'blogger-page') ? $post['overview'] : $post['intro']
        ),
        'sharingActivated' => $post['sharing_activated'] == 1 ? true : false,
        'linkableInHTMLSitemap' => $post['forHTMLSitemap'] == 1 ? true : false,
        'linkableOnHome' => $post['forHome'] == 1 ? true : false,
        'linkableOnCategoryOverview' => $post['forCategoryOverview'] == 1 ? true : false,
        'moveToTopPositionOnCategoryOverview' => $post['forCategoryOverviewTopPosition'] == 1 ? true : false,
        'pageType' => $pageType,
        'pageData' => array(
          'title' => ($post['roof'] != '' ? $post['roof'] . ": " : "") . $post['title'],
          'metas' => array(
            "<meta name=\"keywords\" content=\"" . $post["keywords"] . "\">",
            "<meta name=\"dcterms.date\" content=\"" . date("Y-m-d", $post['tstamp'] > $post['starttime'] ? $post['tstamp'] : $post['starttime']) . "\">",
            "<meta name=\"robots\" content=\"" . ($post['no_index'] == 0 ? "index" : "noindex") . ", " . ($post['no_follow'] == 0 ? "follow" : "nofollow") . "\" />",
            "<meta property=\"og:title\" content=\"" . ($post['roof'] != '' ? $post['roof'] . ": " : "") . $post['title'] . "\">",
            ($overview_image ? "<meta property=\"og:image\" content=\"https://abi.de/cdn/" . $overview_image["sources"]["og"] . "\" >" : ""),
          ),
          'breadcrumbs' => $this->constructBreadCrumb($rootline, $post, $pageType),
          'content' => $initialContent,
          'sidebar' => $this->createContentElement("sidebar", array(), (object) array(), array()),
        ),
        'linkedPosts' => array(),
        'injections' => array(),
        'qr2page' => $qrsvg,
        'status' => $this->constructStatus($post)
      );

      //before content
      switch ($pageType) {
        case "blog-page":
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "blog-author-info"));
          $processedData["injections"][] = "blog-author-info";
          $processedData["pageData"]["sidebar"]["subElements"][] = $this->createContentElement("injection", array("type" => "blog-page-sidebar"));
          $processedData["injections"][] = "blog-page-sidebar";
          break;

        case "blogger-page":
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "blogger-page-author-image"));
          $processedData["injections"][] = "blogger-page-author-image";
          $text = $post['overview'] ?? $post['abstract'];
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("typo3_paragraph", array(), array('text' => '<p>' . $this->exchangeLinkBreaksWithBr($text) . '</p>'), null);
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "blogger-page-author-latest-blogs"));
          $processedData["injections"][] = "blogger-page-author-latest-blogs";
          $processedData["pageData"]["sidebar"]["subElements"][] = $this->createContentElement("injection", array("type" => "blogger-page-sidebar"));
          $processedData["injections"][] = "blogger-page-sidebar";
          break;

        case "video-page":
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "video-date-category"));
          $processedData["injections"][] = "video-date-category";
          $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "video-info"));
          $processedData["injections"][] = "video-info";
          break;
      }

      foreach ($fetchedTTContent as $row) {
        $this->processData($row, $processedData, $processedImages);
      }

      //after content
      $processedData['pageData']['metas'][] = $this->constructMetaDescription($post['abstract'], $processedData['pageData']['content']);
      $processedData['pageData']['metas'][] = $this->constructMetaDescription($post['abstract'], $processedData['pageData']['content'], true);

      if ($pageType == "blog-page") {
        $processedData['pageData']['metas'][] = $this->constructMetaDescriptionForBlogPage('', $processedData['pageData']['content']);
        $processedData['pageData']['metas'][] = $this->constructMetaDescriptionForBlogPage('', $processedData['pageData']['content'], true);
      }



      $processedData['pageData']['metas'] = array_filter($processedData['pageData']['metas'], function ($val) {
        return $val != "";
      });

      switch ($pageType) {
        case "archive":
          $hasSpecificOverviewInjection = false;
          foreach ($processedData["injections"] as $inj) {
            if (str_contains($inj, "-archive-")) {
              $hasSpecificOverviewInjection = true;
              break;
            }
          }
          if (!$hasSpecificOverviewInjection) {
            $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("injection", array("type" => "archive-of-direct-childurls"));
            $processedData["injections"][] = "archive-of-direct-childurls";
          }
          break;
        case "event-page":
          if ($post["event_link"] && $post["event_link"] != "") {
            $processedData["pageData"]["content"]["subElements"][] = $this->createContentElement("typo3_paragraph", array(), array('text' => '<p><a href="' . $post["event_link"] . '" target="_blank">Weitere Infos zu dieser Veranstaltung »</a></p>'));
          }
          break;
      }

      if (sizeof($processedData['pageData']['sidebar']['subElements']) == 0) {
        $processedData['pageData']['sidebar'] = null;
      }
      if (sizeof($processedData['linkedPosts']) == 0) $processedData['linkedPosts'] = null;
      else
        $processedData['linkedPosts'] = array_values(array_unique($processedData['linkedPosts']));

      if (sizeof($processedData['injections']) == 0) $processedData['injections'] = null;
      else
        $processedData['injections'] = array_unique($processedData['injections']);

      if ($post['hidden'] == 1) {
        //TODO: SET STATUS ..
      }

      $this->deletePagePDFIfExists($processedData['url']);
      Mongoer::sendRequest("pages", "save", $processedData);

      $this->generatePDFPath($processedData['pageuid'], $processedData['url']);

      Mongoer::sendRequest("abialtcache", "delete", array("pageuid" => $pid));
      $security_user_pass = $post["security_user_pass"];
      if (!$security_user_pass || $security_user_pass == '')
        Mongoer::sendRequest("security", "delete", array("pageuid" => $pid));
      else {
        $tmp = array();
        foreach (preg_split('/\n|\r\n?/', $security_user_pass) as $itm) {
          $itm = trim($itm);
          $itm = explode('|', $itm);
          $tmp[$itm[0]] = $itm[1];
        }
        $security_user_pass = $tmp;
        Mongoer::sendRequest("security", "save", array("pageuid" => $pid, "url" => $processedData["url"], "data" => $security_user_pass));
      }

      //if($post['doktype'] != 1)   continue;

      if ($post['no_search'] == 0) {
        $dkzer = new \Meramo\mrm_be\DKZer();
        $searchwords = $dkzer->getSearchWords($post['dkz_code_nrs']);
        $freesearchwords = preg_split('/\n|\r|,\n?/', $post['free_searchwords']);
        foreach ($freesearchwords as $sw) {
          $searchwords[] = $this->convertStringToTechnicalName($sw);
        }
        $ignoredsearchwords = preg_split('/\n|\r|,\n?/', $post['ignored_searchwords']);
        foreach ($ignoredsearchwords as &$sw) {
          $sw = $this->convertStringToTechnicalName($sw);
        }
        $searchwords = array_values(array_diff($searchwords, $ignoredsearchwords));
        $searchabletext = $this->constructSearchableText($processedData, true);
        $searchabletext_full = $this->constructSearchableText($processedData, false);

        $arra = array("pageuid" => $pid, "searchwords" => $searchwords, "text" => $searchabletext, "fulltext" => $searchabletext_full, "lesson" => null);
        $lessons = array_values(explode(',', $post['lesson']));
        if (sizeof($lessons) == 1 && $lessons[0] == "") $lessons = [];

        if (sizeof($lessons) > 0) {
          foreach ($lessons as &$l) $l = (int) $l;
          $arra['lesson'] = $lessons;
        }
        Mongoer::sendRequest("search", "save", $arra);
      } else Mongoer::sendRequest("search", "delete", array("pageuid" => $pid));
    }
  }

  private function createPDFHash($url)
  {
    $page = md5($url);
    return  $page[0] . $page[1] . '/' . $page[2] . $page[3] . '/' . $page . '.pdf';
  }

  private function deletePagePDFIfExists($url)
  {
    $partialpath = \TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/pdf-storage/';
    $file = $this->createPDFHash($url);
    $filepath = $partialpath . $file;

    if (file_exists($filepath)) {
      unlink($filepath);
      return true;
    } else {
      return false;
    }
  }

  private function generatePDFPath($pageuid, $url)
  {
    $urlencoded = urlencode($url);
    // $this->log($url, true);
    $urlpart = "https://abi.de/pdfgen?u=";
    $pdfgenurl = $urlpart . $urlencoded;

    $data = [
      'pageuid' => $pageuid,
      'url' => $pdfgenurl,
      'pdfhash' => $this->createPDFHash($url)
    ];

    Mongoer::sendRequest('pdfgenjobs', 'save', $data);
  }

  private function processFolderContent(&$post)
  {
    $statement = $this->queryBuilder
      ->select('*')
      ->from('tt_content')
      ->where(
        $this->queryBuilder->expr()->eq('pid', $this->queryBuilder->createNamedParameter($post["uid"]))
      )
      ->execute();

    $fetchedTTContent = array();
    while ($row = $statement->fetch()) {
      $fetchedTTContent[] = $row;
    }

    if ($post['backend_layout'] == 'pagets__19') {
      $themenderwoche = array();
      $ffs = GeneralUtility::makeInstance(FlexFormService::class);
      foreach ($fetchedTTContent as $row) {
        $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);
        $themenderwoche[] = array(
          "key" => $flex['key'],
          "starttime" => $this->startOfDay($flex['starttime']),
          "endtime" => $this->endOfDay($flex['starttime'], '+6 days'),
          "monday" => (int) $this->parseUIDFromT3Url($flex['monday']),
          "tuesday" => (int) $this->parseUIDFromT3Url($flex['tuesday']),
          "wednesday" => (int) $this->parseUIDFromT3Url($flex['wednesday']),
          "thursday" => (int) $this->parseUIDFromT3Url($flex['thursday']),
          "friday" => (int) $this->parseUIDFromT3Url($flex['friday']),
          "saturday" => (int) $this->parseUIDFromT3Url($flex['saturday']),
          "sunday" => (int) $this->parseUIDFromT3Url($flex['sunday']),
        );
      }
      Mongoer::sendRequest("themaderwoche", "save", array("data" => $themenderwoche));
    }

    if ($post['backend_layout'] == 'pagets__20') {
      $menus = array();
      $ffs = GeneralUtility::makeInstance(FlexFormService::class);
      foreach ($fetchedTTContent as $row) {
        $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);
        $items = array();
        foreach ((array) $flex["dynamicComponents"] as $link) {
          $linkedPostIds = array();
          $itm = $this->parseFlexFormLink($link["links"]["link"], null, $linkedPostIds);
          //$this->log($itm, false);
          unset($itm["href"]);
          $itm["pageuid"] = $linkedPostIds["linkedPosts"][0];
          $items[] = $itm;
        }
        $menus[] = array(
          'headline' => $flex['headline'],
          'menu_id' => $flex['mid'],
          'items' => $items
        );
      }
      Mongoer::sendRequest("menues", "save", array("data" => $menus));
    }

    if ($post['backend_layout'] == 'pagets__21') {
      $topthemen = array();
      $ffs = GeneralUtility::makeInstance(FlexFormService::class);
      foreach ($fetchedTTContent as $row) {
        $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);
        $topthemen[] = array(
          "key" => $flex['key'],
          "starttime" => $this->startOfDay($flex['starttime']),
          "endtime" => $this->endOfDay($flex['starttime'], '+13 days'),
          "section1" => (int) $this->parseUIDFromT3Url($flex['section1']),
          "section2" => (int) $this->parseUIDFromT3Url($flex['section2']),
          "section3" => (int) $this->parseUIDFromT3Url($flex['section3']),
          "section4" => (int) $this->parseUIDFromT3Url($flex['section4']),
          "section5" => (int) $this->parseUIDFromT3Url($flex['section5']),
        );
      }
      Mongoer::sendRequest("topthemen", "save", array("data" => $topthemen));
    }

    if ($post['backend_layout'] == 'pagets__23') {
      $maintenance = array();
      $ffs = GeneralUtility::makeInstance(FlexFormService::class);

      foreach ($fetchedTTContent as $row) {
        $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);
        $maintenance[] = array(
          "starttime" => $flex['starttime'],
          "endtime" => $flex['endtime'],
          "infotext" => $flex['infotext']
        );
      }
      Mongoer::sendRequest("maintenance", "save", array("data" => $maintenance));
    }

    if ($post['backend_layout'] == 'pagets__27' || $post['backend_layout' == 'pagets__28']) {

      $chatbot = array();
      $ffs = GeneralUtility::makeInstance(FlexFormService::class);

      foreach ($fetchedTTContent as $row) {

        $isDirect = $row['CType'] == 'mrm_be_cm_chatbot-direct';

        $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);

        $item = array();

        $item['terms'] = explode("\n", str_replace(',', '', $flex['settings']['terms']));
        $item['type'] = $isDirect ? 'direct' : $flex['settings']['type'];

        if ($isDirect) {
          $item['url'] = $this->replaceT3Link($flex['settings']['url'], null, $row, false);
        }
        if ($flex['settings']['type'] == 'reverse') {
          $item["category"] =  (($flex['settings']['category'] == "Auswählen") ? '' : $flex['settings']['category']);
        }

        $chatbot[] = $item;
      }
      Mongoer::sendRequest("chatbot", "save",  array("data" => $chatbot));
    }
  }

  private function removeLinebreaks($str)
  {
    return trim(preg_replace('/\s+/', ' ', $str));
  }

  private function exchangeLinkBreaksWithBr($str)
  {
    return trim(preg_replace('/\r\n/', '<br />', $str));
  }

  private function startOfDay($ts, $modify = null, $isAtomDate = false, $returnAtomDate = false)
  {
    $dt = null;
    if ($isAtomDate) {
      if (is_numeric($ts)) {
        $ts = $ts + 0;
        $dt = new \DateTime();
        $dt->setTimezone(new \DateTimeZone('UTC'));
        $dt->setTimestamp($ts);
      } else {
        $dt = new \DateTime($ts);
        $dt->setTimezone(new \DateTimeZone('UTC'));
      }
    } else {
      $dt = new \DateTime(null, new \DateTimeZone('Europe/Berlin'));
      $dt->setTimestamp($ts);
    }

    if ($modify) $dt->modify($modify);
    $bodStr = $dt->format('Y-m-d 00:00:00');

    $bodObj = \DateTime::createFromFormat('Y-m-d H:i:s', $bodStr, $returnAtomDate ? new \DateTimeZone('UTC') : new \DateTimeZone('Europe/Berlin'));

    if ($returnAtomDate) return $bodObj->format(\DateTimeInterface::ATOM);

    return (int) $bodObj->getTimestamp();
  }

  private function endOfDay($ts, $modify = null, $isAtomDate = false, $returnAtomDate = false)
  {
    $dt = null;
    if ($isAtomDate) {
      if (is_numeric($ts)) {
        $ts = $ts + 0;
        $dt = new \DateTime();
        $dt->setTimezone(new \DateTimeZone('UTC'));
        $dt->setTimestamp($ts);
      } else {
        $dt = new \DateTime($ts);
        $dt->setTimezone(new \DateTimeZone('UTC'));
      }
    } else {
      $dt = new \DateTime(null, new \DateTimeZone('Europe/Berlin'));
      $dt->setTimestamp($ts);
    }

    if ($modify) $dt->modify($modify);
    $eodStr = $dt->format('Y-m-d 23:59:59');
    $eodObj = \DateTime::createFromFormat('Y-m-d H:i:s', $eodStr, $returnAtomDate ? new \DateTimeZone('UTC') : new \DateTimeZone('Europe/Berlin'));

    if ($returnAtomDate) return $eodObj->format(\DateTimeInterface::ATOM);

    return (int) $eodObj->getTimestamp();
  }

  function array_search_by_key_recursive($needle, array $haystack, &$return)
  {
    foreach ($haystack as $k => $v) {
      if (is_array($v)) {
        $this->array_search_by_key_recursive($needle, $v, $return);
      } else {
        if ($k === $needle) {
          $return[] = $v;
        }
      }
    }
  }

  private function findFirstAppearingElementByType($type, $subs, $typeKey = "type")
  {
    foreach ($subs as $v) {
      if ($v[$typeKey] == $type) return $v;
    }
    return null;
  }

  private function checkOrReduceDescriptionLength($desc, $len)
  {
    $newStr = '';

    $desc = $this->removeLinebreaks($desc);
    if (is_string($desc) && mb_strlen($desc) < $len) {
      $newStr = $desc;
    } else {
      $newStr = substr($desc, 0, $len);
      $pos = strrpos($newStr, ' ');
      $newStr =  substr($desc, 0, $pos);
    }
    return $newStr;
  }

  private function constructMetaDescription($abstract = '', $content, $isOgTag = false)
  {
    $desc = '';
    if ($abstract != '') $desc = $abstract;

    if (!$desc || $desc == '') {
      $desc = $this->findFirstAppearingElementByType("introtext", $content["subElements"]);
      if ($desc)
        $desc = $desc["attributes"]["text"];
    }
    if (!$desc || $desc == '')
      return '';

    if ($isOgTag)
      return "<meta property=\"og:description\" content=\"" . $this->checkOrReduceDescriptionLength($desc, 320) . "\">";

    return "<meta name=\"description\" content=\"" . $this->checkOrReduceDescriptionLength($desc, 320) . "\">";
  }

  private function constructMetaDescriptionForBlogPage($text = '', $content, $isOgTag = false)
  {
    $desc = '';

    if ($text != '') $desc = $text;

    if (!$desc || $desc == '') {
      $desc = $this->findFirstAppearingElementByType('typo3_paragraph', $content["subElements"]);

      if ($desc)
        $desc = strip_tags($desc["attributes"]["text"]);
    }

    if (!$desc || $desc == '')
      return '';

    if ($isOgTag)

      return "<meta property=\"og:description\" content=\"" . $this->checkOrReduceDescriptionLength($desc, 165) . ' …' . "\">";

    return "<meta name=\"description\" content=\"" . $this->checkOrReduceDescriptionLength($desc, 165) . ' …' . "\">";
  }

  private function constructSearchableText($content, $minimum = true)
  {
    $cr = [];
    if (!$minimum) {
      $this->array_search_by_key_recursive("text", $content["pageData"]["content"], $cr);
    } else {
      //$roof = $this->findFirstAppearingElementByType("roof", $content["pageData"]["content"]["subElements"]);
      //if($roof) $cr[] = $roof["attributes"]["text"];
      $h1 = $this->findFirstAppearingElementByType("h1", $content["pageData"]["content"]["subElements"]);
      if ($h1) {
        $cr[] = $h1["attributes"]["roof"];
        $cr[] = $h1["attributes"]["text"];
      }
      $introtext = $this->findFirstAppearingElementByType("introtext", $content["pageData"]["content"]["subElements"]);
      if ($introtext) $cr[] = $introtext["attributes"]["text"];
    }
    $cr = preg_replace("/\r|\n/", " ", strip_tags(implode(" ", $cr)));
    return $cr;
  }

  private function constructStatus($post)
  {
    $publicationType = null;
    switch ($post["red_status"]) {
      case "-1": //neu angelegt
      case "1": //in Bearbeitung
      case "2": //vorbereitet
      case "3": //geprüft
      case "21": //gesperrt
      case "22": //archiviert
        $publicationType = "preview";
        break;
      case "11": //frei
      case "12": //online
        $publicationType = "live";
        break;
      default:
        break;
    }

    $status = array(
      'isLiveFrom' => -1,
      'isLiveTill' => -1,
      'publicationType' => $publicationType,
      'orderStatus' => $post['orderStatus'],
      'date-updated' => ($post['orderStatus'] === 'neu') ? $post['starttime'] : (($post['orderStatus'] === 'aktualisiert') ? $post['red_end'] : ''),
      'seo' => array(
        'sitemap_changefreq' => $post['sitemap_changefreq'],
        'sitemap_priority' => $post['sitemap_priority'],
        'sitemap_lastmod' => time(),
      ),
    );

    if ($post['starttime'] != 0) {
      $status['isLiveFrom'] = $this->startOfDay($post['starttime']);
    }
    if ($post['endtime'] != 0) {
      $status['isLiveTill'] = $this->endOfDay($post['endtime']);
    }

    if ($post['doktype'] == '101') {
      $status['blog_author'] = $post['blog_author'];
      $status['blog_category'] = $post['blog_category'];
    }

    if ($post['doktype'] == '100') {
      $status['event_state'] = $post['event_state'];
      $status['event_category'] = $post['event_category'];
    }

    if ($post['doktype'] == '104') {
      $status['video_category'] = $post['event_category'];
    }
    //$this->log($status, false);
    return $status;
  }

  private function constructRedirects($pageData)
  {
    $redirects = array(
      '/?id=' . $pageData['uid']
    );
    //TODO: Add a single \r to match old Macs line breaks?
    foreach (preg_split('/\n|\r\n?/', $pageData['redirects']) as $redir) {
      $redir = trim($redir);
      if ($redir == '') continue;
      $redirects[] = $redir;
    }
    return $redirects;
  }

  private function convertStringToTechnicalName($string)
  {
    $string = $this->sanitizeString($string);
    $string = preg_replace('/-/', '', $string);
    return strtoupper($string);
  }

  private function sanitizeString($string)
  {
    $table = array(
      'Š' => 'S', 'š' => 's', 'Đ' => 'Dj', 'đ' => 'dj', 'Ž' => 'Z', 'ž' => 'z', 'Č' => 'C', 'č' => 'c', 'Ć' => 'C', 'ć' => 'c',
      'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'AE', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
      'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O',
      'Õ' => 'O', 'Ö' => 'OE', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'UE', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss',
      'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'ae', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e',
      'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o',
      'ô' => 'o', 'õ' => 'o', 'ö' => 'oe', 'ø' => 'o', 'ü' => 'ue', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y',
      'þ' => 'b', 'ÿ' => 'y', 'Ŕ' => 'R', 'ŕ' => 'r', '/' => ''
    );

    $x = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $string);
    $x = trim(strtr($x, $table));
    $x = preg_replace('/[^A-Za-z0-9]+/', ' ', $x);
    $x = trim($x);
    $x = preg_replace('/ {1,}/', '-', $x);
    $x = trim($x, "-");
    return $x;
  }

  private function constructSlug($pid)
  {
    $postStatement = $this->pageQueryBuilder
      ->select('slug')
      ->from('pages')
      ->setMaxResults(1)
      ->where(
        $this->pageQueryBuilder->expr()->eq('uid', $this->pageQueryBuilder->createNamedParameter($pid))
      )
      ->execute();

    $postSlug = $postStatement->fetchAll();
    $postSlug = $postSlug[0];
    return $postSlug ? $postSlug["slug"] : null;
  }

  private function constructBreadCrumb($rootline, $page, $pageType)
  {
    $breadCrumb = $this->createContentElement('breadcrumbs');
    foreach ($rootline as $post) {
      if ($post['doktype'] == 254) continue;
      if ($post['is_siteroot'] == 1) continue;
      if ($page['uid'] == $post['uid'] && ($pageType == "blogger-page" || $pageType == "video-page"))
        $tit = $post['title'];
      else
        if ($post['use_roof_as_breadcrumb_text'] == 0)
        $tit = $post['title'];
      else
        $tit = $post['roof'] && $post['roof'] != '' ? $post['roof'] : $post['title'];
      $breadCrumb['subElements'][] = $this->createContentElement(
        'breadcrumblink',
        array(
          'title' => $tit,
          'alt' => $tit,
          'text' => $tit,
          'href' => $this->constructSlug($post['uid'])
        )
      );
    }
    return $breadCrumb;
  }

  private function processData($dbReference, &$processedData, &$processedImages)
  {
    $isSidebar = $dbReference['colPos'] == 1;
    if ($isSidebar)
      $subs = &$processedData['pageData']['sidebar']['subElements'];
    else
      $subs = &$processedData['pageData']['content']['subElements'];

    $ffs = GeneralUtility::makeInstance(FlexFormService::class);
    $flex = $ffs->convertFlexFormContentToArray($dbReference['pi_flexform']);

    // print_r($flex);
    // die();

    switch ($dbReference['CType']) {
      case "mrm_be_cm_postimage":
        break;
      case "mrm_be_cm_voting":
        $s = $this->createContentElement(
          "voting",
          array(
            "labels" => array(
              "startbutton" => $flex["startbuttontext"],
            ),
            "resultscreen" => array(
              "headingTop" => $flex["resultheadingtop"],
            ),
          ),
          array(
            "items" => array(array(
              "text" => $flex["questiontext"],
              "type" => $flex["questiontype"] == "1" || $flex["questiontype"] == 1 ? "multi" : "single",
              "answers" => array_values(array_map(function ($x) {
                return array("text" => $x["settings"]["answer"]["text"], "value" => null);
              }, $flex["dynamicComponents"]))
            )),
            "validation" => array(
              "alreadyVoted" => $this->createContentElement("injection", array("type" => "voting-alreadyVoted")),
              "chartData" => $this->createContentElement("injection", array("type" => "voting-chartData|")),
            ),
          )
        );
        $cntr = 0;
        foreach ($s["attributes"]["items"][0]["answers"] as &$a) {
          $a["value"] = $cntr;
          $cntr++;
        }
        $s["attributes"]["validation"]["chartData"]["props"]["type"] .= $cntr;
        $processedData["injections"][] = "voting-alreadyVoted";
        $processedData["injections"][] = "voting-chartData|" . $cntr;
        $subs[] = $s;
        $processedData["status"]["hasVoting"] = true;
        break;
      case "mrm_be_cm_checklist-todo":
        $elements = $this->createContentElement(
          "checklist-todo",
          array(
            "headlines" => array(
              "main" => $flex["headline_main"],
              "done" => $flex["headline_done"],
              "not_done" => $flex["headline_not_done"],
            ),
            "controls" => array(
              "print" => $flex["enable_print"] == "1",
              "pdf" => $flex["enable_pdf"] == "1",
            ),
            "labels" => array(
              "submit" => $flex["label_submit"],
              "print" => $flex["label_print"],
              "pdf" => $flex["label_pdf"],
            ),
            "items" => (function ($flex, $dbReference) {
              $itms = array();
              $imgs = array();
              if ($flex["images"] != "0" && $flex["images"] != 0) {
                $imgs = $this->processImagesTTContent($dbReference, 'mrm_be_cm_contentimage', 'tt_content', 'image', 'uid', true, true);
              }
              foreach ($flex["items"] as $itm) {
                $i = $itm["item"];
                $a = array();
                if ($i["text"] != "") $a["text"] = $i["text"];
                if ($i["contains_image"] == "1" || $i["contains_image"] == 1) {
                  $im = array_shift($imgs);
                  if (isset($im)) $a["img"] = $im;
                }
                $itms[] = $a;
              }
              return $itms;
            })($flex, $dbReference),
          )
        );
        $subs[] = $elements;
        $processedData["status"]["hasChecklist"] = true;
        break;
      case "mrm_be_cm_checklist_todo_multi":
        $elements = $this->createContentElement(
          'checklist-todo-multi',
          array(
            "texts" => array(
              "mainhead" => $flex['mainhead'],
              "description" =>  $flex['description'],
            ),
            "controls" => array(
              "print" => $flex["enable_print"] == "1",
              "pdf" => $flex["enable_pdf"] == "1",
            ),
            "labels" => array(

              "print" => $flex["label_print"],
              "pdf" => $flex["label_pdf"],
            ),
            "items" => (function ($flex) {
              $itms  = [];
              $a = array();
              foreach ($flex['items'] as $itm) {

                if (is_array($itm)) {
                  $a['head'] = $itm['item']['head'];
                  $list = $itm['item']['list'];

                  $doc = new \DOMDocument('1.0', 'utf-8');
                  $doc->loadHTML('<?xml encoding="UTF-8">' . $list);
                  $listitems = $doc->getElementsByTagName('li');

                  $list = [];
                  foreach ($listitems as $node) {
                    foreach ($node->childNodes as $child) {
                      $list[] = array('text' => $child->nodeValue);
                    }
                    $a['items'] = $list;
                  }
                }
                $itms[] = $a;
              }
              return $itms;
            })($flex),
          ),
        );
        $subs[] = $elements;
        break;

      case "mrm_be_cm_checklist-input":
        $items = array();
        $dynContentCounter = 0;
        while (true) {
          $dynContentCounter++;
          if (!isset($flex["label" . $dynContentCounter])) break;
          if ($flex["label" . $dynContentCounter] === "") continue;
          $label = array(
            "label" => $flex["label" . $dynContentCounter]
          );
          $items[] = $label;
        }
        $elements = $this->createContentElement(
          "checklist-input",
          array(
            "headlines" => array(
              "main" => $flex["headline_main"],
              "results" => $flex["headline_result"],
            ),
            "intro" => $flex["intro"],
            "controls" => array(
              "print" => $flex["enable_print"] == "1",
              "pdf" => $flex["enable_pdf"] == "1",
            ),
            "labels" => array(
              "submit" => $flex["label_submit"],
              "print" => $flex["label_print"],
              "pdf" => $flex["label_pdf"],
            ),
            "items" => $items,
          )
        );
        $subs[] = $elements;
        $processedData["status"]["hasChecklist"] = true;
        break;
      case "mrm_be_cm_checklist-scale":
        $items = array();
        $dynContentCounter = 0;
        while (true) {
          $dynContentCounter++;
          if (!isset($flex["label" . $dynContentCounter])) break;
          if ($flex["label" . $dynContentCounter] === "") continue;
          $label = array(
            "label" => $flex["label" . $dynContentCounter]
          );
          $items[] = $label;
        }
        $elements = $this->createContentElement(
          "checklist-scale",
          array(
            "headlines" => array(
              "main" => $flex["headline_main"],
              "results" => $flex["headline_result"],
            ),
            "intro" => $flex["intro"],
            "maxPoints" => (int)$flex["maxpoints"],
            "controls" => array(
              "print" => $flex["enable_print"] == "1",
              "pdf" => $flex["enable_pdf"] == "1",
            ),
            "labels" => array(
              "nextbutton" => $flex["label_nextbutton"],
              "lastbutton" => $flex["label_lastbutton"],
              "print" => $flex["label_print"],
              "pdf" => $flex["label_pdf"],
            ),
            "items" => $items,
          )
        );
        $subs[] = $elements;
        $processedData["status"]["hasChecklist"] = true;
        break;
      case "mrm_be_cm_checklist-radiorange":
        $items = array();
        $dynContentCounter = 0;
        while (true) {
          $dynContentCounter++;
          if (!isset($flex["pointsFrom" . $dynContentCounter])) break;
          if ($flex["pointsFrom" . $dynContentCounter] === "") continue;
          $item = array(
            "pointsFrom" => (int)$flex["pointsFrom" . $dynContentCounter],
            "pointsTo" => (int)$flex["pointsTo" . $dynContentCounter],
            "validationText" => $flex["validationText" . $dynContentCounter]
          );
          if ($flex["image" . $dynContentCounter] == 1) {
            $images = $this->processImagesTTContent($dbReference, 'mrm_be_cm_checklist-radiorange', 'tt_content', 'flex_image_' . $dynContentCounter, 'uid', false, true);
            $images = $images[0];
            $images["src"] = $images["sources"]["img"];
            unset($images["sources"]);
            $item["img"] = $images;
          }
          $items[] = $item;
        }
        $elements = $this->createContentElement(
          "checklist-radiorange",
          array(
            "headlines" => array(
              "main" => $flex["headline_main"],
            ),
            "intro" => $flex["intro"],
            "validation" => array(
              "maxPoints" => (int)$flex["maxpoints"],
              "items" => $items,
            )
          )
        );
        $subs[] = $elements;
        $processedData["status"]["hasChecklist"] = true;
        break;
      case "mrm_be_cm_checklist-yesmaybeno":
        $items = array();
        foreach ($flex["dynamicComponents"] as $component) {
          foreach ($component as $key => $value) {
            $item = array(
              "heading" => $value["headline"],
              "text" => $value["text"]
            );
          }
          if ($item) {
            $items[] = $item;
          }
          unset($value);
        }
        $choices = array();
        $choice_yes = array(
          "label" => $flex["choice_value_yes"],
          "value" => "yes"
        );
        $choice_maybe = array(
          "label" => $flex["choice_value_maybe"],
          "value" => "maybe"
        );
        $choice_no = array(
          "label" => $flex["choice_value_no"],
          "value" => "no"
        );
        $choices[] = $choice_yes;
        $choices[] = $choice_maybe;
        $choices[] = $choice_no;
        $elements = $this->createContentElement(
          "checklist-yesmaybeno",
          array(
            "headlines" => array(
              "main" => $flex["headline_main"],
              "results" => $flex["headline_result"],
            ),
            "intro" => $flex["intro"],
            "controls" => array(
              "print" => $flex["enable_print"] == "1",
              "pdf" => $flex["enable_pdf"] == "1",
            ),
            "labels" => array(
              "nextbutton" => $flex["label_nextbutton"],
              "lastbutton" => $flex["label_lastbutton"],
              "print" => $flex["label_print"],
              "pdf" => $flex["label_pdf"],
            ),
            "choices" => $choices,
            "items" => $items,
          )
        );
        $subs[] = $elements;
        $processedData["status"]["hasChecklist"] = true;
        break;
      case "mrm_be_cm_picturechoice":
        $s = $this->createContentElement(
          "picturechoice",
          array(
            "labels" => array(
              "startbutton" => $flex["startbuttontext"],
              "nextbutton" => $flex["nextbuttontext"],
              "lastbutton" => $flex["lastbuttontext"],
              "question" => $flex["question"],
              "repeatbutton" => $flex["repeatbuttontext"],
            ),
            "resultscreen" => array(
              "headingTop" => $flex["resultheadingtop"],
              "end" => $flex["thanks"]
            ),
            "isRestartAble" => $flex["isRestartAble"] == 1 || $flex["isRestartAble"] == "1",
          ),
          array(
            "items" => (function ($flex, $dbReference) {
              $ret = array();
              for ($i = 1; $i <= 3; $i++) {
                $item = array();
                for ($j = 1; $j <= 5; $j++) {
                  if ($flex["image" . $i . "_" . $j] == "1") {
                    $img = $this->processImagesTTContent($dbReference, 'mrm_be_cm_picturechoice', 'tt_content', 'flex_image_' . $i . "_" . $j, 'uid', false, true);
                    $img = $img[0];
                    $item[] = array(
                      "image" => $img,
                      "points" => (int) $flex["pointsOfImage" . $i . "_" . $j]
                    );
                  }
                }
                if (sizeof($item) > 0)
                  $ret[] = $item;
              }
              return $ret;
            })($flex, $dbReference),
            "validation" => array(
              "maxPoints" => (int)$flex["maxpoints"],
              "alreadyReachedPoints" => $this->createContentElement("injection", array("type" => "picturechoice-alreadyReachedPoints")),
              "items" => array_map(
                function ($i) {
                  $i["validationText"] = $this->checkTextForInternalLinks($i["validationText"], $dbReference, $processedData);
                  $i["pointsFrom"] = (int)$i["pointsFrom"];
                  $i["pointsTo"] = (int)$i["pointsTo"];
                  return $i;
                },
                array_filter(array_values(array_map(function ($v) {
                  return $v['settings']['validation'];
                }, $flex["validations"])), function ($x) {
                  return $x != null;
                })
                //TODO: Core: Error handler (BE): PHP Warning: array_filter() expects parameter 1 (or 2 in another error message) to be array, null given in /var/www/html/typo3conf/ext/mrm_be/Classes/Hooks/TCE/TCEMainHook.php line 830
              ),
            ),
          )
        );
        $processedData["injections"][] = "picturechoice-alreadyReachedPoints";
        $subs[] = $s;
        $processedData["status"]["hasPicturechoice"] = true;
        break;
      case "mrm_be_cm_quiz":
        $s = $this->createContentElement(
          "quiz",
          array(
            "labels" => array(
              "startbutton" => $flex["startbuttontext"],
              "nextbutton" => $flex["nextbuttontext"],
              "lastbutton" => $flex["lastbuttontext"],
              "question" => $flex["question"],
              "repeatbutton" => $flex["repeatbuttontext"],
            ),
            "resultscreen" => array(
              "headingTop" => $flex["resultheadingtop"],
              "headingSub" => $flex["resultheadingsub"],
              "validation" => $flex["validationstr"],
              "end" => $flex["thanks"]
            ),
            "isRestartAble" => $flex["isRestartAble"] == 1 || $flex["isRestartAble"] == "1",
          ),
          array(
            "items" => array_values(array_map(function ($v) {
              $questionType = null;
              $quest = $v['settings']['question'];
              if (!isset($quest)) {
                $quest = $v['settings']['question_multi'];
                $questionType = "multi";
              }
              if (isset($quest["additional_text"]) && $quest["additional_text"] != "") {
                $quest["text"] = $quest["text"] . " (" . $quest["additional_text"] . ")";
                unset($quest["additional_text"]);
              }
              if ($questionType) $quest["type"] = $questionType;
              unset($quest["rightanswer"]);
              $i = 0;
              $quest["answers"] = array();
              while (1) {
                $i++;
                if (!isset($quest["answertext" . $i])) break;
                if ($quest["answertext" . $i] === "") continue;
                $quest["answers"][] = array("text" => $quest["answertext" . $i],  "points" => (int)$quest["answerpoints" . $i]);
                unset($quest["answertext" . $i]);
                unset($quest["answerpoints" . $i]);
              }
              /* NOTE: DEPRECATED BY SINGLE INPUTS
              $quest["answers"] = array_map(function($x) {
                $x = explode("|", $x);
                $x = array("text" => $x[0], "points" => (int)$x[1]);
                return $x;
              }, explode("\n", $quest["answers"]));
              */
              return $quest;
            }, $flex["dynamicComponents"])),
            "validation" => array(
              "maxPoints" => (int)$flex["maxpoints"],
              "averagePoints" => $this->createContentElement("injection", array("type" => "quiz-averagePoints")),
              "alreadyReachedPoints" => $this->createContentElement("injection", array("type" => "quiz-alreadyReachedPoints")),
              "items" => array_map(
                function ($i) {
                  $i["validationText"] = $this->checkTextForInternalLinks($i["validationText"], $dbReference, $processedData);
                  return $i;
                },
                array_filter(array_values(array_map(function ($v) {
                  return $v['settings']['validation'];
                }, $flex["dynamicComponents2"])), function ($x) {
                  return $x != null;
                })
              ),
            ),
          )
        );
        $processedData["injections"][] = "quiz-averagePoints";
        $processedData["injections"][] = "quiz-alreadyReachedPoints";
        $subs[] = $s;
        $processedData["status"]["hasQuiz"] = true;
        break;
      case "mrm_be_cm_animation":
        $script = $flex["script"];
        if ($flex["staticfiles"] != "0" && $flex["staticfiles"] != 0) {
          $imgs = $this->processImagesTTContent($dbReference);
          foreach ($imgs as $idx => $v) {
            $script = implode("#cdnurl#/" . $v["sources"]["passthru"], explode("%ASSET_" . ($idx + 1) . "%", $script));
          }
        }
        $subs[] = $this->createContentElement("animation", array("addJQuery" => $flex["addJQuery"] == 1 || $flex["addJQuery"] == "1"), array("script" => $script));
        $processedData["status"]["hasAnimation"] = true;
        break;
      case "mrm_be_cm_injection":
        $subs[] = $this->createContentElement("injection", array("type" => $flex["text"]));
        $processedData["injections"][] = $flex["text"];
        break;
      case "mrm_be_cm_roof":
        $subs[] = $this->createContentElement("roof", array(), array("text" => $flex["text"]));
        break;
      case "mrm_be_cm_h1":
        $subs[] = $this->createContentElement("h1", array(), array("text" => $flex["text"]));
        break;
      case "mrm_be_cm_h2":
        $subs[] = $this->createContentElement("h2", array(), array("text" => $flex["text"]));
        break;
      case "mrm_be_cm_h3":
        $subs[] = $this->createContentElement("h3", array(), array("text" => $flex["text"]));
        break;
      case "mrm_be_cm_introtext":
        $text = preg_replace("/\n/", "<br />", $flex["text"]);
        $subs[] = $this->createContentElement("introtext", array(), array("text" => $text));
        break;
      case "mrm_be_cm_button":
        $href = $this->parseFlexFormLink($flex["button"], $dbReference, $processedData);
        $buttonType = ($flex['buttonType'] == "0") ? 'button-link' : 'button-scream';
        $button = $this->createContentElement("button", array('buttonType' => $buttonType), array("text" => $flex["text"], "href" => $href["href"], "target" => $href["target"]));
        $subs[] = $button;
        break;
      case "mrm_be_cm_html":
        $subs[] = $this->createContentElement("html", array(), array("text" => $flex["html"]));
        break;
      case "mrm_be_cm_heroimage":
        $props = $this->processImagesTTContent($dbReference)[0];
        $props["type"] = "typo3_hero";
        $subs[] = $this->createContentElement("image", $props);
        break;
      case "mrm_be_cm_contentimage":
        $props = $this->processImagesTTContent($dbReference)[0];
        $props["type"] = "typo3_content";
        $subs[] = $this->createContentElement("image", $props);
        break;
      case "mrm_be_cm_publication":
        $imgprops = $this->processImagesTTContent($dbReference, 'mrm_be_cm_publication')[0];
        $imgprops["type"] = "typo3_publication";
        $publication = $this->createContentElement(
          "publication",
          array(
            "starttime" => $this->startOfDay($flex['starttime']),
            "endtime" => $this->endOfDay($flex['endtime']),
            "issuekey" => $flex['issuekey'],
          ),
          array(
            "image" => $imgprops,
            "number" => $flex["issuenumber"],
            "title" => $flex["issuetitle"],
            "headline" => $flex["issueheadline"],
            "link" => $this->parseFlexFormLink($flex["htmllink"], $dbReference, $processedData),
            "pdf" => $this->parseFlexFormLink($flex["pdflink"], $dbReference, $processedData),
          )
        );
        $subs[] = $publication;
        break;
      case "mrm_be_cm_rawimage":
        $props = $this->processImagesTTContent($dbReference)[0];
        $props["type"] = "typo3_raw";
        $subs[] = $this->createContentElement("image", $props);
        break;
      case "mrm_be_cm_movingimagesvideo":
        $subs[] = $this->createContentElement(
          "movingimagesvideo",
          array(
            "hasNoticeForCrossPromotion" => $flex["hasNoticeForCrossPromotion"] == 1,
            "hasNoticeForAccessibility" => $flex["hasNoticeForAccessibility"] == 1
          ),
          array("vid" => $flex["vid"])
        );
        break;
      case "mrm_be_cm_paragraph":
        $elements = $this->checkText($flex["text"], $dbReference, $processedData, "typo3_paragraph");
        $subs = array_merge($subs, $elements);
        break;
      case "mrm_be_cm_additionalinfobox":
      case "mrm_be_cm_infobox":
      case "mrm_be_cm_extra_infosbox":

        $type = null;
        $open = null;
        $noAutoOpen = null;
        if ($dbReference['CType'] == "mrm_be_cm_additionalinfobox") $type = "typo3_additionalinfobox";
        elseif ($dbReference['CType'] == "mrm_be_cm_infobox") $type = "typo3_infobox";
        else $type = "typo3_extrainfosbox";

        if ($dbReference['CType'] == "mrm_be_cm_additionalinfobox" || $dbReference['CType'] == "mrm_me_cm_extra_infosbox") $open = true;
        else $open = $flex["isInitialyOpen"] == "1";

        if ($dbReference['CType'] == "mrm_be_cm_additionalinfobox" || $dbReference['CType'] == "mrm_be_cm_infobox") $headline = $flex["headline"];
        elseif ($dbReference['CType'] == "mrm_be_cm_extra_infosbox") $headline = '';
        $this->log('Headline: ' . $headline, true);

        $sub = $this->createContentElement(
          $type,
          array("open" => $open, "noAutoOpen" => $flex["noAutoOpen"] == 1),
          array("headline" => $flex["headline"])
        );

        if ($flex["image"] == "1") {
          $props = $this->processImagesTTContent($dbReference, "mrm_be_cm_contentimage")[0];
          $props["type"] = "typo3_content";
          $sub["subElements"][] = $this->createContentElement("image", $props);
        } else {
          switch ($flex["icon"]) {
            case "1":
              $sub["attributes"]["icon"] = "stadtinfo_basics";
              break;
            case "2":
              $sub["attributes"]["icon"] = "geschichte";
              break;
            case "3":
              $sub["attributes"]["icon"] = "kultur_freizeit";
              break;
            case "4":
              $sub["attributes"]["icon"] = "besonderheiten";
              break;
            case "5":
              $sub["attributes"]["icon"] = "kosten_geld";
              break;
            case "6":
              $sub["attributes"]["icon"] = "hochschulen";
              break;
            case "7":
              $sub["attributes"]["icon"] = "studieren";
              break;
          }
        }

        if ($flex["dynamicComponents"] && sizeof($flex["dynamicComponents"]) > 0)
          foreach ($flex["dynamicComponents"] as $comp) {
            $stype = array_keys($comp['settings'])[0];
            $elements = [];
            switch ($stype) {
              case "box":
                $box = $this->createContentElement("boxwrapper");
                $box["subElements"] = array_merge($box["subElements"], $this->checkText($comp['settings']['box']['boxheadline'], $dbReference, $processedData, "h3"));
                $box["subElements"] = array_merge($box["subElements"], $this->checkText($comp['settings']['box']['boxtext'], $dbReference, $processedData, "typo3_paragraph"));
                $elements = [$box];
                break;
              case "boxheadline":
                $elements = $this->checkText($comp['settings'][$stype][$stype], $dbReference, $processedData, "h3");
                //$this->log($elements, false);
                break;
              case "boxtext":
                $elements = $this->checkText($comp['settings'][$stype][$stype], $dbReference, $processedData, "typo3_paragraph");
                break;
              case "html":
                $elements = $this->checkText($comp['settings'][$stype][$stype], $dbReference, $processedData, "html");
                break;
            }
            $sub["subElements"] = array_merge($sub["subElements"], $elements);
            $this->log($sub["subElements"], false);
          }
        $subs[] = $sub;
        break;
      case "mrm_be_cm_foldout":
        $sub = $this->createContentElement("typo3_foldout", array("open" => $flex["isInitialyOpen"] == "1", "noAutoOpen" => $flex["noAutoOpen"] == "1"), array("headline" => $flex["headline"]), array());

        if ($flex["image"] == "1") {
          $props = $this->processImagesTTContent($dbReference, "mrm_be_cm_contentimage")[0];
          $props["type"] = "typo3_content";
          $sub["subElements"][] = $this->createContentElement("image", $props);
        } else {
          switch ($flex["icon"]) {
            case "1":
              $sub["attributes"]["icon"] = "stadtinfo_basics";
              break;
            case "2":
              $sub["attributes"]["icon"] = "geschichte";
              break;
            case "3":
              $sub["attributes"]["icon"] = "kultur_freizeit";
              break;
            case "4":
              $sub["attributes"]["icon"] = "besonderheiten";
              break;
            case "5":
              $sub["attributes"]["icon"] = "kosten_geld";
              break;
            case "6":
              $sub["attributes"]["icon"] = "hochschulen";
              break;
            case "7":
              $sub["attributes"]["icon"] = "studieren";
              break;
          }
        }

        if ($flex["dynamicComponents"] && sizeof($flex["dynamicComponents"]) > 0)
          foreach ($flex["dynamicComponents"] as $comp) {
            $stype = array_keys($comp['settings'])[0];
            $elements = $this->checkText($comp['settings'][$stype][$stype], $dbReference, $processedData, $stype == "paragraph" ? "typo3_paragraph" : ($stype == "headline" ? "h3" : $stype));
            $sub["subElements"] = array_merge($sub["subElements"], $elements);
          }
        $subs[] = $sub;
        break;
      case "mrm_be_cm_newsletterabo":
        $newsletterabo = $this->createContentElement("newsletterabo", array("cr_url" => $flex["cr_url"], "cr_url_BIZ" => $flex["cr_url_BIZ"]));
        $subs[] = $newsletterabo;
        break;
      case "mrm_be_cm_linkage":
        $subs[] = $this->createContentElement("sidebarheadline", array(), array("text" => $flex['headline']));
        $banners = $this->createContentElement("sidebarbanners");
        if ($flex['dynamicComponents'] && sizeof($flex['dynamicComponents']) > 0)
          foreach ($flex['dynamicComponents'] as $banner) {
            $banners["subElements"][] = $this->createContentElement("banner", $this->parseFlexFormLink($banner["settings"]["link"]["link"], $dbReference, $processedData));
          }
        $subs[] = $banners;
        $subs[] = $this->createContentElement("injection", array("type" => "rubrik_content"));
        $processedData["injections"][] = "rubrik_content";

        $berufenet = $this->createContentElement("sidebarexternallinks", array("type" => "berufenet"), array("items" => []));
        if ($flex['dynamicComponentsBerufeNet'] && sizeof($flex['dynamicComponentsBerufeNet']) != 0)
          foreach ($flex['dynamicComponentsBerufeNet'] as $itm) {
            $link = $this->parseFlexFormLink($itm["settings"]["link"]["link"], $dbReference, $processedData);
            $link = '<a href="' . $link['href'] . '" target="' . $link['target'] . '" aria-label="Externer Link">' . $link['alt'] . '</a>';
            $berufenet["attributes"]["items"][] = $link;
          }
        if (sizeof($berufenet["attributes"]["items"]) > 0) $subs[] = $berufenet;

        $berufetv = $this->createContentElement("sidebarexternallinks", array("type" => "berufetv"), array("items" => []));
        if ($flex['dynamicComponentsBerufeTV'] && sizeof($flex['dynamicComponentsBerufeTV']) != 0)
          foreach ($flex['dynamicComponentsBerufeTV'] as $itm) {
            $link = $this->parseFlexFormLink($itm["settings"]["link"]["link"], $dbReference, $processedData);
            $link = '<a href="' . $link['href'] . '" target="' . $link['target'] . '" aria-label="Externer Link">' . $link['alt'] . '</a>';
            $berufetv["attributes"]["items"][] = $link;
          }
        if (sizeof($berufetv["attributes"]["items"]) > 0) $subs[] = $berufetv;

        $berufsausbildung = $this->createContentElement("sidebarexternallinks", array("type" => "berufsausbildung"), array("items" => []));
        if ($flex['dynamicComponentsBerufsausbildung'] && sizeof($flex['dynamicComponentsBerufsausbildung']) != 0)
          foreach ($flex['dynamicComponentsBerufsausbildung'] as $itm) {
            $link = $this->parseFlexFormLink($itm["settings"]["link"]["link"], $dbReference, $processedData);
            $link = '<a href="' . $link['href'] . '" target="' . $link['target'] . '" aria-label="Externer Link">' . $link['alt'] . '</a>';
            $berufsausbildung["attributes"]["items"][] = $link;
          }
        if (sizeof($berufsausbildung["attributes"]["items"]) > 0) $subs[] = $berufsausbildung;

        $ba_search = $this->createContentElement("sidebarexternallinks", array("type" => "ba_search"), array("items" => []));
        if ($flex['dynamicComponentsBASearch'] && sizeof($flex['dynamicComponentsBASearch']) != 0)
          foreach ($flex['dynamicComponentsBASearch'] as $itm) {
            $link = $this->parseFlexFormLink($itm["settings"]["link"]["link"], $dbReference, $processedData);
            $link = '<a href="' . $link['href'] . '" target="' . $link['target'] . '" aria-label="Externer Link">' . $link['alt'] . '</a>';
            $ba_search["attributes"]["items"][] = $link;
          }
        if (sizeof($ba_search["attributes"]["items"]) > 0) $subs[] = $ba_search;

        $studienwahl = $this->createContentElement("sidebarexternallinks", array("type" => "studienwahl"), array("items" => []));
        if ($flex['dynamicComponentsStudienwahl'] && sizeof($flex['dynamicComponentsStudienwahl']) != 0)
          foreach ($flex['dynamicComponentsStudienwahl'] as $itm) {
            $link = $this->parseFlexFormLink($itm["settings"]["link"]["link"], $dbReference, $processedData);
            $link = '<a href="' . $link['href'] . '" target="' . $link['target'] . '" aria-label="Externer Link">' . $link['alt'] . '</a>';
            $studienwahl["attributes"]["items"][] = $link;
          }
        if (sizeof($studienwahl["attributes"]["items"]) > 0) $subs[] = $studienwahl;

        if ($flex['enable_check_u']) {
          $check_u = $this->createContentElement("extimgbutton", array("ariaLabel" => "Zur Check-U-Website", "href" => "https://www.arbeitsagentur.de/bildung/welche-ausbildung-welches-studium-passt", "target" => "_blank"), array("imgsrc" => "/public/media/ext-link_check_u.png"));
          $subs[] = $check_u;
        }

        if ($flex['enable_studiencheck']) {
          $studiencheck = $this->createContentElement("extimgbutton", array("ariaLabel" => "Zur Studiencheck-Website", "href" => "https://studiencheck.de/", "target" => "_blank"), array("imgsrc" => "/public/media/ext-link_studiencheck.png"));
          $subs[] = $studiencheck;
        }

        break;
      case "mrm_be_cm_homeheaderinfo":
        $items = array();
        for ($i = 1; $i <= 3; $i++) {
          if ($flex["headline" . $i] != "" && $flex["text" . $i] != "") {
            $item = array("heading" => $flex["headline" . $i], "text" => $flex["text" . $i]);
            if ($flex["link" . $i] != "") {
              $link = $this->parseFlexFormLink($flex["link" . $i], $dbReference, $processedData);
              $item["href"] = $link["href"];
              $item["linkTarget"] = $link["target"];
            }
            if ($flex["image" . $i] == "1") {
              $imgs = $this->processImagesTTContent($dbReference, 'mrm_be_cm_homeheaderinfo', 'tt_content', 'flex_image_' . $i, 'uid', false);
              $item["image"] = "#cdnurl#/" . $imgs[0]["sources"][$flex["imagesize" . $i]];
            }
            $items[] = $item;
          }
        }
        $subs[] = $this->createContentElement("abimessages", array("data" => $items));
        break;
      case "mrm_be_cm_tileoverview":
        $items = array();
        for ($i = 1; $i <= 8; $i++) {
          if ($flex["link" . $i] == "") continue;
          $item = array();
          $link = $this->parseFlexFormLink($flex["link" . $i], $dbReference, $processedData);
          $item["href"] = $link["href"];
          $item["linkTarget"] = $link["target"];
          $item["text"] = $link["alt"];
          if ($flex["image" . $i] == "1") {
            $imgs = $this->processImagesTTContent($dbReference, 'mrm_be_cm_tileoverview', 'tt_content', 'flex_image_' . $i, 'uid', false);
            $item["image"] = "#cdnurl#/" . $imgs[0]["sources"]["default_hero_lte600"];
          }
          $items[] = $item;
        }
        $subs[] = $this->createContentElement("tileoverview", array("items" => $items));
        break;
      case "mrm_be_cm_highlightbox":
        $elements = $this->checkText($flex["text"], $dbReference, $processedData, "typo3_paragraph");
        $subs[] = $this->createContentElement("highlightbox", array("icon" => $flex["icon"]), array(), $elements);
        break;
      case "mrm_be_cm_statementbox":
        $items = array();
        $dynContentCounter = 0;
        while (1) {
          $dynContentCounter++;
          if (!isset($flex['text' . $dynContentCounter])) break;
          if ($flex['text' . $dynContentCounter] === '' || $flex['name' . $dynContentCounter] === '') continue;
          $item = array(
            'quote' => $flex['text' . $dynContentCounter],
            'cite' => $flex['name' . $dynContentCounter]
          );
          if ($flex['image' . $dynContentCounter] == 1) {
            $imgs = $this->processImagesTTContent($dbReference, 'mrm_be_cm_statementbox', 'tt_content', 'flex_image_' . $dynContentCounter, 'uid', false);
            $imgs = $imgs[0];
            $imgs['src'] = "#cdnurl#/" . $imgs['sources']['img'];
            unset($imgs['sources']);
            $item['img'] = $imgs;
          }
          $items[] = $item;
        }
        $subs[] = $this->createContentElement('statementbox', array('items' => $items));
        break;
      case "mrm_be_cm_explorerbox":
        $items = array();
        $dynContentCounter = 0;
        while (1) {
          $dynContentCounter++;
          if (!isset($flex['head' . $dynContentCounter])) break;
          if ($flex['head' . $dynContentCounter] === '' || $flex['claim' . $dynContentCounter] === '' || $flex['image' . $dynContentCounter] == 0) continue;
          $item = array(
            'heading' => $flex['head' . $dynContentCounter],
            'subheading' => $flex['claim' . $dynContentCounter],
            'text' => $flex['text' . $dynContentCounter]
          );
          if ($flex['image' . $dynContentCounter] == 1) {
            $imgs = $this->processImagesTTContent($dbReference, 'mrm_be_cm_explorerbox', 'tt_content', 'flex_image_' . $dynContentCounter, 'uid', false);
            $imgs = $imgs[0];
            $imgs['src'] = "#cdnurl#/" . $imgs['sources']['img'];
            unset($imgs['sources']);
            $item['img'] = $imgs;
          }
          if ($flex['link' . $dynContentCounter] !== '') {
            $button = $this->parseFlexFormLink($flex['link' . $dynContentCounter], $dbReference, $processedData);
            $item['button'] = $button;
          }
          $items[] = $item;
        }
        $subs[] = $this->createContentElement('explorerbox', array('items' => $items));
        break;
      case "mrm_be_cm_dynamic_tileoverview":
        $items = array();
        foreach ($flex["dynamicComponents"] as $comp) {
          foreach ($comp as $k => $v) {
            $itm = null;
            switch ($k) {
              case "links":
                $lnk = $this->parseFlexFormLink($v["link"], $dbReference, $processedData);
                $itm = $this->createContentElement("tile_default", array("link" => $lnk, "coloured" => $v["coloured"] == 1, "allowed" => preg_split('/\+/', $v["type"]), "format" => $v["format"]));
                if ($lnk["alt"]) $itm["props"]["headline"] = $lnk["alt"];
                break;
              case "buttons":
                $itm = $this->createContentElement(
                  "tile_content",
                  array(
                    "headline" => $v["headline"],
                    "content" => $this->checkTextForInternalLinks($v["buttons"], $dbReference, $processedData)
                  )
                );
                break;
              case "icons":
                $lnk = $this->parseFlexFormLink($v["link"], $dbReference, $processedData);
                $itm = $this->createContentElement("tile_icon", array("link" => $lnk, "icon" => $v["icon"]), array());
                if ($lnk["alt"]) $itm["props"]["headline"] = $lnk["alt"];
                break;
              case "flat":
                $lnk = $this->parseFlexFormLink($v["link"], $dbReference, $processedData);
                $itm = $this->createContentElement("tile_flat", array("link" => $lnk));
                if ($lnk["alt"]) $itm["props"]["headline"] = $lnk["alt"];
                break;
              case "injections":
                $itm = $this->createContentElement("injection", array("type" => $v["text"]));
                $processedData["injections"][] = $v["text"];
                break;
            }
            if ($itm)
              $items[] = $itm;
          }
        }
        $dto = $this->createContentElement('dynamic_tileoverview', array(), array(), $items);
        if ($flex["cssClass"] && $flex["cssClass"] !== "")
          $dto["attributes"]["cssClassName"] = $flex["cssClass"];
        $subs[] = $dto;
        $processedData["status"]["hasDynamicTileOverview"] = true;
        break;
      case "mrm_be_cm_podcast":
        //$items = array();
        if ($flex['media'] == "1")
          $media = $this->processAudio($dbReference, 'mrm_be_cm_podcast', 'tt_content', 'media', 'uid', true, true);

        if ($flex['transcript'])
          $transcript = $flex['transcript'];
        $subs[] = $this->createContentElement('podcast', array(), array('media' => $media, 'transcript' => $transcript));
        break;
      case "mrm_be_cm_imageplus":
        $props = $this->processImagesTTContent($dbReference)[0];
        $props["type"] = "imageplus";
        $props["headline"] = $flex['headline'] ?? '';
        $props["description"] = $flex['description'] ?? '';
        $props["link"] = $this->parseFlexFormLink($flex["link"], $dbReference, $processedData);
        $props["customcss"] = $flex['customcss'] ?? '';
        $subs[] = $this->createContentElement('imageplus', $props);
        break;
      case "mrm_be_cm_interviewfrage":
        $props['lang'] = $flex['lang'] ?? '';
        $subs[] = $this->createContentElement("interviewfrage", $props, array("question" => trim($flex['question'])));
        break;

      case "mrm_be_cm_interviewantwort":
        $props['lang'] = $flex['lang'] ?? '';
        $subs[] = $this->createContentElement("interviewantwort", $props, array("interviewee" => trim($flex['interviewee']),"answer" => trim($flex['answer'])));
        break;

        case "mrm_be_cm_foldout_h3":
          $sub = $this->createContentElement("typo3_foldout_h3", array("open" => $flex["isInitialyOpen"] == "1", "noAutoOpen" => $flex["noAutoOpen"] == "1"), array("headline" => $flex["headline"]), array());
  
          if ($flex["image"] == "1") {
            $props = $this->processImagesTTContent($dbReference, "mrm_be_cm_contentimage")[0];
            $props["type"] = "typo3_content";
            $sub["subElements"][] = $this->createContentElement("image", $props);
          } else {
            switch ($flex["icon"]) {
              case "1":
                $sub["attributes"]["icon"] = "stadtinfo_basics";
                break;
              case "2":
                $sub["attributes"]["icon"] = "geschichte";
                break;
              case "3":
                $sub["attributes"]["icon"] = "kultur_freizeit";
                break;
              case "4":
                $sub["attributes"]["icon"] = "besonderheiten";
                break;
              case "5":
                $sub["attributes"]["icon"] = "kosten_geld";
                break;
              case "6":
                $sub["attributes"]["icon"] = "hochschulen";
                break;
              case "7":
                $sub["attributes"]["icon"] = "studieren";
                break;
            }
          }
  
          if ($flex["dynamicComponents"] && sizeof($flex["dynamicComponents"]) > 0)
            foreach ($flex["dynamicComponents"] as $comp) {
              $stype = array_keys($comp['settings'])[0];
              $elements = $this->checkText($comp['settings'][$stype][$stype], $dbReference, $processedData, $stype == "paragraph" ? "typo3_paragraph" : ($stype == "headline" ? "h4" : $stype));
              $sub["subElements"] = array_merge($sub["subElements"], $elements);
            }
          $subs[] = $sub;
          break;
          case "mrm_be_cm_quiz_direct":
            //print_r($flex); die();
            $s = $this->createContentElement(
              "quizdirect",
              array(
                "labels" => array(
                  "startbutton" => $flex["startbuttontext"],
                  "submitbutton" => $flex["submitbuttontext"],
                  "nextbutton" => $flex["nextbuttontext"],
                  "lastbutton" => $flex["lastbuttontext"],
                  "question" => $flex["question"],
                  "repeatbutton" => $flex["repeatbuttontext"],
                  "qsuccess" => $flex["questionsuccesstext"],
                  "qfail" => $flex["questionfailtext"],
                ),
                "resultscreen" => array(
                  "headingTop" => $flex["resultheadingtop"],
                  "headingSub" => $flex["resultheadingsub"],
                  "validation" => $flex["validationstr"],
                  "end" => $flex["thanks"]
                ),
                "isRestartAble" => $flex["isRestartAble"] == 1 || $flex["isRestartAble"] == "1",
              ),
              array(
                "items" => array_values(array_map(function ($v) {
                  $questionType = null;
                  $quest = $v['settings']['question'];
                  if (!isset($quest)) {
                    $quest = $v['settings']['question_multi'];
                    $questionType = "multi";
                  }
                  if (isset($quest["additional_text"]) && $quest["additional_text"] != "") {
                    $quest["text"] = $quest["text"] . " (" . $quest["additional_text"] . ")";
                    unset($quest["additional_text"]);
                  }
                  if ($questionType) $quest["type"] = $questionType;
                  unset($quest["rightanswer"]);
                  if(isset($quest['solutionText'])) $solution = $quest['solutionText'];
                  unset($quest['solutionText']);
                  $i = 0;
                  $quest["answers"] = array();
                  while (1) {
                    $i++;
                    if (!isset($quest["answertext" . $i])) break;
                    if ($quest["answertext" . $i] === "") continue;
                    $quest["answers"][] = array("text" => $quest["answertext" . $i],  "points" => (int)$quest["answerpoints" . $i]);
                    unset($quest["answertext" . $i]);
                    unset($quest["answerpoints" . $i]);
                  }
                  $quest["solution"] = $solution;

                  return $quest;
                }, $flex["dynamicComponents"])),

                "validation" => array(
                  "maxPoints" => (int)$flex["maxpoints"],
                  "averagePoints" => $this->createContentElement("injection", array("type" => "quiz-averagePoints")),
                  "alreadyReachedPoints" => $this->createContentElement("injection", array("type" => "quiz-alreadyReachedPoints")),

                  "items" => ($flex["dynamicComponents2"] == 0) ? [] : array_map(
                    function ($i) {
                      if(empty($i["validationText"]))  $i["validationText"] = "";
                      else $i["validationText"] = $this->checkTextForInternalLinks($i["validationText"], $dbReference, $processedData);
                      return $i;
                    },
                    array_filter(array_values(array_map(function ($v) {
                      return $v['settings']['validation'];
                    }, $flex["dynamicComponents2"])), function ($x) {
                      return $x != null;
                    })
                  ),
                  
                ),
              )
            );
            $processedData["injections"][] = "quiz-averagePoints";
            $processedData["injections"][] = "quiz-alreadyReachedPoints";
            $subs[] = $s;
            $processedData["status"]["hasQuiz"] = true;
            break;

      default:
        $this->log("MISSING PROCESSDATA 4 " . $dbReference['CType']);
        $this->log($flex, false);
        break;
    }
  }

  private function checkText($txt, $dbReference, &$processedData, $defaultElementType = "typo3_paragraph")
  {
    $txt = $this->checkTextForInternalLinks($txt, $dbReference, $processedData);
    $txt = $this->refactorTextElements($txt, $defaultElementType);
    return $txt;
  }

  private function refactorTextElements($txt, $defaultElementType)
  {
    if (strpos($txt, "<table") === FALSE) return [$this->createContentElement($defaultElementType, array(), array("text" => $txt))];
    $elements = [];
    while (($tablepos = strpos($txt, "<table")) !== FALSE) {
      if ($tablepos != 0) {
        //$this->log(trim(substr($txt, 0, $tablepos)));
        $elements[] = $this->createContentElement($defaultElementType, array(), array("text" => trim(substr($txt, 0, $tablepos))));
        $txt = substr($txt, $tablepos);
      }
      $tablepos = strpos($txt, "</table>") + 8;
      $dom = new \DOMDocument();
      @$dom->loadHTML('<?xml encoding="utf-8" ?><div id="sexy">' . trim(substr($txt, 0, $tablepos)) . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
      $tab = $this->createContentElement("table", array("rows" => array(), "columnCount" => 0));
      foreach ($dom->getElementsByTagName('tr') as $tr) {
        $par = $tr->parentNode;
        $row = [];
        if ($tab["props"]["columnCount"] == 0) {
          foreach ($tr->childNodes as $e) {
            if ($e->tagName == "td" ||  $e->tagName == "th") {
              $tab["props"]["columnCount"]++;
            }
          }
        }
        foreach ($tr->childNodes as $e) {
          if ($e->tagName != "td" && $e->tagName != "th") continue;
          $innerHTML = '';
          foreach ($e->childNodes as $n) $innerHTML .= $dom->saveHtml($n);
          $row[] = array(
            "html" => "<p>" . $innerHTML . "</p>",
            "isHeader" => $par->tagName == "thead",
            "isRowHeader" => $e->tagName == "th" && $par->tagName != "thead",
          );
        }
        $tab["props"]["rows"][] = $row;
      }
      $elements[] = $tab;

      $txt = substr($txt, $tablepos);
    }
    $txt = trim($txt);
    if ($txt != "")
      $elements[] = $this->createContentElement($defaultElementType, array(), array("text" => $txt));

    return $elements;
  }

  private function checkTextForInternalLinks($txt, $dbReference, &$processedData)
  {
    $dom = new \DOMDocument();
    @$dom->loadHTML('<?xml encoding="utf-8" ?><div id="sexy">' . $txt . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    foreach ($dom->getElementsByTagName('a') as $link) {
      $emptyHref = false;
      $title = null;
      $alt = null;
      $href = null;
      for ($i = 0; $i < $link->attributes->length; ++$i) {
        $node = $link->attributes->item($i);
        if ($node->nodeName == "href" && strpos($node->nodeValue, 'smartadserver.com') === FALSE) {
          $nv = $node->nodeValue;
          $nv = str_replace('&amp;', '&', $nv);
          $href = $this->replaceT3Link($nv, $dbReference, $processedData);
          $node->nodeValue = htmlspecialchars($href);
          if ($node->nodeValue == '') $emptyHref = true;
        }
        if ($node->nodeName == "title" && $node->nodeValue != '') $title = $node->nodeValue;
        if ($node->nodeName == "alt" && $node->nodeValue != '') $alt = $node->nodeValue;
      }
      if ($emptyHref) $link->removeAttribute('href');
      else {
        if (!$alt) {
          //check for pdf files (AS-337)
          if (strtolower(pathinfo($href, PATHINFO_EXTENSION)) == "pdf") {
            $alt = "PDF-Download (öffnet sich in neuem Fenster)";
            $link->setAttribute('target', '_blank');
            $link->setAttribute('alt', $alt);
          }
        }
      }
      if ($title && !$alt) $link->setAttribute('alt', $title);
      if ($title) $link->removeAttribute('title');
    }

    $txt = $dom->saveHTML($dom->getElementById('sexy'));
    $txt = str_replace('<div id="sexy">', '', $txt);
    $txt = substr($txt, 0, -6);
    return trim($txt);
  }

  private function parseFlexFormLink($link, $dbReference, &$processedData)
  {
    $link = implode("/", explode("\/", $link));
    [$href, $target, $css] = explode(" ", $link);
    $alt = substr($link, strlen($href . $target . $css) + 3);
    $alt = preg_replace('/&quot;/', '', trim($alt, " \""));
    if ($href == "-") return null;
    $href = $this->replaceT3Link($href, $dbReference, $processedData, true);
    $ret = array("href" => $href);
    if (!$target || $target == "-") $ret["target"] = "_top";
    else $ret["target"] = $target;
    if ($alt && $alt != "-") $ret["alt"] = $alt;
    return $ret;
  }

  private function replaceT3Link($link, $dbReference, &$processedData, $addToLinkedPosts = false)
  {
    $uid = $this->parseUIDFromT3Url($link);
    if (!$uid || $uid == '') return $link;
    if (strpos($link, 't3://page?') !== false) {
      if ($uid == "current") {
        $link = str_replace('t3://page?uid=current', '', $link);
      } else {
        if ($addToLinkedPosts) {
          $processedData['linkedPosts'][] = (int)$uid;
          $link = "#linkedPost#" . $uid . "#/linkedPost#";
        } else {
          $pageStatement = $this->pageQueryBuilder
            ->select('*')
            ->from('pages')
            ->setMaxResults(1)
            ->where(
              $this->pageQueryBuilder->expr()->eq('uid', $this->pageQueryBuilder->createNamedParameter($uid))
            )
            ->execute();

          $post = $pageStatement->fetchAll();
          $post = $post[0];
          $link = $post['slug'];
        }
      }
    }

    if (strpos($link, 't3://file?') !== false)
      $link = $this->setStaticFile($dbReference, $uid);

    return $link;
  }

  private function setStaticFile($dbReference, $uid, $publicUrl = null)
  {
    $fnNameRef = $dbReference['pid'] . "|" . $dbReference['uid'] . "|" . $dbReference['CType'] . "|file|" . $uid;
    if (!$publicUrl) {
      $file = $this->resourceFactory->getFileObject($uid);
      $publicUrl = $file->getPublicUrl();
    }
    try {
      $fnName = basename($publicUrl);
      $fnName = explode(".", $fnName);
      $extension = array_pop($fnName);
      $fnName = implode(".", $fnName);
    } catch (Exception $e) {
      $fnName = null;
    }
    return "#cdnurl#/" . $this->copyAndRenameFile($fnNameRef, "/" . $publicUrl, $fnName);
  }

  private function parseUIDFromT3Url($t3url)
  {
    $uid = null;
    if ($t3url && $t3url != '' && substr($t3url, 0, 2) == "t3")
      try {
        parse_str(parse_url($t3url)['query'], $query);
        $uid = $query['uid'];
      } catch (Exception $e) {
      }

    return $uid;
  }

  private function createContentElement($type, $props = null, $attributes = null, $subElements = null)
  {
    if (is_null($props)) $props = array();
    if (is_null($attributes)) $attributes = (object) array();
    $props["__hbs_uid"] = '_ab' . mt_rand(0, 0xffffff) . '_' . mt_rand(0, 0xffffff);
    $ele = array(
      'type' => $type,
      'props' => $props,
      'attributes' => $attributes,
    );
    if (!is_null($subElements)) $ele['subElements'] = $subElements;
    else $ele['subElements'] = [];
    return $ele;
  }

  private function processVideo($dbReference)
  {
    $data = $this->resourceFactory->convertFlexFormDataToConfigurationArray($dbReference['pi_flexform']);
    $vids = array();

    foreach ($data['settings']['video'] as $value) {
      if ($value['posterConfiguration'] && $value['posterConfiguration'] != '') $vids['poster'] = $value['posterConfiguration']['image'];
      if ($value['mp4Configuration'] && $value['mp4Configuration'] != '') $vids['mp4'] = $value['mp4Configuration']['video'];
      if ($value['ogvConfiguration'] && $value['ogvConfiguration'] != '') $vids['ogv'] = $value['ogvConfiguration']['video'];
      if ($value['webmConfiguration'] && $value['webmConfiguration'] != '') $vids['webm'] = $value['webmConfiguration']['video'];
      if ($value['threegpConfiguration'] && $value['threegpConfiguration'] != '') $vids['3gp'] = $value['threegpConfiguration']['video'];
    }

    foreach ($vids as $key => &$value) {
      $value = "/" . $value;
      $fnNameRef = $dbReference['pid'] . "|" . $dbReference['uid'] . "|" . $dbReference['CType'] . "|" . $key;
      $value = $this->copyAndRenameFile($fnNameRef, $value);
    }
    return $vids;
  }

  private function processImagesTTContent($dbReference, $ctypeOverride = '', $table = 'tt_content', $tableColumn = 'image', $refField = 'uid', $useRelationFetch = true, $addCDNPrefix = false)
  {
    if ($useRelationFetch)
      $fileObjects = $this->fileRepository->findByRelation($table, $tableColumn, $dbReference[$refField]);
    else {
      $sysfilerefQueryBuilder = $this->connection->getQueryBuilderForTable('sys_file_reference');
      $sysfileStatement = $sysfilerefQueryBuilder
        ->select('uid')
        ->from('sys_file_reference')
        ->andWhere(
          $sysfilerefQueryBuilder->expr()->eq('uid_foreign', intval($dbReference[$refField])),
          $sysfilerefQueryBuilder->expr()->eq('tablenames', $sysfilerefQueryBuilder->createNamedParameter($table)),
          $sysfilerefQueryBuilder->expr()->eq('fieldname', $sysfilerefQueryBuilder->createNamedParameter($tableColumn)),
        )
        ->execute();

      $frows = $sysfileStatement->fetchAll();
      foreach ($frows as $fileuid) {
        $fileObjects[] = $this->fileRepository->findFileReferenceByUid(intval($fileuid['uid']));
      }
    }
    $processedImages = array();

    $ctypeOverride = $ctypeOverride != '' ? $ctypeOverride : $dbReference['CType'];

    foreach ($fileObjects as $key => $value) {
      $img = array(
        'reference' => $value->getReferenceProperties(),
        'original' => $value->getOriginalFile()->getProperties(),
      );

      $imgfn = rtrim($img['original']['identifier'], "/");
      $image = $this->imageService->getImage('fileadmin/' . $imgfn, null, false);
      $cropvariantcollection = \TYPO3\CMS\Core\Imaging\ImageManipulation\CropVariantCollection::create($img['reference']['crop']);

      $cropareas = $this->imageSizes[$ctypeOverride];

      $processArray = array(
        'sources' => array()
      );

      $alt = $img['reference']['alternative'] != NULL ? $img['reference']['alternative'] : ($img['original']['alternative'] != NULL ? $img['original']['alternative'] : NULL);
      $title = $img['reference']['title'] != NULL ? $img['reference']['title'] : ($img['original']['title'] != NULL ? $img['original']['title'] : NULL);
      $caption = $img['reference']['description'] != NULL ? $img['reference']['description'] : ($img['original']['description'] != NULL ? $img['original']['description'] : NULL);
      $copyright = $img['reference']['copyright'] != NULL ? $img['reference']['copyright'] : ($img['original']['copyright'] != NULL ? $img['original']['copyright'] : NULL);
      if ($alt != NULL) $processArray['alt'] = $alt;
      if ($title != NULL) $processArray['title'] = $title;
      if ($caption != NULL) $processArray['caption'] = $caption;
      if ($copyright != NULL) $processArray['copyright'] = $copyright;

      if ($cropareas['passthru']) {
        if (is_array($cropareas['passthru'])) {
          foreach ($cropareas['passthru'] as $sizename => $size) {
            $processingInstructions = array(
              'width' => $size['width'],
              'minWidth' => $size['width'],
              'maxWidth' => $size['width'],
              'crop' => null
            );
            if ($size['height']) {
              $processingInstructions = array_merge(
                $processingInstructions,
                array(
                  'height' => $size['height'],
                  'minHeight' => $size['height'],
                  'maxHeight' => $size['height']
                )
              );
            }
            if ($size['maxHeight'])
              $processingInstructions['maxHeight'] = $size['maxHeight'];
            if ($size['minHeight'])
              $processingInstructions['minHeight'] = $size['minHeight'];

            $processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
            $imageUri = $this->imageService->getImageUri($processedImage);


            $fnNameRef = $dbReference['pid'] . "|" . $dbReference['uid'] . "|" . $ctypeOverride . "|" . $img['reference']['uid'] . "|passthru|" . $sizename;

            $processArray['sources'][$sizename] = $this->copyAndRenameFile($fnNameRef, $imageUri, $processArray['alt']);
          }
        } else {
          $fnNameRef = $dbReference['pid'] . "|" . $dbReference['uid'] . "|" . $ctypeOverride . "|" . $img['reference']['uid'] . "|passthru";
          $imageUri = $this->imageService->getImageUri($image);
          $processArray['sources']['passthru'] = ($addCDNPrefix ? "#cdnurl#/" : "") . $this->copyAndRenameFile($fnNameRef, $imageUri, $processArray['alt']);
        }
      } else
        foreach ($cropareas as $cropareaname => $sizes) {
          $croparea = $cropvariantcollection->getCropArea($cropareaname);

          foreach ($sizes as $sizename => $size) {
            if ($dbReference["doktype"] && $size['allowed_doktypes'] && !in_array($dbReference["doktype"], $size['allowed_doktypes'])) continue;
            $processingInstructions = array(
              'width' => $size['width'],
              'minWidth' => $size['width'],
              'maxWidth' => $size['width'],
              'crop' => $croparea->isEmpty() ? null : $croparea->makeAbsoluteBasedOnFile($image)
            );
            if ($size['height']) {
              $processingInstructions = array_merge(
                $processingInstructions,
                array(
                  'height' => $size['height'],
                  'minHeight' => $size['height'],
                  'maxHeight' => $size['height']
                )
              );
            }
            if ($size['maxHeight'])
              $processingInstructions['maxHeight'] = $size['maxHeight'];
            if ($size['minHeight'])
              $processingInstructions['minHeight'] = $size['minHeight'];

            $processedImage = $this->imageService->applyProcessingInstructions($image, $processingInstructions);
            $imageUri = $this->imageService->getImageUri($processedImage);


            $fnNameRef = $dbReference['pid'] . "|" . $dbReference['uid'] . "|" . $ctypeOverride . "|" . $img['reference']['uid'] . "|" . $cropareaname . "|" . $sizename;

            $processArray['sources'][$sizename] = ($addCDNPrefix ? "#cdnurl#/" : "") . $this->copyAndRenameFile($fnNameRef, $imageUri, $processArray['alt']);
          }
        }
      $processedImages[] = $processArray;
    }

    return $processedImages;
  }

  private function processAudio($dbReference, $ctypeOverride = '', $table = 'tt_content', $tableColumn = 'media', $refField = 'uid', $useRelationFetch = true, $copyToCDN = false)
  {
    if ($useRelationFetch)
      $fileObjects = $this->fileRepository->findByRelation($table, $tableColumn, $dbReference[$refField]);
    else {
      $sysfilerefQueryBuilder = $this->connection->getQueryBuilderForTable('sys_file_reference');
      $sysfileStatement = $sysfilerefQueryBuilder
        ->select('uid')
        ->from('sys_file_reference')
        ->andWhere(
          $sysfilerefQueryBuilder->expr()->eq('uid_foreign', intval($dbReference[$refField])),
          $sysfilerefQueryBuilder->expr()->eq('tablenames', $sysfilerefQueryBuilder->createNamedParameter($table)),
          $sysfilerefQueryBuilder->expr()->eq('fieldname', $sysfilerefQueryBuilder->createNamedParameter($tableColumn)),
        )
        ->execute();

      $frows = $sysfileStatement->fetchAll();

      foreach ($frows as $fileuid) {
        $fileObjects[] = $this->fileRepository->findFileReferenceByUid(intval($fileuid['uid']));
      }
    }
    $processedAudio = array();
    $audio = [];

    $ctypeOverride = $ctypeOverride != '' ? $ctypeOverride : $dbReference['CType'];

    foreach ($fileObjects as $key => $value) {
      $processedAudio = array(
        'reference' => $value->getReferenceProperties(),
        'original' => $value->getOriginalFile()->getProperties(),
      );

      if ($copyToCDN) {
        $oringalFile = $processedAudio['original']['identifier'];
        $extension = pathinfo($processedAudio['original']['identifier'], PATHINFO_EXTENSION);
        $targetFile = substr(sha1($processedAudio['original']['identifier']), 0, 5) . '_podcast.' . $extension;
        $oringalFile = '/fileadmin' . $oringalFile;
        $url = $this->copyPodcastAudioFileToCDN($oringalFile, $targetFile);
      }

      $audio['name'] = $processedAudio['original']['name'];
      $audio['url'] = $url;
      $audio['title'] = $processedAudio['reference']['title'];
      $audio['description'] = $processedAudio['reference']['description'];
    }
    return $audio;
  }

  private function copyAndRenameFile($destinationFnRef, $sourceUri, $altText = null)
  {
    $shaFileRef = sha1($destinationFnRef);
    $workPath = substr($shaFileRef, 0, 2) . "/" . substr($shaFileRef, 2, 2);
    $workFnPrefix = $shaFileRef;
    if ($altText) {
      $altText = substr($altText, 0, 100);
      $workFnPrefix = $this->sanitizeString($altText) . "-" . $shaFileRef;
    }
    $workFn = $workFnPrefix . "." . pathinfo($sourceUri, PATHINFO_EXTENSION);

    if (!file_exists(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $workPath)) {
      mkdir(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $workPath, 0777, true);
    }
    copy(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . $sourceUri, \TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $workPath . '/' . $workFn);

    return $workPath . '/' . $workFn;
  }

  private function copyPodcastAudioFileToCDN($sourceFile, $destinationFile)
  {
    $dir = 'podcast';
    if (!file_exists(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $dir)) {
      mkdir(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $dir, 0777, true);
    }
    copy(\TYPO3\CMS\Core\Core\Environment::getPublicPath() . $sourceFile, \TYPO3\CMS\Core\Core\Environment::getPublicPath() . '/cdn/' . $dir . '/' . $destinationFile);

    return '#cdnurl#/' . $dir . '/' . $destinationFile;
  }

  public function processCmdmap_deleteAction($table, $id, $recordToDelete, $recordWasDeleted = NULL, \TYPO3\CMS\Core\DataHandling\DataHandler &$pObj)
  {
    //$this->log('processCmdmap_deleteAction');
    if ($table == "pages") {
      Mongoer::sendRequest("pages", "delete", array("pageuid" => $id));
      Mongoer::sendRequest("abialtcache", "delete", array("pageuid" => $pid));
      Mongoer::sendRequest("search", "delete", array("pageuid" => $id));
      Mongoer::sendRequest("security", "delete", array("pageuid" => $id));
      Mongoer::sendRequest("previews", "delete", array("pageuid" => $id));
    }
  }

  /* PRIVATES */
  private function log($msg, $isString = true)
  {
    if (!$isString) {
      $msg = json_encode($msg, JSON_PRETTY_PRINT);
    }
    file_put_contents('/var/www/html/public/typo3temp/debug.log', $msg . PHP_EOL, FILE_APPEND);
  }
}
