1<?php
2namespace go\core\model;
3
4use go\core\db\Criteria;
5use go\core\fs\Blob;
6use go\core\acl\model\AclOwnerEntity;
7use go\core\validate\ErrorCode;
8
9/**
10 * Newsletter model
11 *
12 * @copyright (c) 2019, Intermesh BV http://www.intermesh.nl
13 * @author Merijn Schering <mschering@intermesh.nl>
14 * @license http://www.gnu.org/licenses/agpl-3.0.html AGPLv3
15 */
16
17class EmailTemplate extends AclOwnerEntity
18{
19
20	/**
21	 *
22	 * @var int
23	 */
24	public $id;
25
26
27	/**
28	 *
29	 * @var int
30	 */
31	protected $moduleId;
32
33	/**
34	 *
35	 * @var string
36	 */
37	public $body;
38
39	/**
40	 *
41	 * @var string
42	 */
43	public $name;
44
45	/**
46	 *
47	 * @var string
48	 */
49	public $subject;
50
51	/**
52	 *
53	 * @var EmailTemplateAttachment[]
54	 */
55	public $attachments = [];
56
57
58	protected static function defineMapping()
59	{
60		return parent::defineMapping()
61			->addTable("core_email_template", "newsletter")
62			->addArray('attachments', EmailTemplateAttachment::class, ['id' => 'emailTemplateId']);
63	}
64
65
66	protected static function defineFilters() {
67		return parent::defineFilters()
68						->add('module', function (Criteria $criteria, $module){
69              $module = Module::findByName($module['package'], $module['name']);
70							$criteria->where(['moduleId' => $module->id]);
71						});
72
73	}
74
75	protected static function textFilterColumns() {
76		return ['name'];
77	}
78
79	/**
80	 *
81	 */
82  public function setModule($module) {
83
84		if(is_int($module)) {
85			$this->moduleId = $module;
86			return;
87		}
88    $module = Module::findByName($module['package'], $module['name']);
89    if(!$module) {
90      $this->setValidationError('module', ErrorCode::INVALID_INPUT, 'Module was not found');
91    }
92    $this->moduleId = $module->id;
93  }
94
95	protected function internalSave()
96	{
97		$this->parseImages();
98
99		return parent::internalSave();
100	}
101
102
103	private function parseImages()
104	{
105		$cids = Blob::parseFromHtml($this->body);
106
107		$existing = [];
108		foreach ($this->attachments as $a) {
109			$existing[$a->blobId] = $a;
110		}
111		$this->attachments = [];
112		foreach ($cids as $blobId) {
113			$blob = Blob::findById($blobId);
114			if(isset($existing[$blobId])) {
115				$existing[$blobId]->inline = true;
116				$this->attachments[] = $existing[$blobId];
117			} else {
118				$this->attachments[] = (new EmailTemplateAttachment())->setValues(['blobId' => $blobId, 'name' => $blob->name, 'inline' => true]);
119			}
120		}
121
122		foreach ($existing as $a) {
123			if ($a->attachment) {
124				$this->attachments[] = $a;
125			}
126		}
127	}
128
129	public function toArray($properties = [])
130	{
131		$array =  parent::toArray($properties);
132
133		if(isset($array['attachments'])) {
134			$array['attachments'] = array_filter($array['attachments'], function($a) {
135				return $a['attachment'] == true;
136			});
137		}
138
139		return $array;
140	}
141}
142