<commit_before><?php
/**
 * phlexible
 *
 * @copyright 2007-2013 brainbits GmbH (http://www.brainbits.net)
 * @license   proprietary
 */

namespace Phlexible\Bundle\ElementBundle\Controller;

use Phlexible\Bundle\ElementBundle\ElementEvents;
use Phlexible\Bundle\ElementBundle\ElementStructure\Diff\Differ;
use Phlexible\Bundle\ElementBundle\ElementStructure\Serializer\ArraySerializer as ElementArraySerializer;
use Phlexible\Bundle\ElementBundle\Entity\ElementLock;
use Phlexible\Bundle\ElementBundle\Event\LoadDataEvent;
use Phlexible\Bundle\ElementBundle\Exception\InvalidArgumentException;
use Phlexible\Bundle\ElementBundle\Model\ElementHistoryManagerInterface;
use Phlexible\Bundle\ElementtypeBundle\ElementtypeStructure\Serializer\ArraySerializer as ElementtypeArraySerializer;
use Phlexible\Bundle\ElementtypeBundle\Model\Elementtype;
use Phlexible\Bundle\GuiBundle\Response\ResultResponse;
use Phlexible\Bundle\TreeBundle\Doctrine\TreeFilter;
use Phlexible\Component\AccessControl\Model\DomainObjectInterface;
use Phlexible\Component\AccessControl\Model\HierarchicalObjectIdentity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Data controller
 *
 * @author <NAME> <<EMAIL>>
 * @Route("/elements/data")
 * @Security("is_granted('ROLE_ELEMENTS')")
 */
class DataController extends Controller
{
    /**
     * Load element data
     *
     * @param Request $request
     *
     * @return JsonResponse
     * @Route("/load", name="elements_data_load")
     */
    public function loadAction(Request $request)
    {
        $treeId = (int) $request->get('id');
        $teaserId = (int) $request->get('teaser_id');
        $language = $request->get('language');
        $version = $request->get('version');
        $unlockId = $request->get('unlock');
        $doLock = (bool) $request->get('lock', false);

        $diff = $request->get('diff');
        $diffVersionFrom = (int) $request->get('diff_version_from');
        $diffVersionTo = (int) $request->get('diff_version_to');
        $diffLanguage = $request->get('diff_language');

        $teaserManager = $this->get('phlexible_teaser.teaser_manager');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');
        $stateManager = $this->get('phlexible_tree.state_manager');
        $elementHistoryManager = $this->get('phlexible_element.element_history_manager');
        $lockManager = $this->get('phlexible_element.element_lock_manager');
        $userManager = $this->get('phlexible_user.user_manager');
        $authorizationChecker = $this->get('security.authorization_checker');

        $teaser = null;
        if ($teaserId) {
            $teaser = $teaserManager->find($teaserId);
            $eid = $teaser->getTypeId();
            $treeId = $teaser->getTreeId();
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
        } elseif ($treeId) {
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
            $eid = $node->getTypeId();
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        $element = $elementService->findElement($eid);
        $elementMasterLanguage = $element->getMasterLanguage();

        if (!$language) {
            $language = $elementMasterLanguage;
        }

        if ($teaser) {
            $isPublished = $teaserManager->isPublished($teaser, $language);
            $onlineVersion = $teaserManager->getPublishedVersion($teaser, $language);
        } elseif ($treeId) {
            $isPublished = $tree->isPublished($node, $language);
            $onlineVersion = $tree->getPublishedVersion($node, $language);
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        if ($version) {
            $elementVersion = $elementService->findElementVersion($element, $version);
        } else {
            $elementVersion = $elementService->findLatestElementVersion($element);
        }

        $elementStructure = $elementService->findElementStructure($elementVersion, $language);

        $elementtype = $elementService->findElementtype($element);
        $elementtypeStructure = $elementtype->getStructure();
        $type = $elementtype->getType();

        // versions

        if ($teaser) {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'teaserId' => $teaser->getId(),
                    'action'   => 'publishTeaser'
                ]
            );
        } else {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'treeId' => $node->getId(),
                    'action' => 'publishNode'
                ]
            );
        }

        $versions = [];
        foreach ($elementService->findElementVersions($element, array('version' => 'DESC')) as $version) {
            $versions[$version->getVersion()] = [
                'version'       => $version->getVersion(),
                'format'        => 2,
                'create_date'   => $version->getCreatedAt()->format('Y-m-d H:i:s'),
                'is_published'  => false,
                'was_published' => false,
            ];
        }

        foreach ($publishedVersions as $publishedVersion) {
            $versions[$publishedVersion->getVersion()]['online'] = true;
            if ($publishedVersion->getVersion() === $onlineVersion) {
                $versions[$publishedVersion->getVersion()]['is_published'] = true;
            } else {
                $versions[$publishedVersion->getVersion()]['was_published'] = true;
            }
        }

        $versions = array_values($versions);

        // instances

        $instances = [];<commit_msg>BBPHX-48 do not apply old version information to non existant versions<commit_after><?php
/**
 * phlexible
 *
 * @copyright 2007-2013 brainbits GmbH (http://www.brainbits.net)
 * @license   proprietary
 */

namespace Phlexible\Bundle\ElementBundle\Controller;

use Phlexible\Bundle\ElementBundle\ElementEvents;
use Phlexible\Bundle\ElementBundle\ElementStructure\Diff\Differ;
use Phlexible\Bundle\ElementBundle\ElementStructure\Serializer\ArraySerializer as ElementArraySerializer;
use Phlexible\Bundle\ElementBundle\Entity\ElementLock;
use Phlexible\Bundle\ElementBundle\Event\LoadDataEvent;
use Phlexible\Bundle\ElementBundle\Exception\InvalidArgumentException;
use Phlexible\Bundle\ElementBundle\Model\ElementHistoryManagerInterface;
use Phlexible\Bundle\ElementtypeBundle\ElementtypeStructure\Serializer\ArraySerializer as ElementtypeArraySerializer;
use Phlexible\Bundle\ElementtypeBundle\Model\Elementtype;
use Phlexible\Bundle\GuiBundle\Response\ResultResponse;
use Phlexible\Bundle\TreeBundle\Doctrine\TreeFilter;
use Phlexible\Component\AccessControl\Model\DomainObjectInterface;
use Phlexible\Component\AccessControl\Model\HierarchicalObjectIdentity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Data controller
 *
 * @author <NAME> <<EMAIL>>
 * @Route("/elements/data")
 * @Security("is_granted('ROLE_ELEMENTS')")
 */
class DataController extends Controller
{
    /**
     * Load element data
     *
     * @param Request $request
     *
     * @return JsonResponse
     * @Route("/load", name="elements_data_load")
     */
    public function loadAction(Request $request)
    {
        $treeId = (int) $request->get('id');
        $teaserId = (int) $request->get('teaser_id');
        $language = $request->get('language');
        $version = $request->get('version');
        $unlockId = $request->get('unlock');
        $doLock = (bool) $request->get('lock', false);

        $diff = $request->get('diff');
        $diffVersionFrom = (int) $request->get('diff_version_from');
        $diffVersionTo = (int) $request->get('diff_version_to');
        $diffLanguage = $request->get('diff_language');

        $teaserManager = $this->get('phlexible_teaser.teaser_manager');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $elementService = $this->get('phlexible_element.element_service');
        $iconResolver = $this->get('phlexible_element.icon_resolver');
        $stateManager = $this->get('phlexible_tree.state_manager');
        $elementHistoryManager = $this->get('phlexible_element.element_history_manager');
        $lockManager = $this->get('phlexible_element.element_lock_manager');
        $userManager = $this->get('phlexible_user.user_manager');
        $authorizationChecker = $this->get('security.authorization_checker');

        $teaser = null;
        if ($teaserId) {
            $teaser = $teaserManager->find($teaserId);
            $eid = $teaser->getTypeId();
            $treeId = $teaser->getTreeId();
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
        } elseif ($treeId) {
            $tree = $treeManager->getByNodeId($treeId);
            $node = $tree->get($treeId);
            $eid = $node->getTypeId();
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        $element = $elementService->findElement($eid);
        $elementMasterLanguage = $element->getMasterLanguage();

        if (!$language) {
            $language = $elementMasterLanguage;
        }

        if ($teaser) {
            $isPublished = $teaserManager->isPublished($teaser, $language);
            $onlineVersion = $teaserManager->getPublishedVersion($teaser, $language);
        } elseif ($treeId) {
            $isPublished = $tree->isPublished($node, $language);
            $onlineVersion = $tree->getPublishedVersion($node, $language);
        } else {
            throw new InvalidArgumentException('Unknown data requested.');
        }

        if ($version) {
            $elementVersion = $elementService->findElementVersion($element, $version);
        } else {
            $elementVersion = $elementService->findLatestElementVersion($element);
        }

        $elementStructure = $elementService->findElementStructure($elementVersion, $language);

        $elementtype = $elementService->findElementtype($element);
        $elementtypeStructure = $elementtype->getStructure();
        $type = $elementtype->getType();

        // versions

        if ($teaser) {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'teaserId' => $teaser->getId(),
                    'action'   => 'publishTeaser'
                ]
            );
        } else {
            $publishedVersions = $elementHistoryManager->findBy(
                [
                    'treeId' => $node->getId(),
                    'action' => 'publishNode'
                ]
            );
        }

        $versions = [];
        foreach ($elementService->findElementVersions($element, array('version' => 'DESC')) as $version) {
            $versions[$version->getVersion()] = [
                'version'       => $version->getVersion(),
                'format'        => 2,
                'create_date'   => $version->getCreatedAt()->format('Y-m-d H:i:s'),
                'is_published'  => false,
                'was_published' => false,
            ];
        }

        foreach ($publishedVersions as $publishedVersion) {
            if (!isset($versions[$publishedVersion->getVersion()])) {
                continue;
            }
            $versions[$publishedVersion->getVersion()]['online'] = true;
            if ($publishedVersion->getVersion() === $onlineVersion) {
                $versions[$publishedVersion->getVersion()]['is_published'] = true;
            } else {
                $versions[$publishedVersion->getVersion()]['was_published'] = true;
            }
        }

        $versions = array_values($versions);

        // instances

        $instances = [];
{'fraction_non_alphanumeric': 0.13799470177410292, 'fraction_numerical': 0.0016055229991169624, 'mean_word_length': 2.786626139817629, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 134, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4823325', 'n_tokens_mistral': 3417, 'n_tokens_neox': 3340, 'n_words': 509}