<commit_before><?php

/**
 * MIT License
 * Copyright (c) 2017 Electronic Student Services @ Appalachian State University
 * 
 * See LICENSE file in root directory for copyright and distribution permissions.
 * 
 * @author <NAME> <<EMAIL>>
 * @license https://opensource.org/licenses/MIT
 */

namespace stories\Factory;

use stories\Resource\EntryResource as Resource;
use stories\Factory\AuthorFactory;
use stories\Factory\TagFactory;
use stories\Resource\AuthorResource;
use stories\Exception\MissingInput;
use stories\Exception\ResourceNotFound;
use phpws2\Database;
use Canopy\Request;
use phpws2\Template;

require PHPWS_SOURCE_DIR . 'mod/access/class/Shortcut.php';

class EntryFactory extends BaseFactory
{

    public function build()
    {
        return new Resource;
    }

    /**
     * 
     * @param type $id
     * @return \stories\Resource\EntryResource
     */
    public function load($id)
    {
        $entry = parent::load($id);
        if ($entry->deleted) {
            throw new ResourceNotFound;
        }
        $tagFactory = new TagFactory;
        $entry->tags = $tagFactory->getTagsByEntryId($id);
        return $entry;
    }

    public function adminListView(Request $request)
    {
        $segmentSize = \phpws2\Settings::get('stories', 'segmentSize');
        // if offset not set, default 0
        $offset = (int) $request->pullGetString('offset', true);
        $offsetSize = $segmentSize * $offset;

        $orderBy = $request->pullGetString('sortBy', true);
        if (!in_array($orderBy, array('publishDate', 'title', 'updateDate'))) {
            $orderBy = 'publishDate';
        }

        $search = $request->pullGetString('search', true);

        $options = array(
            'search' => $search,
            'orderBy' => $orderBy,
            'publishedOnly' => false,
            'hideExpired' => true,
            'limit' => $segmentSize,
            'offset' => $offsetSize
        );

        return $this->pullList($options);
    }

    public function pullList(array $options = null)
    {
        $db = Database::getDB();
        $now = time();

        $defaultOptions = array('publishedOnly' => false,
            'hideExpired' => false,
            'orderBy' => 'publishDate',
            'limit' => 30,
            'includeContent' => true,
            'offset' => 0);

        if (is_array($options)) {
            $options = array_merge($defaultOptions, $options);
        } else {
            $options = $defaultOptions;
        }

        $tbl = $db->addTable('storiesEntry');

        $tbl->addField('id');
        $tbl->addField('createDate');
        $tbl->addField('expirationDate');
        $tbl->addField('publishDate');
        $tbl->addField('published');
        $tbl->addField('summary');
        $tbl->addField('thumbnail');
        $tbl->addField('title');
        if ($options['includeContent']) {
            $tbl->addField('content');
        }

        //conditionals
        $tbl->addFieldConditional('deleted', 0);
        if ($options['publishedOnly']) {
            $tbl->addFieldConditional('published', 1);
            $tbl->addFieldConditional('publishDate', $now, '<');
        }

        if (isset($options['search']) && strlen($options['search']) >= 3) {
            $s1 = $db->createConditional($tbl->getField('title'),
                    '%' . $options['search'] . '%', 'like');
            $db->addConditional($s1);
        }

        if (!$options['hideExpired']) {
            $expire1 = $db->createConditional($tbl->getField('expirationDate'),
                    0);
            $expire2 = $db->createConditional($tbl->getField('expirationDate'),
                    $now, '>');
            $db->addConditional($db->createConditional($expire1, $expire1, 'or'));
        }

        $tbl2 = $db->addTable('storiesAuthor');
        $tbl2->addField('name', 'authorName');
        $tbl2->addField('email', 'authorEmail');
        $db->joinResources($tbl, $tbl2,
                $db->createConditional($tbl->getField('authorId'),
                        $tbl2->getField('id')), 'left');
        if (isset($options['orderBy'])) {
            $tbl->addOrderBy($options['orderBy'],
                    $options['orderBy'] === 'title' ? 'asc' : 'desc');
        }

        if (isset($options['limit'])) {
            if (isset($options['offset'])) {
                $db->setLimit($options['limit'], $options['offset']);
            } else {
                $db->setLimit($options['limit']);
            }
        }

        $objectList = $db->selectAsResources('\stories\Resource\EntryResource');
        if (empty($objectList)) {
            return null;
        }
        foreach ($objectList as $entry) {
            $listing[] = $entry->getStringVars();
        }
        return $listing;
    }

    /**
     * Creates the first entry. Should not be used outside its creation.
     * @param string $content
     * @param string $title
     * @return \stories\Resource\Entry
     */
    public function create()
    {
        $entry = $this->build();
        $entry->title = '';
        $entry->content = '';
        $authorFactory = new AuthorFactory;
        $this->loadAuthor($entry, $authorFactory->getByCurrentUser(true));
        return self::saveResource($entry);
    }

    public function form(Resource $entry, $new = false)
    {
        $tagFactory = new TagFactory();

        $sourceHttp = PHPWS_SOURCE_HTTP;
        $insertSource = PHPWS_SOURCE_HTTP . 'mod/stories/javascript/MediumEditor/insert.js';
        $vars['cssOverride'] = $this->mediumCSSOverride();
        $entryId = $entry->id;
        $vars['home'] = $sourceHttp;
        $vars['publishBar'] = $this->scriptView('PublishBar');
        $vars['MediumEditorPack'] = $this->scriptView('MediumEditorPack', false);
        $vars['EntryForm'] = $this->scriptView('EntryForm', false);
        $vars['content'] = $this->prepareFormContent($entry->content);
        $vars['insert'] = "<script src='$insertSource'></script>";
        $vars['published'] = $entry->published ? 1 : 0;
        $vars['publishDate'] = $entry->publishDate;
        $vars['entryId'] = $entryId;
        $vars['title'] = $entry->title;
        $vars['tags'] = json_encode($entry->tags);

        $vars['status'] = $new ? 'Draft' : 'Last updated ' . $this->relativeTime($entry->updateDate);
        $template = new \phpws2\Template($vars);
        $template->setModuleTemplate('stories', 'Entry/Form.html');
        return $template->get();
    }

    public function getByUrlTitle($title)
    {
        $db = Database::getDB();
        $tbl = $db->addTable('storiesEntry');
        $tbl->addFieldConditional('urlTitle', $title);
        $data = $db->selectOneRow();
        if (empty($data)) {
            return null;
        }
        $entry = $this->build();
        $entry->setVars($data);
        return $entry;
    }

    public function mediumCSSOverride()
    {
        $homeHttp = PHPWS_SOURCE_HTTP;
        return <<<EOF
<link rel="stylesheet" type="text/css" href="{$homeHttp}mod/stories/css/MediumOverrides.css" />
EOF;
    }<commit_msg>TagBar added to entry form<commit_after><?php

/**
 * MIT License
 * Copyright (c) 2017 Electronic Student Services @ Appalachian State University
 * 
 * See LICENSE file in root directory for copyright and distribution permissions.
 * 
 * @author <NAME> <<EMAIL>>
 * @license https://opensource.org/licenses/MIT
 */

namespace stories\Factory;

use stories\Resource\EntryResource as Resource;
use stories\Factory\AuthorFactory;
use stories\Factory\TagFactory;
use stories\Resource\AuthorResource;
use stories\Exception\MissingInput;
use stories\Exception\ResourceNotFound;
use phpws2\Database;
use Canopy\Request;
use phpws2\Template;

require PHPWS_SOURCE_DIR . 'mod/access/class/Shortcut.php';

class EntryFactory extends BaseFactory
{

    public function build()
    {
        return new Resource;
    }

    /**
     * 
     * @param type $id
     * @return \stories\Resource\EntryResource
     */
    public function load($id)
    {
        $entry = parent::load($id);
        if ($entry->deleted) {
            throw new ResourceNotFound;
        }
        $tagFactory = new TagFactory;
        $entry->tags = $tagFactory->getTagsByEntryId($id);
        return $entry;
    }

    public function adminListView(Request $request)
    {
        $segmentSize = \phpws2\Settings::get('stories', 'segmentSize');
        // if offset not set, default 0
        $offset = (int) $request->pullGetString('offset', true);
        $offsetSize = $segmentSize * $offset;

        $orderBy = $request->pullGetString('sortBy', true);
        if (!in_array($orderBy, array('publishDate', 'title', 'updateDate'))) {
            $orderBy = 'publishDate';
        }

        $search = $request->pullGetString('search', true);

        $options = array(
            'search' => $search,
            'orderBy' => $orderBy,
            'publishedOnly' => false,
            'hideExpired' => true,
            'limit' => $segmentSize,
            'offset' => $offsetSize
        );

        return $this->pullList($options);
    }

    public function pullList(array $options = null)
    {
        $db = Database::getDB();
        $now = time();

        $defaultOptions = array('publishedOnly' => false,
            'hideExpired' => false,
            'orderBy' => 'publishDate',
            'limit' => 30,
            'includeContent' => true,
            'offset' => 0);

        if (is_array($options)) {
            $options = array_merge($defaultOptions, $options);
        } else {
            $options = $defaultOptions;
        }

        $tbl = $db->addTable('storiesEntry');

        $tbl->addField('id');
        $tbl->addField('createDate');
        $tbl->addField('expirationDate');
        $tbl->addField('publishDate');
        $tbl->addField('published');
        $tbl->addField('summary');
        $tbl->addField('thumbnail');
        $tbl->addField('title');
        if ($options['includeContent']) {
            $tbl->addField('content');
        }

        //conditionals
        $tbl->addFieldConditional('deleted', 0);
        if ($options['publishedOnly']) {
            $tbl->addFieldConditional('published', 1);
            $tbl->addFieldConditional('publishDate', $now, '<');
        }

        if (isset($options['search']) && strlen($options['search']) >= 3) {
            $s1 = $db->createConditional($tbl->getField('title'),
                    '%' . $options['search'] . '%', 'like');
            $db->addConditional($s1);
        }

        if (!$options['hideExpired']) {
            $expire1 = $db->createConditional($tbl->getField('expirationDate'),
                    0);
            $expire2 = $db->createConditional($tbl->getField('expirationDate'),
                    $now, '>');
            $db->addConditional($db->createConditional($expire1, $expire1, 'or'));
        }

        $tbl2 = $db->addTable('storiesAuthor');
        $tbl2->addField('name', 'authorName');
        $tbl2->addField('email', 'authorEmail');
        $db->joinResources($tbl, $tbl2,
                $db->createConditional($tbl->getField('authorId'),
                        $tbl2->getField('id')), 'left');
        if (isset($options['orderBy'])) {
            $tbl->addOrderBy($options['orderBy'],
                    $options['orderBy'] === 'title' ? 'asc' : 'desc');
        }

        if (isset($options['limit'])) {
            if (isset($options['offset'])) {
                $db->setLimit($options['limit'], $options['offset']);
            } else {
                $db->setLimit($options['limit']);
            }
        }

        $objectList = $db->selectAsResources('\stories\Resource\EntryResource');
        if (empty($objectList)) {
            return null;
        }
        foreach ($objectList as $entry) {
            $listing[] = $entry->getStringVars();
        }
        return $listing;
    }

    /**
     * Creates the first entry. Should not be used outside its creation.
     * @param string $content
     * @param string $title
     * @return \stories\Resource\Entry
     */
    public function create()
    {
        $entry = $this->build();
        $entry->title = '';
        $entry->content = '';
        $authorFactory = new AuthorFactory;
        $this->loadAuthor($entry, $authorFactory->getByCurrentUser(true));
        return self::saveResource($entry);
    }

    public function form(Resource $entry, $new = false)
    {
        $tagFactory = new TagFactory();

        $sourceHttp = PHPWS_SOURCE_HTTP;
        $insertSource = PHPWS_SOURCE_HTTP . 'mod/stories/javascript/MediumEditor/insert.js';
        $vars['cssOverride'] = $this->mediumCSSOverride();
        $entryId = $entry->id;
        $vars['home'] = $sourceHttp;
        $vars['publishBar'] = $this->scriptView('PublishBar');
        $vars['tagBar'] = $this->scriptView('TagBar');
        $vars['MediumEditorPack'] = $this->scriptView('MediumEditorPack', false);
        $vars['EntryForm'] = $this->scriptView('EntryForm', false);
        $vars['content'] = $this->prepareFormContent($entry->content);
        $vars['insert'] = "<script src='$insertSource'></script>";
        $vars['published'] = $entry->published ? 1 : 0;
        $vars['publishDate'] = $entry->publishDate;
        $vars['entryId'] = $entryId;
        $vars['title'] = $entry->title;
        $vars['entryTags'] = json_encode($tagFactory->changeToSelectValues($entry->tags));
        $vars['tags'] = json_encode($tagFactory->listTags(true));

        $vars['status'] = $new ? 'Draft' : 'Last updated ' . $this->relativeTime($entry->updateDate);
        $template = new \phpws2\Template($vars);
        $template->setModuleTemplate('stories', 'Entry/Form.html');
        return $template->get();
    }

    public function getByUrlTitle($title)
    {
        $db = Database::getDB();
        $tbl = $db->addTable('storiesEntry');
        $tbl->addFieldConditional('urlTitle', $title);
        $data = $db->selectOneRow();
        if (empty($data)) {
            return null;
        }
        $entry = $this->build();
        $entry->setVars($data);
        return $entry;
    }

    public function mediumCSSOverride()
    {
        $homeHttp = PHPWS_SOURCE_HTTP;
        return <<<EOF
<link rel="stylesheet" type="text/css" href="{$homeHttp}mod/stories/css/MediumOverrides.css" />
EOF;
    }
{'fraction_non_alphanumeric': 0.1670849017147637, 'fraction_numerical': 0.004042938798271295, 'mean_word_length': 2.3710056390977443, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 178, 'https://': 2, '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': '495418', 'n_tokens_mistral': 4155, 'n_tokens_neox': 4061, 'n_words': 746}