<commit_before><?php
/*
 * Copyright 2016 CampaignChain, Inc. <<EMAIL>>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace CampaignChain\Activity\FacebookBundle\Controller;

use CampaignChain\CoreBundle\Controller\Module\AbstractActivityHandler;
use Symfony\Component\Form\Form;
use CampaignChain\CoreBundle\Entity\Location;
use CampaignChain\CoreBundle\Entity\Campaign;
use CampaignChain\Operation\FacebookBundle\Job\PublishStatus;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\TwigBundle\TwigEngine;
use CampaignChain\CoreBundle\Entity\Operation;
use CampaignChain\Location\FacebookBundle\Entity\Page;
use CampaignChain\Location\FacebookBundle\Entity\User;
use CampaignChain\Operation\FacebookBundle\Entity\PageStatus;
use CampaignChain\Operation\FacebookBundle\Entity\UserStatus;
use CampaignChain\Operation\FacebookBundle\EntityService\Status;
use CampaignChain\Operation\FacebookBundle\Validator\PublishStatus as Validator;

class PublishStatusHandler extends AbstractActivityHandler
{
    const DATETIME_FORMAT_TWITTER = 'F j, Y';

    protected $em;
    protected $contentService;
    protected $job;
    protected $session;
    protected $templating;
    protected $validator;

    public function __construct(
        EntityManager $em,
        Status $contentService,
        PublishStatus $job,
        $session,
        TwigEngine $templating,
        Validator $validator
    )
    {
        $this->em = $em;
        $this->contentService = $contentService;
        $this->job = $job;
        $this->session = $session;
        $this->templating = $templating;
        $this->validator = $validator;
    }

    public function createContent(Location $location = null, Campaign $campaign = null)
    {
        // Check whether the status will be published on a User or Page stream.
        $facebookLocation = $this->em
            ->getRepository('CampaignChainLocationFacebookBundle:LocationBase')
            ->findOneByLocation($location);

        if (!$facebookLocation) {
            throw new \Exception(
                'No Facebook location found.'
            );
        }

        if ($facebookLocation instanceof User) {
            $status = new UserStatus();
        } elseif ($facebookLocation instanceof Page) {
            $status = new PageStatus();
        }

        return $status->setFacebookLocation($facebookLocation);
    }

    public function getContent(Location $location, Operation $operation = null)
    {
        return $this->contentService->getStatusByOperation($operation);
    }

    public function processContent(Operation $operation, $data)
    {
        try {
            if(is_array($data)) {
                // If the status has already been created, we modify its data.
                $status = $this->contentService->getStatusByOperation($operation);
                $status->setMessage($data['message']);
                $class = get_class($status);
                if (strpos($class, 'CampaignChain\Operation\FacebookBundle\Entity\UserStatus') !== false) {
                    $status->setPrivacy($data['privacy']);
                }
            } else {
                $status = $data;
            }
        } catch(\Exception $e) {
            // Status has not been created yet, so do it from the form data.
            $status = $data;
        }

        return $status;
    }

    public function postPersistNewEvent(Operation $operation, Form $form, $content = null)
    {
        // Content to be published immediately?
        $this->publishNow($operation, $form);
    }

    public function postPersistEditEvent(Operation $operation, Form $form, $content = null)
    {
        // Content to be published immediately?
        $this->publishNow($operation, $form);
    }

    public function readAction(Operation $operation)
    {
        $status = $this->contentService->getStatusByOperation($operation);

        $statusType = 'user';

        if($status instanceof \CampaignChain\Operation\FacebookBundle\Entity\PageStatus){
            $statusType = 'page';
        }

        $isPublic = true;

        if(
            $statusType == 'user'
            && $status->getPrivacy() != 'EVERYONE'
        ){
            // Check whether it is a protected tweet.
            $isPublic = false;
        }

        if(!$statusType == 'page' && !$isPublic){
            $this->get('session')->getFlashBag()->add(
                'warning',
                'This post is not public.'
            );
        }

        return $this->templating->renderResponse(
            'CampaignChainOperationFacebookBundle::read.html.twig',
            array(
                'page_title' => $operation->getActivity()->getName(),
                'is_public' => $isPublic,
                'status' => $status,
                'activity' => $operation->getActivity(),
                'status_type' => $statusType,
            ));
    }

    private function publishNow(Operation $operation, Form $form)
    {
        if ($form->get('campaignchain_hook_campaignchain_due')->has('execution_choice') && $form->get('campaignchain_hook_campaignchain_due')->get('execution_choice')->getData() == 'now') {
            // Validate whether we can execute the Activity?
            $isExecutable = $this->validator->isExecutableByLocation(
                $this->contentService->getContent($operation), new \DateTime()
            );
            if(!$isExecutable['status']) {
                throw new \Exception($isExecutable['message']);
            }

            $this->job->execute($operation->getId());
            $content = $this->contentService->getStatusByOperation($operation);
            $this->session->getFlashBag()->add(
                'success',
                'The status was published. <a href="'.$content->getUrl().'">View it on Facebook</a>.'
            );

            return true;
        }

        return false;
    }
}<commit_msg>CampaignChain/campaignchain#223 Deal with identical content in campaigns<commit_after><?php
/*
 * Copyright 2016 CampaignChain, Inc. <<EMAIL>>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace CampaignChain\Activity\FacebookBundle\Controller;

use CampaignChain\CoreBundle\Controller\Module\AbstractActivityHandler;
use Symfony\Component\Form\Form;
use CampaignChain\CoreBundle\Entity\Location;
use CampaignChain\CoreBundle\Entity\Campaign;
use CampaignChain\Operation\FacebookBundle\Job\PublishStatus;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\TwigBundle\TwigEngine;
use CampaignChain\CoreBundle\Entity\Operation;
use CampaignChain\Location\FacebookBundle\Entity\Page;
use CampaignChain\Location\FacebookBundle\Entity\User;
use CampaignChain\Operation\FacebookBundle\Entity\PageStatus;
use CampaignChain\Operation\FacebookBundle\Entity\UserStatus;
use CampaignChain\Operation\FacebookBundle\EntityService\Status;
use CampaignChain\Operation\FacebookBundle\Validator\PublishStatusValidator as Validator;

class PublishStatusHandler extends AbstractActivityHandler
{
    const DATETIME_FORMAT_TWITTER = 'F j, Y';

    protected $em;
    protected $contentService;
    protected $job;
    protected $session;
    protected $templating;
    protected $validator;

    public function __construct(
        EntityManager $em,
        Status $contentService,
        PublishStatus $job,
        $session,
        TwigEngine $templating,
        Validator $validator
    )
    {
        $this->em = $em;
        $this->contentService = $contentService;
        $this->job = $job;
        $this->session = $session;
        $this->templating = $templating;
        $this->validator = $validator;
    }

    public function createContent(Location $location = null, Campaign $campaign = null)
    {
        // Check whether the status will be published on a User or Page stream.
        $facebookLocation = $this->em
            ->getRepository('CampaignChainLocationFacebookBundle:LocationBase')
            ->findOneByLocation($location);

        if (!$facebookLocation) {
            throw new \Exception(
                'No Facebook location found.'
            );
        }

        if ($facebookLocation instanceof User) {
            $status = new UserStatus();
        } elseif ($facebookLocation instanceof Page) {
            $status = new PageStatus();
        }

        return $status->setFacebookLocation($facebookLocation);
    }

    public function getContent(Location $location, Operation $operation = null)
    {
        return $this->contentService->getStatusByOperation($operation);
    }

    public function processContent(Operation $operation, $data)
    {
        try {
            if(is_array($data)) {
                // If the status has already been created, we modify its data.
                $status = $this->contentService->getStatusByOperation($operation);
                $status->setMessage($data['message']);
                $class = get_class($status);
                if (strpos($class, 'CampaignChain\Operation\FacebookBundle\Entity\UserStatus') !== false) {
                    $status->setPrivacy($data['privacy']);
                }
            } else {
                $status = $data;
            }
        } catch(\Exception $e) {
            // Status has not been created yet, so do it from the form data.
            $status = $data;
        }

        return $status;
    }

    public function postPersistNewEvent(Operation $operation, Form $form, $content = null)
    {
        // Content to be published immediately?
        $this->publishNow($operation, $form);
    }

    public function postPersistEditEvent(Operation $operation, Form $form, $content = null)
    {
        // Content to be published immediately?
        $this->publishNow($operation, $form);
    }

    public function readAction(Operation $operation)
    {
        $status = $this->contentService->getStatusByOperation($operation);

        $statusType = 'user';

        if($status instanceof \CampaignChain\Operation\FacebookBundle\Entity\PageStatus){
            $statusType = 'page';
        }

        $isPublic = true;

        if(
            $statusType == 'user'
            && $status->getPrivacy() != 'EVERYONE'
        ){
            // Check whether it is a protected tweet.
            $isPublic = false;
        }

        if(!$statusType == 'page' && !$isPublic){
            $this->get('session')->getFlashBag()->add(
                'warning',
                'This post is not public.'
            );
        }

        return $this->templating->renderResponse(
            'CampaignChainOperationFacebookBundle::read.html.twig',
            array(
                'page_title' => $operation->getActivity()->getName(),
                'is_public' => $isPublic,
                'status' => $status,
                'activity' => $operation->getActivity(),
                'status_type' => $statusType,
            ));
    }

    private function publishNow(Operation $operation, Form $form)
    {
        if ($form->get('campaignchain_hook_campaignchain_due')->has('execution_choice') && $form->get('campaignchain_hook_campaignchain_due')->get('execution_choice')->getData() == 'now') {
            // Validate whether we can execute the Activity?
            $isExecutable = $this->validator->isExecutableByLocation(
                $this->contentService->getContent($operation), new \DateTime()
            );
            if(!$isExecutable['status']) {
                throw new \Exception($isExecutable['message']);
            }

            $this->job->execute($operation->getId());
            $content = $this->contentService->getStatusByOperation($operation);
            $this->session->getFlashBag()->add(
                'success',
                'The status was published. <a href="'.$content->getUrl().'">View it on Facebook</a>.'
            );

            return true;
        }

        return false;
    }
}
{'fraction_non_alphanumeric': 0.11336533994114914, 'fraction_numerical': 0.0014712714883072635, 'mean_word_length': 2.444, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 115, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 30, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1990193', 'n_tokens_mistral': 3358, 'n_tokens_neox': 3239, 'n_words': 804}