Passed
Push — developer ( 4e3135...f5c82a )
by Radosław
30:25 queued 12:59
created

Mail::getAttachmentsFromDocument()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 19
rs 9.2222
c 0
b 0
f 0
ccs 0
cts 2
cp 0
cc 6
nc 10
nop 2
crap 42
1
<?php
2
3
namespace App;
4
5
/**
6
 * Mail basic class.
7
 *
8
 * @package App
9
 *
10
 * @copyright YetiForce S.A.
11
 * @license   YetiForce Public License 5.0 (licenses/LicenseEN.txt or yetiforce.com)
12
 * @author    Mariusz Krzaczkowski <[email protected]>
13
 * @author    Radosław Skrzypczak <[email protected]>
14
 */
15
class Mail
16
{
17
	/** @var int Default smtp ID */
18
	public const SMTP_DEFOULT = 0;
19
	/** @var string Table name for configuration */
20
	public const TABLE_NAME_CONFIG = 'yetiforce_mail_config';
21
22
	/**
23
	 * Get smtp server by id.
24
	 *
25
	 * @param int $smtpId
26
	 *
27
	 * @return array
28
	 */
29
	public static function getSmtpById(int $smtpId): array
30
	{
31
		return static::getSmtpServers()[$smtpId] ?? [];
32
	}
33
34
	/**
35
	 * Get a list of all smtp servers.
36
	 *
37
	 * @return array
38
	 */
39
	public static function getAll()
40
	{
41
		if (Cache::has('SmtpServers', 'all')) {
42
			return Cache::get('SmtpServers', 'all');
43
		}
44
		$all = (new Db\Query())->from('s_#__mail_smtp')->indexBy('id')->all(Db::getInstance('admin'));
45
		Cache::save('SmtpServers', 'all', $all, Cache::LONG);
46
47
		return $all;
48
	}
49
50
	public static function getSmtpServers(bool $skipDefault = false): array
51
	{
52
		$all = [];
53
		if (Cache::has('SmtpServers', 'all')) {
54
			$all = Cache::get('SmtpServers', 'all');
55
		} else {
56
			$dataReader = (new Db\Query())->from('s_#__mail_smtp')->createCommand(Db::getInstance('admin'))->query();
57 1
			while ($row = $dataReader->read()) {
58
				$all[$row['id']] = $row;
59 1
				if ($row['default']) {
60
					$all[self::SMTP_DEFOULT] = $row;
61
				}
62 1
			}
63 1
			Cache::save('SmtpServers', 'all', $all, Cache::LONG);
64 1
		}
65
		if ($skipDefault) {
66 1
			unset($all[self::SMTP_DEFOULT]);
67
		}
68 1
69
		return $all;
70
	}
71
72
	/**
73
	 * Get default smtp ID.
74
	 *
75
	 * @return int
76
	 */
77
	public static function getDefaultSmtp()
78
	{
79
		return static::getSmtpById(static::SMTP_DEFOULT)['id'] ?? key(static::getSmtpServers());
0 ignored issues
show
Bug Best Practice introduced by
The expression return static::getSmtpBy...atic::getSmtpServers()) also could return the type string which is incompatible with the documented return type integer.
Loading history...
80
	}
81
82
	/**
83
	 * Get template list for module.
84
	 *
85
	 * @param string   $moduleName
86
	 * @param string   $type
87
	 * @param bool     $hideSystem
88
	 * @param int|null $userId
89
	 *
90
	 * @return array
91
	 */
92
	public static function getTemplateList(string $moduleName = '', string $type = '', bool $hideSystem = true, ?int $userId = null)
93
	{
94
		$queryGenerator = new \App\QueryGenerator('EmailTemplates', $userId ?? \App\User::getCurrentUserId());
95
		$queryGenerator->setFields(['id', 'name', 'module_name']);
96
		if ($moduleName) {
97
			$queryGenerator->addCondition('module_name', $moduleName, 'e');
98
		}
99
		if ($type) {
100
			$queryGenerator->addCondition('email_template_type', $type, 'e');
101
		}
102
		if ($hideSystem) {
103
			$queryGenerator->addNativeCondition(['u_#__emailtemplates.sys_name' => [null, '']]);
104
		}
105 1
		return $queryGenerator->createQuery()->all();
106
	}
107 1
108 1
	/**
109
	 * Get mail template.
110 1
	 *
111 1
	 * @param int|string $id
112 1
	 * @param bool       $attachments
113
	 *
114
	 * @return array
115
	 */
116
	public static function getTemplate($id, bool $attachments = true): array
117
	{
118
		if (!is_numeric($id)) {
119
			$id = self::getTemplateIdFromSysName($id);
120
		}
121
		if (!$id || !\App\Record::isExists($id, 'EmailTemplates')) {
122
			return [];
123 1
		}
124
		$template = \Vtiger_Record_Model::getInstanceById($id, 'EmailTemplates');
125 1
		if (!$attachments) {
126 1
			return $template->getData();
127
		}
128
		return array_merge(
129 1
			$template->getData(), static::getAttachmentsFromTemplate($template->getId())
130 1
		);
131 1
	}
132 1
133 1
	/**
134 1
	 * Get template ID.
135
	 *
136 1
	 * @param string $name
137
	 *
138
	 * @return int|null
139
	 */
140
	public static function getTemplateIdFromSysName(string $name): ?int
141
	{
142
		$cacheName = 'TemplateIdFromSysName';
143
		if (Cache::has($cacheName, '')) {
144
			$templates = Cache::get($cacheName, '');
145
		} else {
146 1
			$queryGenerator = new \App\QueryGenerator('EmailTemplates');
147
			$queryGenerator->setFields(['id']);
148 1
			$queryGenerator->permissions = false;
149
			$queryGenerator->addNativeCondition(['not', ['sys_name' => null]]);
150
			$templates = $queryGenerator->createQuery()->select(['sys_name', 'emailtemplatesid'])->createCommand()->queryAllByGroup();
151 1
			Cache::save($cacheName, '', $templates, Cache::LONG);
152 1
		}
153 1
		return $templates[$name] ?? null;
154 1
	}
155 1
156
	/**
157
	 * Get attachments email template.
158 1
	 *
159
	 * @param int|string $id
160 1
	 *
161
	 * @return array
162
	 */
163
	public static function getAttachmentsFromTemplate($id)
164
	{
165
		if (Cache::has('MailAttachmentsFromTemplete', $id)) {
166
			return Cache::get('MailAttachmentsFromTemplete', $id);
167
		}
168
		$ids = (new \App\Db\Query())->select(['u_#__documents_emailtemplates.crmid'])->from('u_#__documents_emailtemplates')
169
			->innerJoin('vtiger_crmentity', 'u_#__documents_emailtemplates.relcrmid = vtiger_crmentity.crmid')
170
			->where(['vtiger_crmentity.deleted' => 0, 'u_#__documents_emailtemplates.relcrmid' => $id])->column();
171
		$attachments = [];
172
		if ($ids) {
173
			$attachments['attachments'] = ['ids' => $ids];
174
		}
175
		Cache::save('MailAttachmentsFromTemplete', $id, $attachments, Cache::LONG);
176
		return $attachments;
177
	}
178
179
	/**
180
	 * Get attachments from document.
181
	 *
182
	 * @param int|int[] $ids
183
	 * @param mixed     $returnOnlyName
184
	 *
185
	 * @return array
186
	 */
187
	public static function getAttachmentsFromDocument($ids, $returnOnlyName = true)
188
	{
189
		$cacheId = "$returnOnlyName|" . \is_array($ids) ? implode(',', $ids) : $ids;
190
		if (Cache::has('MailAttachmentsFromDocument', $cacheId)) {
191
			return Cache::get('MailAttachmentsFromDocument', $cacheId);
192
		}
193
		$query = (new \App\Db\Query())->select(['vtiger_attachments.*'])->from('vtiger_attachments')
194
			->innerJoin('vtiger_seattachmentsrel', 'vtiger_attachments.attachmentsid = vtiger_seattachmentsrel.attachmentsid')
195
			->where(['vtiger_seattachmentsrel.crmid' => $ids]);
196
		$attachments = [];
197
		$dataReader = $query->createCommand()->query();
198
		while ($row = $dataReader->read()) {
199
			$filePath = realpath(ROOT_DIRECTORY . \DIRECTORY_SEPARATOR . $row['path'] . $row['attachmentsid']);
200
			if (is_file($filePath)) {
201
				$attachments[$filePath] = $returnOnlyName ? Purifier::decodeHtml($row['name']) : $row;
202
			}
203
		}
204
		Cache::save('MailAttachmentsFromDocument', $cacheId, $attachments, Cache::LONG);
205
		return $attachments;
206
	}
207
208
	/**
209
	 * Get attr form send mail button.
210
	 *
211
	 * @param string      $email
212
	 * @param int|null    $record
213
	 * @param string|null $view
214
	 * @param string|null $type
215
	 *
216
	 * @return string
217
	 */
218
	public static function getComposeAttr(string $email, ?int $record = null, ?string $view = null, ?string $type = null): string
219
	{
220
		$return = '';
221
		foreach ([
222
			'email' => $email,
223
			'record' => $record,
224
			'view' => $view,
225
			'type' => $type,
226
		] as $key => $value) {
227
			if (null !== $value) {
228
				$return .= 'data-' . $key . '="' . Purifier::encodeHtml($value) . '" ';
229
			}
230
		}
231
		return $return;
232
	}
233
234
	/**
235
	 * Get user composer.
236
	 *
237
	 * @return string
238
	 */
239
	public static function getMailComposer(): string
240
	{
241
		if (Cache::staticHas('MailMailComposer')) {
242
			return Cache::staticGet('MailMailComposer');
243
		}
244
		$composer = \App\User::getCurrentUserModel()->getDetail('internal_mailer');
245
		if (!\Config\Main::$isActiveSendingMails || 1 == $composer || 'Base' !== $composer && ($composerInstance = self::getComposerInstance($composer)) && !$composerInstance->isActive()) {
0 ignored issues
show
Bug introduced by
The type Config\Main was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
246
			$composer = 'Base';
247
		}
248
		Cache::staticSave('MailMailComposer', '', $composer);
249
		return $composer;
250
	}
251
252
	/**
253
	 * Get composer instance.
254
	 *
255
	 * @param string $name
256
	 *
257
	 * @return \App\Mail\Composers\Base|null
258
	 */
259
	public static function getComposerInstance(string $name): ?Mail\Composers\Base
260
	{
261
		if (Cache::staticHas('MailComposerInstance', $name)) {
262
			return Cache::staticGet('MailComposerInstance', $name);
263
		}
264
		$className = '\App\Mail\Composers\\' . $name;
265
		if (!class_exists($className)) {
266
			\App\Log::warning('Not found composer class: ' . $className);
267
			return null;
268
		}
269
		$composer = new $className();
270
		Cache::staticSave('MailComposerInstance', $name, $composer);
271
		return $composer;
272
	}
273
274
	/**
275
	 * Check if the user has access to the internal mail client.
276
	 *
277
	 * @return bool
278
	 */
279
	public static function checkInternalMailClient(): bool
280
	{
281
		return 'InternalClient' === self::getMailComposer();
282
	}
283
284
	/**
285
	 * Get mail configuration by type.
286
	 *
287
	 * @param string $type
288
	 * @param string $field
289
	 *
290
	 * @return string|array
291
	 */
292
	public static function getConfig(string $type, string $field = '')
293
	{
294
		if (Cache::has('MailConfiguration', $type)) {
295
			$config = Cache::get('MailConfiguration', $type);
296
		} else {
297
			$config = (new \App\Db\Query())->from(self::TABLE_NAME_CONFIG)->indexBy('name')->where(['type' => $type])->all();
298
			Cache::save('MailConfiguration', $type, $config);
299
		}
300
301
		return $field ? $config[$field]['value'] ?? '' : $config;
302
	}
303
}
304