1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 
<?php
/* --------------------------------------------------------------
 ContentManagerPagesController.inc.php 2018-04-09
 Gambio GmbH
 http://www.gambio.de
 Copyright (c) 2018 Gambio GmbH
 Released under the GNU General Public License (Version 2)
 [http://www.gnu.org/licenses/gpl-2.0.html]
 --------------------------------------------------------------
 */

require_once __DIR__ . '/ContentManagerContentNavigationTrait.inc.php';

/**
 * Class ContentManagerPagesController
 *
 * @category System
 * @package  AdminHttpViewControllers
 */
class ContentManagerPagesController extends AdminHttpViewController
{
    use ContentManagerContentNavigationTrait;
    
    /**
     * @var \UserConfigurationService
     */
    protected $userConfigurationService;
    
    /**
     * @var \LanguageTextManager
     */
    protected $languageTextManager;
    
    /**
     * @var \LanguageProvider
     */
    protected $languageProvider;
    
    /**
     * @var \CI_DB_query_builder
     */
    protected $queryBuilder;
    
    /**
     * @var \UrlRewriteStorage
     */
    protected $urlRewriteStorage;
    
    /**
     * @var array
     */
    protected $fieldMap = [
        'content_name',
        'content_title',
        'content_heading',
        'content_text',
        'contents_meta_title',
        'contents_meta_keywords',
        'contents_meta_description',
        'gm_url_keywords',
        'url_rewrite',
        'gm_robots_entry',
        'gm_sitemap_entry',
        'gm_priority',
        'gm_changefreq',
        'gm_link',
        'gm_link_target',
        'content_file',
        'download_file',
        'content_status',
        'content_file',
        'content_type',
        'content_version'
    ];
    
    /**
     * @var array
     */
    protected $switcherFields = [
        'content_status',
        'gm_robots_entry',
        'gm_sitemap_entry'
    ];
    
    /**
     * @var array
     */
    protected $typeMap = [
        'content' => 'infopage',
        'link'    => 'linkpage',
        'file'    => 'scriptpage'
    ];
    
    /**
     * @var NonEmptyStringType
     */
    protected $title;
    
    /**
     * @var SliderWriteServiceInterface
     */
    protected $sliderWriteService;
    
    /**
     * @var SliderReadServiceInterface
     */
    protected $sliderReadService;
    
    
    /**
     * Initialize Controller
     */
    public function init()
    {
        $this->userConfigurationService = StaticGXCoreLoader::getService('UserConfiguration');
        $this->languageTextManager      = MainFactory::create('LanguageTextManager', 'content_manager',
                                                              $_SESSION['languages_id']);
        $this->queryBuilder             = StaticGXCoreLoader::getDatabaseQueryBuilder();
        $this->languageProvider         = MainFactory::create('LanguageProvider', $this->queryBuilder);
        
        $this->title = new NonEmptyStringType($this->languageTextManager->get_text('HEADING_TITLE'));
        
        $this->urlRewriteStorage = MainFactory::create('UrlRewriteStorage', new NonEmptyStringType('content'),
                                                       $this->queryBuilder, $this->languageProvider);
        
        $this->sliderWriteService = StaticGXCoreLoader::getService('SliderWrite');
        $this->sliderReadService  = StaticGXCoreLoader::getService('SliderRead');
    }
    
    
    /**
     * Default actions, renders the content manager elements overview.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionDefault()
    {
        $this->_setExpertMode();
        
        $contentData = $this->_getPagesData();
        
        $data = MainFactory::create('KeyValueCollection', [
            'mainCategoryData'        => $contentData['main'],
            'secondaryNavigationData' => $contentData['secondary'],
            'other'                   => $contentData['other'],
            'infoBox'                 => $contentData['infoBox'],
            'contentStatus'           => $contentData['contentStatus'],
        ]);
        
        return MainFactory::create('AdminLayoutHttpControllerResponse', $this->title,
                                   $this->_getTemplate('pages', 'overview'), $data, $this->_getAssets(),
                                   $this->_createContentNavigation($this->languageTextManager, 'pages'));
    }
    
    
    /**
     * Renders the editing form for content manager pages.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionEdit()
    {
        $this->_setExpertMode();
        
        $formData = $this->_getEditFormData();
        
        $contentType  = $this->typeMap[$formData->getValue('contentType')];
        $languageCode = $this->languageProvider->getCodeById(new IdType($_SESSION['languages_id']));
        $contentData  = $formData->getValue('contentManager')[$contentType];
        
        $title = new NonEmptyStringType($this->languageTextManager->get_text('CONTENT_TITLE') . ': '
                                        . $contentData['content_title'][$languageCode->asString()]);
        
        return MainFactory::create('AdminLayoutHttpControllerResponse', $title, $this->_getTemplate('pages', 'edit'),
                                   $formData, $this->_getAssets(),
                                   $this->_createContentNavigation($this->languageTextManager, 'pages'));
    }
    
    
    /**
     * Stores content manager info page data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionSaveInfoPage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareData('infopage');
        
        // special case for withdrawal and withdrawal form modal (content group id 3889895)
        if((int)$data['contentGroupId'] === 3889895)
        {
            $withdrawalFormFile = $this->_getPostData('content_manager')['infopage']['withdrawal_form_file'];
            
            foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
            {
                $languageId   = $this->languageProvider->getIdByCode($languageCode);
                $languageCode = $languageCode->asString();
                
                gm_set_content('WITHDRAWAL_FORM_FILE', $withdrawalFormFile[$languageCode], $languageId);
            }
        }
        
        return $this->_insertContentData($this->queryBuilder, $data['contentData'])
                    ->_storeUrlRewrites($data['urlRewrites'], $data['contentGroupId'])
                    ->_updateSlider($data)
                    ->_repairUrlKeywords()
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Updates content manager info pages data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionUpdateContentPage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareData('infopage');
        
        // special case for withdrawal and withdrawal form modal (content group id 3889895)
        if((int)$data['contentGroupId'] === 3889895)
        {
            $withdrawalFormFile = $this->_getPostData('content_manager')['infopage']['withdrawal_form_file'];
            
            foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
            {
                $languageId   = $this->languageProvider->getIdByCode($languageCode);
                $languageCode = $languageCode->asString();
                
                gm_set_content('WITHDRAWAL_FORM_FILE', $withdrawalFormFile[$languageCode], $languageId);
            }
        }
        
        return $this->_updateContentData($this->queryBuilder, $data['contentData'], $data['contentGroupId'])
                    ->_storeUrlRewrites($data['urlRewrites'], $data['contentGroupId'])
                    ->_updateSlider($data)
                    ->_repairUrlKeywords()
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Stores content manager link page data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionSaveScriptPage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareData('scriptpage');
        
        // special case for withdrawal and withdrawal form modal (content group id 3889895)
        if((int)$data['contentGroupId'] === 3889895)
        {
            $withdrawalFormFile = $this->_getPostData('content_manager')['scriptpage']['withdrawal_form_file'];
            
            foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
            {
                $languageId   = $this->languageProvider->getIdByCode($languageCode);
                $languageCode = $languageCode->asString();
                
                gm_set_content('WITHDRAWAL_FORM_FILE', $withdrawalFormFile[$languageCode], $languageId);
            }
        }
        
        return $this->_insertContentData($this->queryBuilder, $data['contentData'])
                    ->_storeUrlRewrites($data['urlRewrites'], $data['contentGroupId'])
                    ->_updateSlider($data)
                    ->_repairUrlKeywords()
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Updates content manager script pages data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionUpdateFilePage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareData('scriptpage');
        
        // special case for withdrawal and withdrawal form modal (content group id 3889895)
        if((int)$data['contentGroupId'] === 3889895)
        {
            $withdrawalFormFile = $this->_getPostData('content_manager')['scriptpage']['withdrawal_form_file'];
            
            foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
            {
                $languageId   = $this->languageProvider->getIdByCode($languageCode);
                $languageCode = $languageCode->asString();
                
                gm_set_content('WITHDRAWAL_FORM_FILE', $withdrawalFormFile[$languageCode], $languageId);
            }
        }
        
        return $this->_updateContentData($this->queryBuilder, $data['contentData'], $data['contentGroupId'])
                    ->_storeUrlRewrites($data['urlRewrites'], $data['contentGroupId'])
                    ->_updateSlider($data)
                    ->_repairUrlKeywords()
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Stores content manager link page data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionSaveLinkPage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareLinkPagePostData();
        
        return $this->_insertContentData($this->queryBuilder, $data['contentData'])
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Updates content manager link pages data in the database and redirects to the overview.
     *
     * @return \RedirectHttpControllerResponse
     */
    public function actionUpdateLinkPage()
    {
        $this->_setExpertMode();
        
        $data = $this->_prepareLinkPagePostData();
        
        return $this->_updateContentData($this->queryBuilder, $data['contentData'], $data['contentGroupId'])
                    ->_getUpdateResponse('ContentManagerPages', $data['contentGroupId']);
    }
    
    
    /**
     * Renders the creation form for content manager main pages.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionCreateMain()
    {
        return $this->_getCreationResponse('main');
    }
    
    
    /**
     * Renders the creation form for content manager secondary pages.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionCreateSecondary()
    {
        return $this->_getCreationResponse('secondary');
    }
    
    
    /**
     * Renders the creation form for content manager info pages.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionCreateInfo()
    {
        return $this->_getCreationResponse('info');
    }
    
    
    /**
     * Renders the creation form for content manager info box pages.
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    public function actionCreateInfoBox()
    {
        return $this->_getCreationResponse('info_box');
    }
    
    
    /**
     * Prepares $_POST data for content manager link pages.
     *
     * @return array Prepared data set for updating or inserting into the database.
     */
    protected function _prepareLinkPagePostData()
    {
        $data = $this->_prepareData('linkpage');
        foreach($data['contentData'] as $key => $dataSet)
        {
            $data['contentData'][$key]['gm_link_target'] = array_key_exists('gm_link_target',
                                                                            $dataSet) ? '_blank' : '_top';
        }
        
        return $data;
    }
    
    
    /**
     * Stores the given url rewrites in the database.
     *
     * @param array $urlRewrites    Content data array.
     * @param int   $contentGroupId Content group id.
     *
     * @return $this|\ContentManagerPagesController Same instance for chained method calls.
     */
    protected function _storeUrlRewrites(array $urlRewrites, $contentGroupId)
    {
        $urlRewriteContentId = new IdType($contentGroupId);
        $this->urlRewriteStorage->delete($urlRewriteContentId);
        $urlRewriteCollection = [];
        
        foreach($urlRewrites as $languageId => $urlRewrite)
        {
            $languageId      = new IdType($languageId);
            $languageCode    = $this->languageProvider->getCodeById($languageId);
            $rewriteUrl      = new NonEmptyStringType($urlRewrite);
            $targetUrlString = 'shop_content.php?coID=' . $urlRewriteContentId->asInt() . '&language='
                               . strtolower($languageCode->asString());
            $targetUrl       = new NonEmptyStringType($targetUrlString);
            
            $urlRewrite = MainFactory::create('UrlRewrite', new NonEmptyStringType('content'), $urlRewriteContentId,
                                              $languageId, $rewriteUrl, $targetUrl);
            
            $urlRewriteCollection[$languageCode->asString()] = $urlRewrite;
        }
        
        $this->urlRewriteStorage->set($urlRewriteContentId,
                                      MainFactory::create('UrlRewriteCollection', $urlRewriteCollection));
        
        return $this;
    }
    
    
    /**
     * Update content slider
     *
     * @param array $data
     *
     * @return $this Same instance for chained method calls.
     */
    protected function _updateSlider(array $data)
    {
        $sliderId       = new IdType((int)$data['slider_id']);
        $contentGroupId = new IdType((int)$data['contentGroupId']);
        
        $sliderId->asInt() ? $this->sliderWriteService->saveSliderAssignmentForContentId($sliderId,
                                                                                         $contentGroupId) : $this->sliderWriteService->deleteSliderAssignmentByContentId($contentGroupId);
        
        return $this;
    }
    
    
    /**
     * Repairs gm_url_keywords for contents
     *
     * @return $this Same instance for chained method calls.
     */
    protected function _repairUrlKeywords()
    {
        $seoBoost = MainFactory::create_object('GMSEOBoost', [], true);
        $seoBoost->repair('contents');
        
        return $this;
    }
    
    
    /**
     * Renders the creation form for content manager main pages.
     *
     * @param string $type Content manager type to be created, whether "main", "secondary" or "info".
     *
     * @return \AdminLayoutHttpControllerResponse
     */
    protected function _getCreationResponse($type)
    {
        $contentManager = [
            'filemanager_available' => $this->_isFilemanagerAvailable(),
            'infopage'              => [
                'form_action' => 'admin.php?do=ContentManagerPages/saveInfoPage&type=' . $type
            ],
            'linkpage'              => [
                'form_action' => 'admin.php?do=ContentManagerPages/saveLinkPage&type=' . $type
            ],
            'scriptpage'            => [
                'form_action' => 'admin.php?do=ContentManagerPages/saveScriptPage&type=' . $type,
                'filelist'    => $this->_getScriptPageFiles()
            ]
        ];
        
        $ckIdentifier = [];
        $ckTypes      = [];
        foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
        {
            $languageCode                = $languageCode->asString();
            $ckIdentifier[$languageCode] = 'content-manager-infopage-new-content-' . $languageCode;
            $ckTypes[$languageCode]      = $this->userConfigurationService->getUserConfiguration(new IdType(0),
                                                                                                 $ckIdentifier[$languageCode]) ? : 'ckeditor';
        }
        $contentManager['infopage']['ckeditor'] = [
            'identifier' => $ckIdentifier,
            'type'       => $ckTypes,
        ];
        
        $contentManager['sliders'] = [];
        
        /** @var \SliderInterface $slider */
        foreach($this->sliderReadService->getAllSlider()->getArray() as $slider)
        {
            $contentManager['sliders'][] = ['id' => $slider->getId(), 'name' => $slider->getName()];
        }
        
        $contentManager['sliderId'] = 0;
        
        $data = MainFactory::create('KeyValueCollection', [
            'contentType'    => $this->_getQueryParameter('contentType'),
            'contentManager' => $contentManager
        ]);
        
        $title = new NonEmptyStringType($this->languageTextManager->get_text('NEW_CONTENT_TITLE'));
        
        return MainFactory::create('AdminLayoutHttpControllerResponse', $title, $this->_getTemplate('pages', 'edit'),
                                   $data, $this->_getAssets(),
                                   $this->_createContentNavigation($this->languageTextManager, 'pages'));
    }
    
    
    /**
     * Prepares the given content manager data to use it in the edit form.
     *
     * @param array $contentManagerData Content manager data from sql query.
     *
     * @return array Prepared content manager data.
     */
    protected function _getContentManagerEditData(array $contentManagerData)
    {
        $data = [];
        
        foreach($contentManagerData as $key => $contentManagerDataSet)
        {
            try
            {
                $languageCode = $this->languageProvider->getCodeById(new IdType($contentManagerData[$key]['languages_id']))
                                                       ->asString();
                foreach($contentManagerDataSet as $field => $value)
                {
                    $data[$field][$languageCode] = $value;
                }
            }
            catch(UnexpectedValueException $e)
            {
            }
        }
        
        return $data;
    }
    
    
    /**
     * Returns the required data for the edit form of content manager pages.
     *
     * @return \KeyValueCollection Contains data for the edit form of content manager entries.
     */
    protected function _getEditFormData()
    {
        $contentId   = $this->_getQueryParameter('id');
        $contentData = $this->_getContentDataById($contentId);
        
        $data = MainFactory::create('KeyValueCollection', $this->_getContentEditData($contentId, $contentData));
        
        return $data;
    }
    
    
    /**
     * Returns the content edit data array, which will be
     * converted to a key value collection and assigned to the edit form.
     *
     * @param int   $contentId   Id of content manager entry to be edited.
     * @param array $contentData Content manager data to be edited.
     *
     * @return array
     */
    protected function _getContentEditData($contentId, $contentData)
    {
        $data            = [];
        $contentPosition = $this->_getContentPosition($contentData);
        $contentType     = $this->_getContentType($contentData);
        
        // set form actions
        foreach($this->typeMap as $type => $uiType)
        {
            $data['contentManager'][$this->typeMap[$type]]                = $this->_getEditData($contentId,
                                                                                                $contentData);
            $data['contentManager'][$this->typeMap[$type]]['form_action'] = 'admin.php?do=ContentManagerPages/update'
                                                                            . ucfirst($type) . 'Page&id=' . $contentId
                                                                            . '&type=' . $contentPosition;
            $data['contentManager'][$this->typeMap[$type]]['filelist']    = $this->_getScriptPageFiles();
        }
        
        $data['contentManager'][$this->typeMap[$contentType]]['ckeditor'] = $this->_getCkEditorData($contentId,
                                                                                                    $contentType);
        $data['contentManager']['filemanager_available']                  = $this->_isFilemanagerAvailable();
        $data['contentType']                                              = $contentType;
        
        foreach($contentData as $dataSet)
        {
            $groupIds = implode(',', array_map(function ($element) {
                return str_replace(['_group', 'c_'], '', $element);
            }, array_filter(explode(',', $dataSet['group_ids']))));
            
            $data['contentManager']['groupCheck']   = $groupIds;
            $data['contentManager']['contentGroup'] = $dataSet['content_group'];
            break;
        }
        
        $data['contentManager']['sliders'] = [];
        
        /** @var \SliderInterface $slider */
        foreach($this->sliderReadService->getAllSlider()->getArray() as $slider)
        {
            $data['contentManager']['sliders'][] = ['id' => $slider->getId(), 'name' => $slider->getName()];
        }
        
        // special case for withdrawal and withdrawal form modal (content group id 3889895)
        if((int)$contentId === 3889895)
        {
            foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
            {
                $languageId   = $this->languageProvider->getIdByCode($languageCode);
                $languageCode = $languageCode->asString();
                
                $data['contentManager']['infopage']['withdrawal_form_file'][$languageCode]   = gm_get_content('WITHDRAWAL_FORM_FILE',
                                                                                                              $languageId);
                $data['contentManager']['scriptpage']['withdrawal_form_file'][$languageCode] = gm_get_content('WITHDRAWAL_FORM_FILE',
                                                                                                              $languageId);
            }
        }
        
        $data['contentManager']['sliderId'] = $this->sliderReadService->findAssignedSliderIdForContentId(new IdType((int)$contentData[0]['content_group']));
        
        return $data;
    }
    
    
    /**
     * Executes an sql query again the url_rewrites table and returns the result.
     *
     * @param int $contentId Url rewrites table "content_id" value.
     *
     * @return UrlRewriteCollection Url rewrite collection.
     */
    protected function _getUrlRewriteEditData($contentId)
    {
        return $this->urlRewriteStorage->get(new IdType($contentId));
    }
    
    
    /**
     * Returns content manager data to be edited, prepared for the edit form.
     *
     * @param int   $contentId   Content manager tables "content_group" value.
     * @param array $contentData Raw data set from sql query.
     *
     * @return array Prepared data set array for edit forms of content manager pages.
     */
    protected function _getEditData($contentId, array $contentData)
    {
        $contentManagerEditData = $this->_getContentManagerEditData($contentData);
        
        /** @var UrlRewrite $urlRewrite */
        foreach($this->_getUrlRewriteEditData($contentId) as $urlRewrite)
        {
            $languageCode = $this->languageProvider->getCodeById(new IdType($urlRewrite->getLanguageId()));
            
            $contentManagerEditData['url_rewrite'][$languageCode->asString()] = $urlRewrite->getRewriteUrl();
        }
        
        return $contentManagerEditData;
    }
    
    
    /**
     * Returns required data for CkEditor settings.
     *
     * @param int    $contentId Content manager tables "content_group" value.
     * @param string $type      Content type, whether "content", "file" or "link".
     *
     * @return array
     */
    protected function _getCkEditorData($contentId, $type)
    {
        $ckIdentifier = [];
        $ckTypes      = [];
        
        foreach($this->languageProvider->getCodes()->getArray() as $languageCode)
        {
            $languageCode                = $languageCode->asString();
            $ckIdentifier[$languageCode] = 'content-manager-' . $this->typeMap[$type] . '-content-' . $contentId . '-'
                                           . $languageCode;
            $ckTypes[$languageCode]      = $this->userConfigurationService->getUserConfiguration(new IdType(0),
                                                                                                 $ckIdentifier[$languageCode]) ? : 'ckeditor';
        }
        
        return [
            'identifier' => $ckIdentifier,
            'type'       => $ckTypes,
        ];
    }
    
    
    /**
     * Executes an sql query again the content_manager table and returns the result.
     *
     * @param int $contentId Content manager tables "content_group" value.
     *
     * @return array Content manager table data.
     */
    protected function _getContentDataById($contentId)
    {
        return $this->queryBuilder->select()
                                  ->from('content_manager')
                                  ->where('content_group', $contentId)
                                  ->get()
                                  ->result_array();
    }
    
    
    /**
     * Returns the content position of the given query result.
     *
     * @param array $queryResult Data sets of query for content_manager table.
     *
     * @return string Whether "pages_main", "pages_secondary" or "pages_info".
     */
    protected function _getContentPosition(array $queryResult)
    {
        foreach($queryResult as $result)
        {
            return str_replace('pages_', '', $result['content_position']);
        }
        
        return 'main';
    }
    
    
    /**
     * Prepares $_POST data for updating or inserting into the database.
     *
     * @param string $contentManagerType Whether "infopage", "linkpage" or "scriptpage".
     *
     * @return array Contains data sets for content_manager- and url_rewrites table and an additional content group id.
     */
    protected function _prepareData($contentManagerType)
    {
        $contentGroupId = $this->_getQueryParameter('id') ? : $this->_createNewContentGroupId($this->queryBuilder);
        $data           = $this->_prepareContentManagerData($contentGroupId, $contentManagerType);
        $urlRewrites    = [];
        
        // prepare url keywords and rewrite data sets
        // and remove content_file if its not a scriptpage
        foreach($data as $languageId => &$datum)
        {
            if(array_key_exists('url_rewrite', $datum) && $datum['url_rewrite'] !== '')
            {
                $urlRewrites[$datum['languages_id']] = $datum['url_rewrite'];
            }
            unset($data[$languageId]['url_rewrite']);
            
            if(array_key_exists('gm_url_keywords', $datum))
            {
                $datum['gm_url_keywords'] = xtc_cleanName($datum['gm_url_keywords']);
            }
            
            if($contentManagerType !== 'scriptpage')
            {
                $datum['content_file'] = '';
            }
        }
        
        return [
            'contentData'    => $data,
            'urlRewrites'    => $urlRewrites,
            'contentGroupId' => $contentGroupId,
            'slider_id'      => $this->_getPostData('content_manager')['slider_id']
        ];
    }
    
    
    /**
     * Prepares $_POST data for updating or inserting into the content_manager table.
     *
     * @param int    $contentGroupId     Content manager tables "content_group" value.
     * @param string $contentManagerType Whether "infopage", "linkpage" or "scriptpage".
     *
     * @return array Data set for the content_manager table.
     */
    protected function _prepareContentManagerData($contentGroupId, $contentManagerType)
    {
        $contentManagerData = $this->_getPostData('content_manager')[$contentManagerType];
        $newContentGroupId  = $this->_getPostData('content_manager')['content_group_id'];
        $data               = [];
        
        if($this->_isFilemanagerAvailable() === false && $contentManagerType === 'scriptpage')
        {
            $contentManagerData['content_file'] = $this->_checkScriptpageFileUploads();
        }
        
        foreach($this->fieldMap as $field)
        {
            if(array_key_exists($field, $contentManagerData))
            {
                foreach($contentManagerData[$field] as $languageCode => $value)
                {
                    $languageId      = $this->languageProvider->getIdByCode(new LanguageCode(new StringType($languageCode)));
                    $contentPosition = 'pages_' . $this->_getQueryParameter('type');
                    
                    $data[$languageId]['languages_id']     = $languageId;
                    $data[$languageId]['content_group']    = $newContentGroupId ? : $contentGroupId;
                    $data[$languageId]['content_position'] = $contentPosition;
                    $data[$languageId]['group_ids']        = $this->_prepareContentManagerGroupCheckData();
                    $data[$languageId]['file_flag']        = array_flip($this->fileTypMap)[$this->contentTypeFileFlagMap[$contentPosition]];
                    
                    $data[$languageId][$field] = $value;
                }
            }
        }
        
        foreach($data as $languageId => $datum)
        {
            foreach($this->switcherFields as $switcherField)
            {
                if(!array_key_exists($switcherField, $datum))
                {
                    $data[$languageId][$switcherField] = '0';
                }
            }
        }
        
        return $data;
    }
    
    
    /**
     * Fetches and returns the content data for the content manager pages.
     *
     * @return array
     */
    protected function _getPagesData()
    {
        $main          = [];
        $secondary     = [];
        $other         = [];
        $infoBox       = [];
        $contentStatus = [];
        
        $queryResult = $this->queryBuilder->select()
                                          ->from('content_manager')
                                          ->order_by('sort_order')
                                          ->get()
                                          ->result_array();
        
        foreach($queryResult as $result)
        {
            if((int)$result['languages_id'] === (int)$_SESSION['languages_id'])
            {
                if($result['content_position'] === 'pages_main')
                {
                    $main[] = [
                        'contentId'   => $result['content_id'],
                        'link'        => $result['gm_link'],
                        'sortOrder'   => $result['sort_order'],
                        'id'          => $result['content_group'],
                        'name'        => $result['content_name'],
                        'title'       => $result['content_title'],
                        'type'        => $result['content_type'],
                        'description' => $this->_getContentDescription($result['content_type']),
                        'deletable'   => (int)$result['content_delete'] === 1
                    ];
                }
                if($result['content_position'] === 'pages_secondary')
                {
                    $secondary[] = [
                        'contentId'   => $result['content_id'],
                        'link'        => $result['gm_link'],
                        'sortOrder'   => $result['sort_order'],
                        'id'          => $result['content_group'],
                        'name'        => $result['content_name'],
                        'title'       => $result['content_title'],
                        'type'        => $result['content_type'],
                        'description' => $this->_getContentDescription($result['content_type']),
                        'deletable'   => (int)$result['content_delete'] === 1
                    ];
                }
                if($result['content_position'] === 'pages_info')
                {
                    $other[] = [
                        'contentId'   => $result['content_id'],
                        'link'        => $result['gm_link'],
                        'sortOrder'   => $result['sort_order'],
                        'id'          => $result['content_group'],
                        'name'        => $result['content_name'],
                        'title'       => $result['content_title'],
                        'type'        => $result['content_type'],
                        'description' => $this->_getContentDescription($result['content_type']),
                        'deletable'   => (int)$result['content_delete'] === 1
                    ];
                }
                if($result['content_position'] === 'pages_info_box')
                {
                    $infoBox[] = [
                        'contentId'   => $result['content_id'],
                        'link'        => $result['gm_link'],
                        'sortOrder'   => $result['sort_order'],
                        'id'          => $result['content_group'],
                        'name'        => $result['content_name'],
                        'title'       => $result['content_title'],
                        'type'        => $result['content_type'],
                        'description' => $this->_getContentDescription($result['content_type']),
                        'deletable'   => (int)$result['content_delete'] === 1
                    ];
                }
            }
            
            if(!isset($contentStatus[(int)$result['content_group']]))
            {
                $contentStatus[(int)$result['content_group']] = 0;
            }
            if((int)$result['content_status'] === 1)
            {
                $contentStatus[(int)$result['content_group']]++;
            }
        }
        
        return [
            'main'          => $main,
            'secondary'     => $secondary,
            'other'         => $other,
            'infoBox'       => $infoBox,
            'contentStatus' => $contentStatus,
        ];
    }
    
    
    /**
     * Detects the content type names from the queries result data.
     *
     * @param string $contentType Must be whether "link", "file" or "content".
     *
     * @return string Names of content types for whether "link", "file" or "content".
     */
    protected function _getContentDescription($contentType)
    {
        $descriptions = [
            'link'    => $this->languageTextManager->get_text('DESCRIPTION_LINK'),
            'file'    => $this->languageTextManager->get_text('DESCRIPTION_FILE'),
            'content' => $this->languageTextManager->get_text('DESCRIPTION_CONTENT')
        ];
        
        return $descriptions[$contentType];
    }
    
    
    /**
     * Detects file uploads for scriptpages and returns the array for new content_file post data.
     *
     * @return array
     */
    protected function _checkScriptpageFileUploads()
    {
        $return = $this->_getPostData('content_manager')['scriptpage']['content_file'];
        if(count($_FILES['content_manager']['name']['scriptpage']['content_file']) > 0)
        {
            foreach($_FILES['content_manager']['name']['scriptpage']['content_file'] as $key => $filename)
            {
                if(!empty($filename) && $_FILES['content_manager']['error']['scriptpage']['content_file'][$key] === 0)
                {
                    // move uploaded file into media/content directory
                    $directory    = DIR_FS_CATALOG . 'media' . DIRECTORY_SEPARATOR . 'content' . DIRECTORY_SEPARATOR;
                    $tempFilename = $_FILES['content_manager']['tmp_name']['scriptpage']['content_file'][$key];
                    move_uploaded_file($tempFilename, $directory . $filename);
                    
                    // update post data for selected content_file. set this value to the uploaded file.
                    $return[$key] = $filename;
                }
            }
        }
        
        return $return;
    }
}