<commit_before><?php
namespace CsvMigrations\Event;

use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\I18n\Time;
use Cake\Mailer\Email;
use Cake\ORM\Table;
use Cake\Routing\Router;
use Cake\Utility\Inflector;
use CsvMigrations\ConfigurationTrait;
use CsvMigrations\FieldHandlers\FieldHandlerFactory;

class ModelAfterSaveListener implements EventListenerInterface
{
    /**
     * Changelog template
     */
    const CHANGELOG = '* %s: changed from "%s" to "%s".' . "\n";

    /**
     * Ingored modified fields
     *
     * @var array
     */
    protected $_ignoredFields = ['created', 'modified'];

    /**
     * Implemented Events
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'CsvMigrations.Model.afterSave' => 'sendCalendarReminder'
        ];
    }

    /**
     * sendCalendarReminder method
     * Notification about the reminder is sent only
     * when the record belonds to anyone.
     * @param Cake\Event $event from the afterSave
     * @param Cake\Datasource\EntityInterface $entity from the afterSave
     * @return array|bool $sent on whether the email was sent
     */
    public function sendCalendarReminder(Event $event, EntityInterface $entity)
    {
        $sent = false;
        $currentUser = null;

        //get applications's timezone
        $timezone = Time::now()->format('e');
        $dtz = new \DateTimeZone($timezone);

        $table = $event->subject();

        //get attendees Table for the event
        if (method_exists($table, 'getConfig') && is_callable([$table, 'getConfig'])) {
            $config = $table->getConfig();
            $remindersTo = $table->getConfig(ConfigurationTrait::$CONFIG_OPTION_ALLOW_REMINDERS);
        }

        // skip if attendees Table is not defined
        if (empty($remindersTo)) {
            return $sent;
        }

        // Figure out which field is a reminder one
        $reminderField = $table->getReminderFields();
        if (empty($reminderField) || !is_array($reminderField)) {
            return $sent;
        }
        $reminderField = $reminderField[0];
        if (!is_array($reminderField) || empty($reminderField['name'])) {
            return $sent;
        }
        $reminderField = $reminderField['name'];
        // Skip sending email if reminder field is empty
        if (empty($entity->$reminderField)) {
            return $sent;
        }

        $attendeesFields = $this->_getAttendeesFields($table, ['tables' => $remindersTo]);
        // skip if no attendees fields found
        if (empty($attendeesFields)) {
            return $sent;
        }

        // skip if none of the required fields was modified
        $requiredFields = array_merge((array)$reminderField, $attendeesFields);
        if (!$this->_requiredFieldsModified($entity, $requiredFields)) {
            return $sent;
        }

        /*
         * Figure out the subject of the email
         *
         * This should happen AFTER the `$table->getConfig()` call,
         * in case the display field of the table is changed from the
         * configuration.
         *
         * Use singular of the table name and the value of the entity's display field.
         * For example: "Call: Payment remind" or "Lead: Qobo Ltd".
         */
        $fhf = new FieldHandlerFactory();

        $emailSubjectValue = $fhf->renderValue($table, $table->displayField(), $entity->{$table->displayField()}, [ 'renderAs' => 'plain']);

        $eventSubject = $emailSubjectValue ?: 'reminder';
        $emailSubject = Inflector::singularize($table->alias()) . ": " . $eventSubject;
        $emailContent = Inflector::singularize($table->alias()) . ' ' . $emailSubjectValue . " information was ";
        // If the record is being updated, prefix the above subject with "(Updated) ".
        if (!$entity->isNew()) {
            $emailSubject = '(Updated) ' . $emailSubject;
            $emailContent .= "updated";
        } else {
            $emailContent .= "created";
        }

        $emails = $this->_getAttendees($table, $entity, $attendeesFields);

        if (empty($emails)) {
            return $sent;
        }

        if (method_exists($table, 'getCurrentUser') && is_callable([$table, 'getCurrentUser'])) {
            $currentUser = $table->getCurrentUser();
            $emailContent .= " by " . $currentUser['name'];
        }
        // append changelog if entity is not new
        if (!$entity->isNew()) {
            $emailContent .= ":\n\n" . $this->_getChangelog($entity);
        }

        // append link
        $entityUrl = Router::url(['controller' => $table->table(), 'action' => 'view', $entity->id], true);
        $emailContent .= "\n\nSee more: " . $entityUrl;

        foreach ($emails as $email) {
            $vCalendar = new \Eluceo\iCal\Component\Calendar('-//Calendar Events//EN//');
            $vCalendar->setCalendarScale('GREGORIAN');

            $vAttendees = $this->_getEventAttendees($emails);

            $vEvent = $this->_getCalendarEvent($entity, [
                'dtz' => $dtz,
                'organizer' => $email,
                'subject' => $emailSubject,
                'attendees' => $vAttendees,
                'field' => $reminderField,
                'timezone' => $timezone,
                'url' => $entityUrl
            ]);

            if (!$entity->isNew()) {
                $vEvent->setSequence(time());
            } else {
                $vEvent->setSequence(0);
            }

            $vEvent->setUniqueId($entity->id);
            $vEvent->setAttendees($vAttendees);
            $vCalendar->addComponent($vEvent);

            $headers = "Content-Type: text/calendar; charset=utf-8";
            $headers .= 'Content-Disposition: attachment; filename="event.ics"';<commit_msg>Make sure that no prefixes will be auto-appended to URL<commit_after><?php
namespace CsvMigrations\Event;

use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\I18n\Time;
use Cake\Mailer\Email;
use Cake\ORM\Table;
use Cake\Routing\Router;
use Cake\Utility\Inflector;
use CsvMigrations\ConfigurationTrait;
use CsvMigrations\FieldHandlers\FieldHandlerFactory;

class ModelAfterSaveListener implements EventListenerInterface
{
    /**
     * Changelog template
     */
    const CHANGELOG = '* %s: changed from "%s" to "%s".' . "\n";

    /**
     * Ingored modified fields
     *
     * @var array
     */
    protected $_ignoredFields = ['created', 'modified'];

    /**
     * Implemented Events
     * @return array
     */
    public function implementedEvents()
    {
        return [
            'CsvMigrations.Model.afterSave' => 'sendCalendarReminder'
        ];
    }

    /**
     * sendCalendarReminder method
     * Notification about the reminder is sent only
     * when the record belonds to anyone.
     * @param Cake\Event $event from the afterSave
     * @param Cake\Datasource\EntityInterface $entity from the afterSave
     * @return array|bool $sent on whether the email was sent
     */
    public function sendCalendarReminder(Event $event, EntityInterface $entity)
    {
        $sent = false;
        $currentUser = null;

        //get applications's timezone
        $timezone = Time::now()->format('e');
        $dtz = new \DateTimeZone($timezone);

        $table = $event->subject();

        //get attendees Table for the event
        if (method_exists($table, 'getConfig') && is_callable([$table, 'getConfig'])) {
            $config = $table->getConfig();
            $remindersTo = $table->getConfig(ConfigurationTrait::$CONFIG_OPTION_ALLOW_REMINDERS);
        }

        // skip if attendees Table is not defined
        if (empty($remindersTo)) {
            return $sent;
        }

        // Figure out which field is a reminder one
        $reminderField = $table->getReminderFields();
        if (empty($reminderField) || !is_array($reminderField)) {
            return $sent;
        }
        $reminderField = $reminderField[0];
        if (!is_array($reminderField) || empty($reminderField['name'])) {
            return $sent;
        }
        $reminderField = $reminderField['name'];
        // Skip sending email if reminder field is empty
        if (empty($entity->$reminderField)) {
            return $sent;
        }

        $attendeesFields = $this->_getAttendeesFields($table, ['tables' => $remindersTo]);
        // skip if no attendees fields found
        if (empty($attendeesFields)) {
            return $sent;
        }

        // skip if none of the required fields was modified
        $requiredFields = array_merge((array)$reminderField, $attendeesFields);
        if (!$this->_requiredFieldsModified($entity, $requiredFields)) {
            return $sent;
        }

        /*
         * Figure out the subject of the email
         *
         * This should happen AFTER the `$table->getConfig()` call,
         * in case the display field of the table is changed from the
         * configuration.
         *
         * Use singular of the table name and the value of the entity's display field.
         * For example: "Call: Payment remind" or "Lead: Qobo Ltd".
         */
        $fhf = new FieldHandlerFactory();

        $emailSubjectValue = $fhf->renderValue($table, $table->displayField(), $entity->{$table->displayField()}, [ 'renderAs' => 'plain']);

        $eventSubject = $emailSubjectValue ?: 'reminder';
        $emailSubject = Inflector::singularize($table->alias()) . ": " . $eventSubject;
        $emailContent = Inflector::singularize($table->alias()) . ' ' . $emailSubjectValue . " information was ";
        // If the record is being updated, prefix the above subject with "(Updated) ".
        if (!$entity->isNew()) {
            $emailSubject = '(Updated) ' . $emailSubject;
            $emailContent .= "updated";
        } else {
            $emailContent .= "created";
        }

        $emails = $this->_getAttendees($table, $entity, $attendeesFields);

        if (empty($emails)) {
            return $sent;
        }

        if (method_exists($table, 'getCurrentUser') && is_callable([$table, 'getCurrentUser'])) {
            $currentUser = $table->getCurrentUser();
            $emailContent .= " by " . $currentUser['name'];
        }
        // append changelog if entity is not new
        if (!$entity->isNew()) {
            $emailContent .= ":\n\n" . $this->_getChangelog($entity);
        }

        // append link
        $entityUrl = Router::url(['prefix' => false, 'controller' => $table->table(), 'action' => 'view', $entity->id], true);
        $emailContent .= "\n\nSee more: " . $entityUrl;

        foreach ($emails as $email) {
            $vCalendar = new \Eluceo\iCal\Component\Calendar('-//Calendar Events//EN//');
            $vCalendar->setCalendarScale('GREGORIAN');

            $vAttendees = $this->_getEventAttendees($emails);

            $vEvent = $this->_getCalendarEvent($entity, [
                'dtz' => $dtz,
                'organizer' => $email,
                'subject' => $emailSubject,
                'attendees' => $vAttendees,
                'field' => $reminderField,
                'timezone' => $timezone,
                'url' => $entityUrl
            ]);

            if (!$entity->isNew()) {
                $vEvent->setSequence(time());
            } else {
                $vEvent->setSequence(0);
            }

            $vEvent->setUniqueId($entity->id);
            $vEvent->setAttendees($vAttendees);
            $vCalendar->addComponent($vEvent);

            $headers = "Content-Type: text/calendar; charset=utf-8";
            $headers .= 'Content-Disposition: attachment; filename="event.ics"';
{'fraction_non_alphanumeric': 0.13693754766545208, 'fraction_numerical': 0.0008473858147614609, 'mean_word_length': 2.2193126022913257, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 92, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1349689', 'n_tokens_mistral': 3352, 'n_tokens_neox': 3285, 'n_words': 782}