<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\Operation\MailChimpBundle\Job;

use CampaignChain\CoreBundle\Entity\Action;
use CampaignChain\CoreBundle\Exception\ExternalApiException;
use Doctrine\ORM\EntityManager;
use CampaignChain\CoreBundle\Entity\Medium;
use CampaignChain\CoreBundle\Job\JobActionInterface;
use Symfony\Component\HttpFoundation\Response;
use CampaignChain\CoreBundle\EntityService\CTAService;

class SendNewsletter implements JobActionInterface
{
    protected $em;
    protected $container;
    protected $message;
    protected $operation;
    protected $url;

    public function __construct(EntityManager $em, $container)
    {
        $this->em = $em;
        $this->container = $container;
    }

    public function getMessage(){
        return $this->message;
    }
    
    public function execute($operationId)
    {
        $localNewsletter = $this->em
          ->getRepository('CampaignChainOperationMailChimpBundle:MailChimpNewsletter')
          ->findOneByOperation($operationId);

        if (!$localNewsletter) {
            throw new \Exception(
                'No newsletter found for an operation with ID: '.$operationId
            );
        }

        // Connect to MailChimp REST API.
        $restService = $this->container->get('campaignchain.channel.mailchimp.rest.client');
        $client = $restService->connectByActivity($localNewsletter->getOperation()->getActivity());

        /*
         * Get remote newsletter data.
         */

        $remoteNewsletterData = $client->campaigns->getList(array(
            'campaign_id' => $localNewsletter->getCampaignId(),
        ));

        $remoteNewsletter = $remoteNewsletterData['data'][0];

        /*
         * Grab the raw newsletter content and parse all included URLs to see
         * if they are pointing to Channels connected with CampaignChain. If so,
         * then add a tracking ID.
         */

        // Get the newsletter content in raw HTML format.
        $newsletterContent = $client->campaigns->content(
            $localNewsletter->getCampaignId(),
            array(
                'view' => 'raw',
            )
        );

        // Set template_id to null to be able to paste parsed HTML.
        if($remoteNewsletter['template_id'] != 0){
            $client->campaigns->update(
                $localNewsletter->getCampaignId(),
                'options',
                array(
                    'template_id' => null,
                )
            );
        }

        // Process URLs in message and save the new message text, now including
        // the replaced URLs with the Tracking ID attached for call to action tracking.
        $ctaService = $this->container->get('campaignchain.core.cta');
        $ctaNewsletterContent = $ctaService->processCTAs(
                                    $newsletterContent['html'],
                                    $localNewsletter->getOperation(),
                                    CTAService::FORMAT_HTML
                                )->getContent();

        $updatedNewsletter = $client->campaigns->update(
            $localNewsletter->getCampaignId(),
            'content',<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\Operation\MailChimpBundle\Job;

use CampaignChain\CoreBundle\Entity\Action;
use CampaignChain\CoreBundle\Exception\ExternalApiException;
use Doctrine\ORM\EntityManager;
use CampaignChain\CoreBundle\Entity\Medium;
use CampaignChain\CoreBundle\Job\JobActionInterface;
use Symfony\Component\HttpFoundation\Response;
use CampaignChain\CoreBundle\EntityService\CTAService;

class SendNewsletter implements JobActionInterface
{
    protected $em;
    protected $container;
    protected $message;
    protected $operation;
    protected $url;

    public function __construct(EntityManager $em, $container)
    {
        $this->em = $em;
        $this->container = $container;
    }

    public function getMessage(){
        return $this->message;
    }
    
    public function execute($operationId)
    {
        $localNewsletter = $this->em
          ->getRepository('CampaignChainOperationMailChimpBundle:MailChimpNewsletter')
          ->findOneByOperation($operationId);

        if (!$localNewsletter) {
            throw new \Exception(
                'No newsletter found for an operation with ID: '.$operationId
            );
        }

        // Connect to MailChimp REST API.
        $restService = $this->container->get('campaignchain.channel.mailchimp.rest.client');
        $client = $restService->connectByActivity($localNewsletter->getOperation()->getActivity());

        /*
         * Get remote newsletter data.
         */

        $remoteNewsletterData = $client->campaigns->getList(array(
            'campaign_id' => $localNewsletter->getCampaignId(),
        ));

        $remoteNewsletter = $remoteNewsletterData['data'][0];

        /*
         * Grab the raw newsletter content and parse all included URLs to see
         * if they are pointing to Channels connected with CampaignChain. If so,
         * then add a tracking ID.
         */

        // Get the newsletter content in raw HTML format.
        $newsletterContent = $client->campaigns->content(
            $localNewsletter->getCampaignId(),
            array(
                'view' => 'raw',
            )
        );

        // Set template_id to null to be able to paste parsed HTML.
        if($remoteNewsletter['template_id'] != 0){
            $client->campaigns->update(
                $localNewsletter->getCampaignId(),
                'options',
                array(
                    'template_id' => null,
                )
            );
        }

        // Process URLs in message and save the new message text, now including
        // the replaced URLs with the Tracking ID attached for call to action tracking.
        $ctaService = $this->container->get('campaignchain.core.cta');
        $options['format'] = CTAService::FORMAT_HTML;
        $ctaNewsletterContent = $ctaService->processCTAs(
                                    $newsletterContent['html'],
                                    $localNewsletter->getOperation(),
                                    $options
                                )->getContent();

        $updatedNewsletter = $client->campaigns->update(
            $localNewsletter->getCampaignId(),
            'content',
{'fraction_non_alphanumeric': 0.09786569495054659, 'fraction_numerical': 0.002993232691306611, 'mean_word_length': 2.3082221265604823, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1421082', 'n_tokens_mistral': 1962, 'n_tokens_neox': 1874, 'n_words': 539}