<commit_before><?php

/**
 * flexContent
 *
 * @author Team phpManufaktur <<EMAIL>>
 * @link https://kit2.phpmanufaktur.de/flexContent
 * @copyright 2013 <NAME> <<EMAIL>>
 * @license MIT License (MIT) http://www.opensource.org/licenses/MIT
 */

namespace phpManufaktur\flexContent\Control\Admin;

use Silex\Application;
use phpManufaktur\flexContent\Data\Content\Content as ContentData;
use Carbon\Carbon;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use phpManufaktur\flexContent\Data\Content\Tag;
use phpManufaktur\flexContent\Data\Content\TagType;
use phpManufaktur\flexContent\Data\Content\Category;
use phpManufaktur\flexContent\Data\Content\CategoryType;

class ContentEdit extends Admin
{
    protected $ContentData = null;
    protected static $content_id = null;
    protected $TagData = null;
    protected $TagTypeData = null;
    protected $CategoryTypeData = null;
    protected $CategoryData = null;
    protected static $language = null;

    /**
     * (non-PHPdoc)
     * @see \phpManufaktur\flexContent\Control\Backend\Backend::initialize()
     */
    protected function initialize(Application $app)
    {
        parent::initialize($app);

        self::$content_id = -1;
        $this->ContentData = new ContentData($app);
        $this->TagData = new Tag($app);
        $this->TagTypeData = new TagType($app);
        $this->CategoryData = new Category($app);
        $this->CategoryTypeData = new CategoryType($app);

        self::$language = $this->app['request']->get('form[language]', self::$config['content']['language']['default'], true);
    }

    /**
     * Create the form.factory form for flexContent
     *
     * @param array $data
     */
    protected function getContentForm($data=array())
    {
        if (isset($data['language'])) {
            // set the language property from the content data
            self::$language = $data['language'];
        }

        if (!isset($data['publish_from']) || ($data['publish_from'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::create();
            $dt->addHours(self::$config['content']['field']['publish_from']['add']['hours']);
            $publish_from = $dt->toDateTimeString();
        }
        else {
            $publish_from = $data['publish_from'];
        }

        if (!isset($data['breaking_to']) || ($data['breaking_to'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::createFromFormat('Y-m-d H:i:s', $publish_from);
            $dt->addHours(self::$config['content']['field']['breaking_to']['add']['hours']);
            $breaking_to = $dt->toDateTimeString();
        }
        else {
            $breaking_to = $data['breaking_to'];
        }

        if (!isset($data['archive_from']) || ($data['archive_from'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::createFromFormat('Y-m-d H:i:s', $publish_from);
            $dt->endOfDay();
            $dt->addDays(self::$config['content']['field']['archive_from']['add']['days']);
            $archive_from = $dt->toDateTimeString();
        }
        else {
            $archive_from = $data['archive_from'];
        }

        if (false === ($primary_category = $this->CategoryData->selectPrimaryCategoryIDbyContentID(self::$content_id))) {
            $primary_category = null;
        }
        if (false === ($secondary_categories = $this->CategoryData->selectSecondaryCategoryIDsByContentID(self::$content_id))) {
            $secondary_categories = null;
        }

        $categories = $this->CategoryTypeData->getListForSelect(self::$language);
        if (empty($categories)) {
            $this->setAlert('No category available for the language %language%, please create a category first!',
                array('%language%' => $this->app['translator']->trans(self::$language)), self::ALERT_TYPE_WARNING);
        }

        // show the permalink URL
        $permalink_url = CMS_URL.str_ireplace('{language}', strtolower(self::$language), self::$config['content']['permalink']['directory']).'/';

        $form = $this->app['form.factory']->createBuilder('form')
        ->add('content_id', 'hidden', array(
            'data' => isset($data['content_id']) ? $data['content_id'] : -1
        ))
        ->add('language', 'hidden', array(
            'data' => self::$language,
        ))
        ->add('title', 'text', array(
            'data' => isset($data['title']) ? $data['title'] : '',
            'required' => self::$config['content']['field']['title']['required']
        ))
        ->add('description', 'textarea', array(
            'data' => isset($data['description']) ? $data['description'] : '',
            'required' => self::$config['content']['field']['description']['required']
        ))
        ->add('keywords', 'textarea', array(
            'data' => isset($data['keywords']) ? $data['keywords'] : '',
            'required' => self::$config['content']['field']['keywords']['required']
        ))
        ->add('publish_from', 'text', array(
            'required' => self::$config['content']['field']['publish_from']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($publish_from)),
        ))
        ->add('breaking_to', 'text', array(
            'required' => self::$config['content']['field']['breaking_to']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($breaking_to)),
        ))
        ->add('archive_from', 'text', array(
            'required' => self::$config['content']['field']['archive_from']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($archive_from)),
        ))
        ->add('teaser', 'textarea', array(
            'data' => isset($data['teaser']) ? $data['teaser'] : '',
            'required' => self::$config['content']['field']['teaser']['required']
        ))
        ->add('content', 'textarea', array(
            'data' => isset($data['content']) ? $data['content'] : '',
            'required' => self::$config['content']['field']['content']['required']
        ))
        ->add('rss', 'choice', array(
            'choices' => $this->ContentData->getRSSValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['rss']['required'],
            'data' => isset($data['rss']) ? $data['rss'] : 'YES',
            'label' => 'RSS'
        ))
        ->add('status', 'choice', array(
            'choices' => $this->ContentData->getStatusTypeValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['status']['required'],
            'data' => isset($data['status']) ? $data['status'] : 'UNPUBLISHED'
        ))
        ->add('permalink', 'text', array(
            'required' => self::$config['content']['field']['permalink']['required'],
            'data' => isset($data['permalink']) ? $data['permalink'] : ''
        ))
        ->add('permalink_url', 'hidden', array(
            'data' => $permalink_url
        ))
        ->add('redirect_url', 'text', array(
            'required' => self::$config['content']['field']['redirect_url']['required'],
            'data' => isset($data['redirect_url']) ? $data['redirect_url'] : ''
        ))
        ->add('redirect_target', 'choice', array(
            'choices' => $this->ContentData->getTargetTypeValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['redirect_target']['required'],
            'data' => isset($data['redirect_target']) ? $data['redirect_target'] : self::$config['content']['field']['redirect_target']['default']
        ))
        ->add('teaser_image', 'hidden', array(
            'data' => isset($data['teaser_image']) ? $data['teaser_image'] : ''
        ))
        ->add('primary_category', 'choice', array(
            'choices' => $categories,
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => true,
            'data' => $primary_category
        ))
        ->add('secondary_categories', 'choice', array(
            'choices' => $categories,
            'empty_value' => '- please select -',
            'required' => false,
            'multiple' => true,
            'data' => $secondary_categories
        ))

        ;
        return $form->getForm();
    }

    /**
     * Check the submitted form, create a new record or update an existing
     *
     * @param array reference $data
     * @return boolean
     */
    protected function checkContentForm(&$data=array())
    {
        // get the form
        $form = $this->getContentForm();
        // get the requested data
        $form->bind($this->app['request']);

        if ($form->isValid()) {
            // the form is valid
            $content = $form->getData();
            $data = array();

            self::$content_id = $content['content_id'];
            $data['content_id'] = self::$content_id;

            $checked = true;

            // check the fields
            foreach (self::$config['content']['field'] as $name => $property) {
                switch ($name) {
                    case 'title':
                        if (!$property['required']) {
                            // the title must be always set!
                            $this->setAlert('The title is always needed and con not switched off, please check the configuration!',
                                array(), self::ALERT_TYPE_WARNING);
                        }
                        if ((strlen($content[$name]) < $property['length']['minimum']) ||
                        (strlen($content[$name]) > $property['length']['maximum'])) {
                            $this->setAlert('The title should have a length between %minimum% and %maximum% characters (actual: %length%).',
                                array('%minimum%' => $property['length']['minimum'],
                                    '%maximum%' => $property['length']['maximum'], '%length%' => strlen($content[$name])),
                                self::ALERT_TYPE_WARNING);
                            $checked = false;
                        }
                        $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                        break;
                    case 'description':
                        if ($property['required']) {
                            if ((strlen($content[$name]) < $property['length']['minimum']) ||
                                (strlen($content[$name]) > $property['length']['maximum'])) {
                                $this->setAlert('The description should have a length between %minimum% and %maximum% characters (actual: %length%).',
                                    array('%minimum%' => $property['length']['minimum'],
                                        '%maximum%' => $property['length']['maximum'], '%length%' => strlen($content[$name])),
                                    self::ALERT_TYPE_WARNING);
                                $checked = false;
                            }
                        }
                        $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                        break;
                    case 'keywords':
                        if ($property['required']) {
                            $separator = ($property['separator'] == 'comma') ? ',' : ' ';
                            if (false === strpos($content[$name], $separator)) {
                                $this->setAlert('Please define keywords for the content', array(), self::ALERT_TYPE_WARNING);
                                $data[$name] = $content[$name];
                                $checked = false;
                            }
                            else {
                                $explode = explode($separator, $content[$name]);
                                $keywords = array();
                                foreach ($explode as $item) {
                                    $keyword = strtolower(trim($item));
                                    if (!empty($keyword)) {
                                        $keywords[] = $keyword;
                                    }
                                }
                                if ((count($keywords) < $property['words']['minimum']) ||
                                    (count($keywords) > $property['words']['maximum'])) {
                                    $this->setAlert('Please define between %minimum% and %maximum% keywords, actual: %count%',
                                        array('%minimum%' => $property['words']['minimum'],
                                            '%maximum' => $property['words']['maximum'], '%count%' => count($keywords)),
                                        self::ALERT_TYPE_WARNING);
                                    $checked = false;
                                }
                                $data[$name] = implode($separator, $keywords);
                            }
                        }
                        else {
                            $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                        }
                        break;
                    case 'permalink':
                        if (!$property['required']) {
                            // the 'required' flag for the permanent link can not switched off
                            $this->setAlert('The permanent link is always needed and can not switched off, please check the configuration!',
                                    array(), self::ALERT_TYPE_DANGER);
                        }

                        $permalink = !is_null($content[$name]) ? strtolower($content[$name]) : '';
                        $permalink = $this->app['utils']->sanitizeLink($permalink);

                        if ((self::$content_id < 1) && $this->ContentData->existsPermaLink($permalink, self::$language)) {<commit_msg>grant a proper build of the keywords<commit_after><?php

/**
 * flexContent
 *
 * @author Team phpManufaktur <<EMAIL>>
 * @link https://kit2.phpmanufaktur.de/flexContent
 * @copyright 2013 <NAME> <<EMAIL>>
 * @license MIT License (MIT) http://www.opensource.org/licenses/MIT
 */

namespace phpManufaktur\flexContent\Control\Admin;

use Silex\Application;
use phpManufaktur\flexContent\Data\Content\Content as ContentData;
use Carbon\Carbon;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use phpManufaktur\flexContent\Data\Content\Tag;
use phpManufaktur\flexContent\Data\Content\TagType;
use phpManufaktur\flexContent\Data\Content\Category;
use phpManufaktur\flexContent\Data\Content\CategoryType;

class ContentEdit extends Admin
{
    protected $ContentData = null;
    protected static $content_id = null;
    protected $TagData = null;
    protected $TagTypeData = null;
    protected $CategoryTypeData = null;
    protected $CategoryData = null;
    protected static $language = null;

    /**
     * (non-PHPdoc)
     * @see \phpManufaktur\flexContent\Control\Backend\Backend::initialize()
     */
    protected function initialize(Application $app)
    {
        parent::initialize($app);

        self::$content_id = -1;
        $this->ContentData = new ContentData($app);
        $this->TagData = new Tag($app);
        $this->TagTypeData = new TagType($app);
        $this->CategoryData = new Category($app);
        $this->CategoryTypeData = new CategoryType($app);

        self::$language = $this->app['request']->get('form[language]', self::$config['content']['language']['default'], true);
    }

    /**
     * Create the form.factory form for flexContent
     *
     * @param array $data
     */
    protected function getContentForm($data=array())
    {
        if (isset($data['language'])) {
            // set the language property from the content data
            self::$language = $data['language'];
        }

        if (!isset($data['publish_from']) || ($data['publish_from'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::create();
            $dt->addHours(self::$config['content']['field']['publish_from']['add']['hours']);
            $publish_from = $dt->toDateTimeString();
        }
        else {
            $publish_from = $data['publish_from'];
        }

        if (!isset($data['breaking_to']) || ($data['breaking_to'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::createFromFormat('Y-m-d H:i:s', $publish_from);
            $dt->addHours(self::$config['content']['field']['breaking_to']['add']['hours']);
            $breaking_to = $dt->toDateTimeString();
        }
        else {
            $breaking_to = $data['breaking_to'];
        }

        if (!isset($data['archive_from']) || ($data['archive_from'] == '0000-00-00 00:00:00')) {
            $dt = Carbon::createFromFormat('Y-m-d H:i:s', $publish_from);
            $dt->endOfDay();
            $dt->addDays(self::$config['content']['field']['archive_from']['add']['days']);
            $archive_from = $dt->toDateTimeString();
        }
        else {
            $archive_from = $data['archive_from'];
        }

        if (false === ($primary_category = $this->CategoryData->selectPrimaryCategoryIDbyContentID(self::$content_id))) {
            $primary_category = null;
        }
        if (false === ($secondary_categories = $this->CategoryData->selectSecondaryCategoryIDsByContentID(self::$content_id))) {
            $secondary_categories = null;
        }

        $categories = $this->CategoryTypeData->getListForSelect(self::$language);
        if (empty($categories)) {
            $this->setAlert('No category available for the language %language%, please create a category first!',
                array('%language%' => $this->app['translator']->trans(self::$language)), self::ALERT_TYPE_WARNING);
        }

        // show the permalink URL
        $permalink_url = CMS_URL.str_ireplace('{language}', strtolower(self::$language), self::$config['content']['permalink']['directory']).'/';

        $form = $this->app['form.factory']->createBuilder('form')
        ->add('content_id', 'hidden', array(
            'data' => isset($data['content_id']) ? $data['content_id'] : -1
        ))
        ->add('language', 'hidden', array(
            'data' => self::$language,
        ))
        ->add('title', 'text', array(
            'data' => isset($data['title']) ? $data['title'] : '',
            'required' => self::$config['content']['field']['title']['required']
        ))
        ->add('description', 'textarea', array(
            'data' => isset($data['description']) ? $data['description'] : '',
            'required' => self::$config['content']['field']['description']['required']
        ))
        ->add('keywords', 'textarea', array(
            'data' => isset($data['keywords']) ? $data['keywords'] : '',
            'required' => self::$config['content']['field']['keywords']['required']
        ))
        ->add('publish_from', 'text', array(
            'required' => self::$config['content']['field']['publish_from']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($publish_from)),
        ))
        ->add('breaking_to', 'text', array(
            'required' => self::$config['content']['field']['breaking_to']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($breaking_to)),
        ))
        ->add('archive_from', 'text', array(
            'required' => self::$config['content']['field']['archive_from']['required'],
            'data' => date($this->app['translator']->trans('DATETIME_FORMAT'), strtotime($archive_from)),
        ))
        ->add('teaser', 'textarea', array(
            'data' => isset($data['teaser']) ? $data['teaser'] : '',
            'required' => self::$config['content']['field']['teaser']['required']
        ))
        ->add('content', 'textarea', array(
            'data' => isset($data['content']) ? $data['content'] : '',
            'required' => self::$config['content']['field']['content']['required']
        ))
        ->add('rss', 'choice', array(
            'choices' => $this->ContentData->getRSSValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['rss']['required'],
            'data' => isset($data['rss']) ? $data['rss'] : 'YES',
            'label' => 'RSS'
        ))
        ->add('status', 'choice', array(
            'choices' => $this->ContentData->getStatusTypeValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['status']['required'],
            'data' => isset($data['status']) ? $data['status'] : 'UNPUBLISHED'
        ))
        ->add('permalink', 'text', array(
            'required' => self::$config['content']['field']['permalink']['required'],
            'data' => isset($data['permalink']) ? $data['permalink'] : ''
        ))
        ->add('permalink_url', 'hidden', array(
            'data' => $permalink_url
        ))
        ->add('redirect_url', 'text', array(
            'required' => self::$config['content']['field']['redirect_url']['required'],
            'data' => isset($data['redirect_url']) ? $data['redirect_url'] : ''
        ))
        ->add('redirect_target', 'choice', array(
            'choices' => $this->ContentData->getTargetTypeValuesForForm(),
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => self::$config['content']['field']['redirect_target']['required'],
            'data' => isset($data['redirect_target']) ? $data['redirect_target'] : self::$config['content']['field']['redirect_target']['default']
        ))
        ->add('teaser_image', 'hidden', array(
            'data' => isset($data['teaser_image']) ? $data['teaser_image'] : ''
        ))
        ->add('primary_category', 'choice', array(
            'choices' => $categories,
            'empty_value' => '- please select -',
            'expanded' => false,
            'required' => true,
            'data' => $primary_category
        ))
        ->add('secondary_categories', 'choice', array(
            'choices' => $categories,
            'empty_value' => '- please select -',
            'required' => false,
            'multiple' => true,
            'data' => $secondary_categories
        ))

        ;
        return $form->getForm();
    }

    /**
     * Check the submitted form, create a new record or update an existing
     *
     * @param array reference $data
     * @return boolean
     */
    protected function checkContentForm(&$data=array())
    {
        // get the form
        $form = $this->getContentForm();
        // get the requested data
        $form->bind($this->app['request']);

        if ($form->isValid()) {
            // the form is valid
            $content = $form->getData();
            $data = array();

            self::$content_id = $content['content_id'];
            $data['content_id'] = self::$content_id;

            $checked = true;

            // check the fields
            foreach (self::$config['content']['field'] as $name => $property) {
                switch ($name) {
                    case 'title':
                        if (!$property['required']) {
                            // the title must be always set!
                            $this->setAlert('The title is always needed and con not switched off, please check the configuration!',
                                array(), self::ALERT_TYPE_WARNING);
                        }
                        if ((strlen($content[$name]) < $property['length']['minimum']) ||
                        (strlen($content[$name]) > $property['length']['maximum'])) {
                            $this->setAlert('The title should have a length between %minimum% and %maximum% characters (actual: %length%).',
                                array('%minimum%' => $property['length']['minimum'],
                                    '%maximum%' => $property['length']['maximum'], '%length%' => strlen($content[$name])),
                                self::ALERT_TYPE_WARNING);
                            $checked = false;
                        }
                        $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                        break;
                    case 'description':
                        if ($property['required']) {
                            if ((strlen($content[$name]) < $property['length']['minimum']) ||
                                (strlen($content[$name]) > $property['length']['maximum'])) {
                                $this->setAlert('The description should have a length between %minimum% and %maximum% characters (actual: %length%).',
                                    array('%minimum%' => $property['length']['minimum'],
                                        '%maximum%' => $property['length']['maximum'], '%length%' => strlen($content[$name])),
                                    self::ALERT_TYPE_WARNING);
                                $checked = false;
                            }
                        }
                        $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                        break;
                    case 'keywords':
                        if ($property['required']) {
                            $separator = ($property['separator'] == 'comma') ? ',' : ' ';
                            if (false === strpos($content[$name], $separator)) {
                                $this->setAlert('Please define keywords for the content', array(), self::ALERT_TYPE_WARNING);
                                $data[$name] = $content[$name];
                                $checked = false;
                            }
                            else {
                                $explode = explode($separator, $content[$name]);
                                $keywords = array();
                                foreach ($explode as $item) {
                                    $keyword = strtolower(trim($item));
                                    if (!empty($keyword)) {
                                        $keywords[] = $keyword;
                                    }
                                }
                                if ((count($keywords) < $property['words']['minimum']) ||
                                    (count($keywords) > $property['words']['maximum'])) {
                                    $this->setAlert('Please define between %minimum% and %maximum% keywords, actual: %count%',
                                        array('%minimum%' => $property['words']['minimum'],
                                            '%maximum' => $property['words']['maximum'], '%count%' => count($keywords)),
                                        self::ALERT_TYPE_WARNING);
                                    $checked = false;
                                }
                                $data[$name] = implode(($separator == 'comma') ? ', ' : ' ', $keywords);
                            }
                        }
                        else {
                            if (($property['separator'] == 'comma') && strpos($content[$name], ',')) {
                                // proper separate the keywords
                                $explode = explode(',', $content[$name]);
                                $keywords = array();
                                foreach ($explode as $item) {
                                    $keyword = strtolower(trim($item));
                                    if (!empty($keyword)) {
                                        $keywords[] = $keyword;
                                    }
                                }
                                $data[$name] = implode(', ', $keywords);
                            }
                            else {
                                $data[$name] = !is_null($content[$name]) ? $content[$name] : '';
                            }
                        }
                        break;
                    case 'permalink':
                        if (!$property['required']) {
                            // the 'required' flag for the permanent link can not switched off
                            $this->setAlert('The permanent link is always needed and can not switched off, please check the configuration!',
                                    array(), self::ALERT_TYPE_DANGER);
                        }

                        $permalink = !is_null($content[$name]) ? strtolower($content[$name]) : '';
                        $permalink = $this->app['utils']->sanitizeLink($permalink);

                        if ((self::$content_id < 1) && $this->ContentData->existsPermaLink($permalink, self::$language)) {
{'fraction_non_alphanumeric': 0.17473439688450107, 'fraction_numerical': 0.003416117241143716, 'mean_word_length': 1.841032608695652, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 285, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 43, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '492608', 'n_tokens_mistral': 7590, 'n_tokens_neox': 7352, 'n_words': 1330}