Passed
Pull Request — developer (#15265)
by Arkadiusz
20:15
created

Vtiger_ListView_Model::getListViewEntries()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 19
rs 9.7333
ccs 6
cts 6
cp 1
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/* +***********************************************************************************
3
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
4
 * ("License"); You may not use this file except in compliance with the License
5
 * The Original Code is:  vtiger CRM Open Source
6
 * The Initial Developer of the Original Code is vtiger.
7
 * Portions created by vtiger are Copyright (C) vtiger.
8
 * All Rights Reserved.
9
 * Contributor(s): YetiForce.com
10
 * *********************************************************************************** */
11
12
/**
13
 * Vtiger ListView Model Class.
14
 */
15
class Vtiger_ListView_Model extends \App\Base
16
{
17
	/**
18
	 * Function to get the Module Model.
19
	 *
20
	 * @return Vtiger_Module_Model instance
21
	 */
22 1
	public function getModule()
23
	{
24 1
		return $this->get('module');
25
	}
26
27
	/**
28
	 * Static Function to get the Instance of Vtiger ListView model for a given module and custom view.
29
	 *
30
	 * @param string $moduleName - Module Name
31
	 * @param int    $viewId     - Custom View Id
32
	 *
33
	 * @return Vtiger_ListView_Model instance
34
	 */
35 1
	public static function getInstance($moduleName, $viewId = 0)
36
	{
37 1
		$cacheName = $viewId . ':' . $moduleName;
38 1
		if (\App\Cache::staticHas('ListView_Model', $cacheName)) {
39
			return \App\Cache::staticGet('ListView_Model', $cacheName);
40
		}
41 1
		$modelClassName = Vtiger_Loader::getComponentClassName('Model', 'ListView', $moduleName);
42 1
		$instance = new $modelClassName();
43 1
		$moduleModel = Vtiger_Module_Model::getInstance($moduleName);
44 1
		$queryGenerator = new \App\QueryGenerator($moduleModel->getName());
45 1
		if ($viewId) {
46 1
			$instance->set('viewId', $viewId);
47 1
			$queryGenerator->initForCustomViewById($viewId);
48
		} else {
49 1
			if ($viewId = $queryGenerator->initForDefaultCustomView(true, true)) {
50 1
				$instance->set('viewId', $viewId);
51
			} else {
52
				$queryGenerator->loadListFields();
53
			}
54
		}
55 1
		$instance->set('module', $moduleModel)->set('query_generator', $queryGenerator);
56 1
		\App\Cache::staticSave('ListView_Model', $cacheName, $instance);
57
58 1
		return $instance;
59
	}
60
61
	/**
62
	 * Static Function to get the Instance of Vtiger ListView model for a given module and custom view.
63
	 *
64
	 * @param string $value        - Module Name
65
	 * @param mixed  $sourceModule
66
	 * @param int    $cvId
67
	 *
68
	 * @return Vtiger_ListView_Model instance
69
	 */
70
	public static function getInstanceForPopup($value, $sourceModule = false, int $cvId = 0)
71
	{
72
		$modelClassName = Vtiger_Loader::getComponentClassName('Model', 'ListView', $value);
73
		$instance = new $modelClassName();
74
		$moduleModel = Vtiger_Module_Model::getInstance($value);
75
		$queryGenerator = new \App\QueryGenerator($moduleModel->getName());
76
		if (!$sourceModule && !empty($sourceModule)) {
77
			$moduleModel->set('sourceModule', $sourceModule);
78
		}
79
		if ($cvId) {
80
			$instance->set('viewId', $cvId);
81
			$queryGenerator->initForCustomViewById($cvId);
82
		} else {
83
			$moduleModel->getModalRecordsListFields($queryGenerator, $sourceModule);
84
		}
85
86
		return $instance->set('module', $moduleModel)->set('query_generator', $queryGenerator);
87
	}
88
89
	/**
90
	 * Function to get the Quick Links for the List view of the module.
91
	 *
92
	 * @param array $linkParams
93
	 *
94
	 * @return array List of Vtiger_Link_Model instances
95
	 */
96
	public function getHederLinks($linkParams)
97
	{
98
		$links = Vtiger_Link_Model::getAllByType($this->getModule()->getId(), ['LIST_VIEW_HEADER'], $linkParams);
99
100
		$headerLinks = [];
101
		$moduleModel = $this->getModule();
102
		if (App\Config::module('ModTracker', 'WATCHDOG') && $moduleModel->isPermitted('WatchingModule')) {
103
			$watchdog = Vtiger_Watchdog_Model::getInstance($moduleModel->getName());
104
			$class = 'btn-outline-dark';
105
			$iconclass = 'fa-eye-slash';
106
			if ($watchdog->isWatchingModule()) {
107
				$class = 'btn-dark';
108
				$iconclass = 'fa-eye';
109
			}
110
			$headerLinks[] = [
111
				'linktype' => 'LIST_VIEW_HEADER',
112
				'linkhint' => 'BTN_WATCHING_MODULE',
113
				'linkurl' => 'javascript:Vtiger_Index_Js.changeWatching(this)',
114
				'linkclass' => $class,
115
				'linkicon' => 'fas ' . $iconclass,
116
				'linkdata' => ['off' => 'btn-outline-dark', 'on' => 'btn-dark', 'value' => $watchdog->isWatchingModule() ? 0 : 1],
117
				'active' => !$watchdog->isLock(),
118
			];
119
		}
120
		$userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
121
		if ($userPrivilegesModel->hasModuleActionPermission('Notification', 'CreateView')) {
122
			$headerLinks[] = [
123
				'linktype' => 'LIST_VIEW_HEADER',
124
				'linkhint' => 'LBL_SEND_NOTIFICATION',
125
				'linkurl' => 'javascript:Vtiger_Index_Js.sendNotification(this)',
126
				'linkicon' => 'fas fa-paper-plane',
127
			];
128
		}
129
		$openStreetMapModuleModel = Vtiger_Module_Model::getInstance('OpenStreetMap');
130
		if ($userPrivilegesModel->hasModulePermission($openStreetMapModuleModel->getId()) && $openStreetMapModuleModel->isAllowModules($moduleModel->getName())) {
0 ignored issues
show
Bug introduced by
The method isAllowModules() does not exist on Vtiger_Module_Model. It seems like you code against a sub-type of Vtiger_Module_Model such as OpenStreetMap_Module_Model. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

130
		if ($userPrivilegesModel->hasModulePermission($openStreetMapModuleModel->getId()) && $openStreetMapModuleModel->/** @scrutinizer ignore-call */ isAllowModules($moduleModel->getName())) {
Loading history...
131
			$headerLinks[] = [
132
				'linktype' => 'LIST_VIEW_HEADER',
133
				'linkhint' => 'LBL_SHOW_MAP',
134
				'linkurl' => 'javascript:Vtiger_List_Js.showMap()',
135
				'linkicon' => 'fas fa-globe',
136
			];
137
		}
138
		if ($userPrivilegesModel->hasModulePermission('PermissionInspector')) {
0 ignored issues
show
Bug introduced by
'PermissionInspector' of type string is incompatible with the type integer expected by parameter $mixed of Users_Privileges_Model::hasModulePermission(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

138
		if ($userPrivilegesModel->hasModulePermission(/** @scrutinizer ignore-type */ 'PermissionInspector')) {
Loading history...
139
			$headerLinks[] = [
140
				'linktype' => 'LIST_VIEW_HEADER',
141
				'linkhint' => 'BTN_PERMISSION_INSPECTOR',
142
				'linkdata' => ['url' => 'index.php?module=PermissionInspector&view=UserListModal&srcModule=' . $moduleModel->getName()],
143
				'linkicon' => 'fas fa-user-secret',
144
				'modalView' => true,
145
			];
146
		}
147
		foreach ($headerLinks as $headerLink) {
148
			$links['LIST_VIEW_HEADER'][] = Vtiger_Link_Model::getInstanceFromValues($headerLink);
149
		}
150
		return $links;
151
	}
152
153
	/**
154
	 * Function to give advance links of a module.
155
	 *
156
	 * @return array of advanced links
157
	 */
158
	public function getAdvancedLinks()
159
	{
160
		$moduleModel = $this->getModule();
161
		$advancedLinks = [];
162
163
		if ($moduleModel->isPermitted('CreateView') && $moduleModel->isPermitted('Import')) {
164
			$advancedLinks[] = [
165
				'linktype' => 'LISTVIEW',
166
				'linklabel' => 'LBL_IMPORT',
167
				'linkurl' => $moduleModel->getImportUrl(),
168
				'linkicon' => 'fas fa-download',
169
			];
170
		}
171
		if ($moduleModel->isPermitted('Export')) {
172
			$advancedLinks[] = [
173
				'linktype' => 'LISTVIEW',
174
				'linklabel' => 'LBL_EXPORT',
175
				'linkurl' => 'javascript:Vtiger_List_Js.triggerExportAction("' . $this->getModule()->getExportUrl() . '")',
176
				'linkicon' => 'fas fa-upload',
177
			];
178
		}
179
		if ($moduleModel->isPermitted('Merge')) {
180
			$advancedLinks[] = [
181
				'linktype' => 'LISTVIEW',
182
				'linklabel' => 'LBL_MERGING',
183
				'linkicon' => 'yfi yfi-merging-records',
184
				'linkdata' => ['url' => "index.php?module={$moduleModel->getName()}&view=MergeRecords"],
185
				'linkclass' => 'js-mass-action--merge',
186
			];
187
		}
188
		if ($moduleModel->isPermitted('ExportPdf')) {
189
			$handlerClass = Vtiger_Loader::getComponentClassName('Model', 'PDF', $moduleModel->getName());
190
			$pdfModel = new $handlerClass();
191
			$templates = $pdfModel->getActiveTemplatesForModule($moduleModel->getName(), 'List');
192
			if (\count($templates) > 0) {
193
				$advancedLinks[] = [
194
					'linktype' => 'DETAIL_VIEW_ADDITIONAL',
195
					'linklabel' => \App\Language::translate('LBL_EXPORT_PDF'),
196
					'linkdata' => ['url' => 'index.php?module=' . $moduleModel->getName() . '&view=PDF&fromview=List', 'type' => 'modal'],
197
					'linkclass' => 'js-mass-action',
198
					'linkicon' => 'fas fa-file-pdf',
199
					'title' => \App\Language::translate('LBL_EXPORT_PDF'),
200
				];
201
			}
202
		}
203
		if ($moduleModel->isPermitted('QuickExportToExcel')) {
204
			$advancedLinks[] = [
205
				'linktype' => 'LISTVIEWMASSACTION',
206
				'linklabel' => 'LBL_QUICK_EXPORT',
207
				'linkurl' => 'javascript:Vtiger_List_Js.triggerQuickExport("' . $moduleModel->getName() . '")',
208
				'linkicon' => 'fas fa-file-export',
209
			];
210
		}
211
		if ($moduleModel->isPermitted('RecordMappingList')) {
212
			$handlerClass = Vtiger_Loader::getComponentClassName('Model', 'MappedFields', $moduleModel->getName());
213
			$mfModel = new $handlerClass();
214
			$templates = $mfModel->getActiveTemplatesForModule($moduleModel->getName(), 'List');
215
			if (\count($templates) > 0) {
216
				$advancedLinks[] = [
217
					'linktype' => 'LISTVIEW',
218
					'linklabel' => 'LBL_GENERATE_RECORDS',
219
					'linkurl' => 'javascript:Vtiger_List_Js.triggerGenerateRecords();',
220
					'linkicon' => 'fas fa-plus-circle',
221
				];
222
			}
223
		}
224
		return $advancedLinks;
225
	}
226
227
	/**
228
	 * Function to get the list of Mass actions for the module.
229
	 *
230
	 * @param type $linkParams
231
	 *
232
	 * @return Vtiger_Link_Model[]
233
	 */
234
	public function getListViewMassActions($linkParams)
235
	{
236
		$currentUser = Users_Record_Model::getCurrentUserModel();
237
		$moduleModel = $this->getModule();
238
		$links = Vtiger_Link_Model::getAllByType($moduleModel->getId(), ['LISTVIEWMASSACTION'], $linkParams);
0 ignored issues
show
Bug introduced by
$linkParams of type type is incompatible with the type array|boolean expected by parameter $parameters of Vtiger_Link_Model::getAllByType(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

238
		$links = Vtiger_Link_Model::getAllByType($moduleModel->getId(), ['LISTVIEWMASSACTION'], /** @scrutinizer ignore-type */ $linkParams);
Loading history...
239
		$massActionLinks = [];
240
		if ($moduleModel->isPermitted('MassEdit')) {
241
			$massActionLinks[] = [
242
				'linktype' => 'LISTVIEWMASSACTION',
243
				'linklabel' => 'LBL_MASS_EDIT',
244
				'linkurl' => 'javascript:Vtiger_List_Js.triggerMassEdit("index.php?module=' . $moduleModel->getName() . '&view=MassActionAjax&mode=showMassEditForm");',
245
				'linkicon' => 'yfi yfi-full-editing-view',
246
			];
247
		}
248
		if ($moduleModel->isPermitted('MassActive')) {
249
			$massActionLinks[] = [
250
				'linktype' => 'LISTVIEWMASSACTION',
251
				'linklabel' => 'LBL_MASS_ACTIVATE',
252
				'linkurl' => 'javascript:',
253
				'dataUrl' => 'index.php?module=' . $moduleModel->getName() . '&action=MassState&state=Active&sourceView=List',
254
				'linkdata' => ['confirm' => \App\Language::translate('LBL_ACTIVATE_RECORD_DESC')],
255
				'linkclass' => 'js-mass-record-event',
256
				'linkicon' => 'fas fa-undo-alt',
257
			];
258
		}
259
		if ($moduleModel->isPermitted('MassArchived')) {
260
			$massActionLinks[] = [
261
				'linktype' => 'LISTVIEWMASSACTION',
262
				'linklabel' => 'LBL_MASS_ARCHIVE',
263
				'linkurl' => 'javascript:',
264
				'dataUrl' => 'index.php?module=' . $moduleModel->getName() . '&action=MassState&state=Archived&sourceView=List',
265
				'linkdata' => ['confirm' => \App\Language::translate('LBL_ARCHIVE_RECORD_DESC')],
266
				'linkclass' => 'js-mass-record-event',
267
				'linkicon' => 'fas fa-archive',
268
			];
269
		}
270
		if ($moduleModel->isPermitted('MassTrash')) {
271
			$massActionLinks[] = [
272
				'linktype' => 'LISTVIEWMASSACTION',
273
				'linklabel' => 'LBL_MASS_MOVE_TO_TRASH',
274
				'linkurl' => 'javascript:',
275
				'dataUrl' => 'index.php?module=' . $moduleModel->getName() . '&action=MassState&state=Trash&sourceView=List',
276
				'linkdata' => ['confirm' => \App\Language::translate('LBL_MOVE_TO_TRASH_DESC')],
277
				'linkclass' => 'js-mass-record-event',
278
				'linkicon' => 'fas fa-trash-alt',
279
			];
280
		}
281
		if ($moduleModel->isPermitted('MassDelete')) {
282
			$massActionLinks[] = [
283
				'linktype' => 'LISTVIEWMASSACTION',
284
				'linklabel' => 'LBL_MASS_DELETE',
285
				'linkurl' => 'javascript:',
286
				'dataUrl' => 'index.php?module=' . $moduleModel->getName() . '&action=MassDelete&sourceView=List',
287
				'linkdata' => ['confirm' => \App\Language::translate('LBL_DELETE_RECORD_COMPLETELY_DESC')],
288
				'linkclass' => 'js-mass-record-event',
289
				'linkicon' => 'fas fa-eraser',
290
			];
291
		}
292
		$modCommentsModel = Vtiger_Module_Model::getInstance('ModComments');
293
		if ($moduleModel->isCommentEnabled() && $modCommentsModel->isPermitted('CreateView') && $moduleModel->isPermitted('MassAddComment')) {
294
			$massActionLinks[] = [
295
				'linktype' => 'LISTVIEWMASSACTION',
296
				'linklabel' => 'LBL_MASS_ADD_COMMENT',
297
				'linkurl' => 'javascript:Vtiger_List_Js.triggerMassComment("index.php?module=' . $moduleModel->getName() . '&view=MassActionAjax&mode=showAddCommentForm")',
298
				'linkicon' => 'fas fa-comments',
299
			];
300
		}
301
		if ($moduleModel->isPermitted('MassTransferOwnership')) {
302
			$massActionLinks[] = [
303
				'linktype' => 'LISTVIEWMASSACTION',
304
				'linklabel' => 'LBL_TRANSFER_OWNERSHIP',
305
				'linkurl' => 'javascript:Vtiger_List_Js.triggerTransferOwnership("index.php?module=' . $moduleModel->getName() . '&view=MassActionAjax&mode=transferOwnership")',
306
				'linkicon' => 'yfi yfi-change-of-owner',
307
			];
308
		}
309
		if ($moduleModel->isTrackingEnabled() && App\Config::module('ModTracker', 'UNREVIEWED_COUNT') && $moduleModel->isPermitted('ReviewingUpdates') && $currentUser->getId() === $currentUser->getRealId()) {
310
			$massActionLinks[] = [
311
				'linktype' => 'LISTVIEWMASSACTION',
312
				'linklabel' => 'LBL_REVIEW_CHANGES',
313
				'linkurl' => 'javascript:Vtiger_List_Js.triggerReviewChanges("index.php?module=ModTracker&sourceModule=' . $moduleModel->getName() . '&action=ChangesReviewedOn&mode=reviewChanges")',
314
				'linkicon' => 'fas fa-check-circle',
315
			];
316
		}
317
		if ($moduleModel->isPermitted('RecordConventer') && \App\RecordConverter::isActive($moduleModel->getName(), 'List')) {
318
			$massActionLinks[] = [
319
				'linktype' => 'LISTVIEWMASSACTION',
320
				'linklabel' => 'LBL_RECORD_CONVERTER',
321
				'linkdata' => ['url' => "index.php?module={$moduleModel->getName()}&view=RecordConverter&sourceView=List", 'type' => 'modal'],
322
				'linkicon' => 'fas fa-exchange-alt',
323
				'linkclass' => 'u-cursor-pointer js-mass-action',
324
			];
325
		}
326
		foreach ($massActionLinks as $massActionLink) {
327
			$links['LISTVIEWMASSACTION'][] = Vtiger_Link_Model::getInstanceFromValues($massActionLink);
328
		}
329
		return $links;
330
	}
331
332
	/**
333
	 * Function to get Basic links.
334
	 *
335
	 * @return array of Basic links
336
	 */
337
	public function getBasicLinks()
338
	{
339
		$basicLinks = [];
340
		$moduleModel = $this->getModule();
341
342
		if ($moduleModel->isPermitted('CreateView')) {
343
			$basicLinks[] = [
344
				'linktype' => 'LISTVIEWBASIC',
345
				'linklabel' => 'LBL_ADD_RECORD',
346
				'linkurl' => $moduleModel->getCreateRecordUrl(),
347
				'linkclass' => 'btn-light addButton modCT_' . $moduleModel->getName(),
348
				'linkicon' => 'fas fa-plus',
349
				'showLabel' => 1,
350
				'linkhref' => true,
351
			];
352
		}
353
354
		if ($moduleModel->isPermitted('ExportPdf')) {
355
			$handlerClass = Vtiger_Loader::getComponentClassName('Model', 'PDF', $moduleModel->getName());
356
			$pdfModel = new $handlerClass();
357
			$templates = $pdfModel->getActiveTemplatesForModule($moduleModel->getName(), 'List');
358
			if (\count($templates) > 0) {
359
				$basicLinks[] = [
360
					'linktype' => 'LISTVIEWBASIC',
361
					'linkdata' => ['url' => 'index.php?module=' . $moduleModel->getName() . '&view=PDF&fromview=List', 'type' => 'modal'],
362
					'linkclass' => 'btn-light js-mass-record-event',
363
					'linkicon' => 'fas fa-file-pdf',
364
					'linkhint' => \App\Language::translate('LBL_EXPORT_PDF'),
365
				];
366
			}
367
		}
368
		return $basicLinks;
369
	}
370
371
	/**
372
	 * Function to get the list of listview links for the module.
373
	 *
374
	 * @param <Array> $linkParams
0 ignored issues
show
Documentation Bug introduced by
The doc comment <Array> at position 0 could not be parsed: Unknown type name '<' at position 0 in <Array>.
Loading history...
375
	 *
376
	 * @return <Array> - Associate array of Link Type to List of Vtiger_Link_Model instances
0 ignored issues
show
Documentation Bug introduced by
The doc comment <Array> at position 0 could not be parsed: Unknown type name '<' at position 0 in <Array>.
Loading history...
377
	 */
378
	public function getListViewLinks($linkParams)
379
	{
380
		$moduleModel = $this->getModule();
381
		$links = ['LISTVIEWBASIC' => []];
382
383
		$basicLinks = $this->getBasicLinks();
384
		foreach ($basicLinks as $basicLink) {
385
			$links['LISTVIEWBASIC'][] = Vtiger_Link_Model::getInstanceFromValues($basicLink);
386
		}
387
388
		$allLinks = Vtiger_Link_Model::getAllByType($moduleModel->getId(), ['LISTVIEWBASIC', 'LISTVIEW'], $linkParams);
389
		if (!empty($allLinks)) {
390
			foreach ($allLinks as $type => $allLinksByType) {
391
				foreach ($allLinksByType as $linkModel) {
392
					$links[$type][] = $linkModel;
393
				}
394
			}
395
		}
396
397
		$advancedLinks = $this->getAdvancedLinks();
398
		foreach ($advancedLinks as $advancedLink) {
399
			$links['LISTVIEW'][] = Vtiger_Link_Model::getInstanceFromValues($advancedLink);
400
		}
401
		return $links;
402 1
	}
403
404 1
	/**
405
	 * Get query generator instance.
406
	 *
407
	 * @return \App\QueryGenerator
408
	 */
409
	public function getQueryGenerator()
410
	{
411
		return $this->get('query_generator');
412 1
	}
413
414 1
	/**
415 1
	 * Function to get the list view header.
416
	 *
417
	 * @return Vtiger_Field_Model[] - List of Vtiger_Field_Model instances
418
	 */
419
	public function getListViewHeaders()
420
	{
421 1
		$headerFieldModels = [];
422 1
		if ($this->isEmpty('viewId')) {
423 1
			$queryGenerator = $this->getQueryGenerator();
424
			$queryGenerator->setFields(array_values($this->getModule()->getPopupFields()));
425
			$queryGenerator->setField('id');
426
			$headerFields = $queryGenerator->getListViewFields();
427
		} else {
428 1
			$headerFields = [];
429 1
			if (!$this->isEmpty('header_fields')) {
430 1
				$fields = $this->get('header_fields');
431 1
			} else {
432
				$customView = App\CustomView::getInstance($this->getModule()->getName());
433
				$fields = $customView->getColumnsListByCvid($this->get('viewId'));
434
			}
435 1
			foreach ($fields as $fieldInfo) {
436 1
				$fieldName = $fieldInfo['field_name'];
437
				$fieldModel = Vtiger_Field_Model::getInstance($fieldName, Vtiger_Module_Model::getInstance($fieldInfo['module_name']));
438
				if (!empty($fieldInfo['source_field_name'])) {
439
					if (!$this->getModule()->getFieldByName($fieldInfo['source_field_name'])->isActiveField()) {
440
						continue;
441 1
					}
442
					$fieldModel->set('source_field_name', $fieldInfo['source_field_name']);
443
					$fieldModel->set('isCalculateField', false);
444 1
				} else {
445 1
					$queryGenerator = $this->getQueryGenerator();
446 1
					if ($field = $queryGenerator->getQueryField($fieldName)->getListViewFields()) {
447
						$queryGenerator->setField($field->getName());
448 1
						$headerFields[] = $field;
449
					}
450 1
				}
451
				$headerFields[] = $fieldModel;
452
			}
453
		}
454
		foreach ($headerFields as $fieldModel) {
455
			if ($fieldModel && (!$fieldModel->isViewable() || !$fieldModel->getPermissions())) {
456 1
				continue;
457
			}
458 1
			$name = $fieldModel->get('source_field_name') ? "{$fieldModel->getName()}:{$fieldModel->getModuleName()}:{$fieldModel->get('source_field_name')}" : $fieldModel->getName();
459 1
			$headerFieldModels[$name] = $fieldModel;
460
		}
461
		return $headerFieldModels;
462
	}
463
464
	/**
465
	 * Set list view order by.
466
	 */
467
	public function loadListViewOrderBy()
468
	{
469
		$orderBy = $this->get('orderby');
470
		if (!empty($orderBy) && \is_array($orderBy)) {
471 1
			$fields = $this->getModule()->getFields();
472
			foreach ($orderBy as $fieldName => $sortFlag) {
473
				[$fieldName, $moduleName, $sourceFieldName] = array_pad(explode(':', $fieldName), 3, false);
474
				if ($sourceFieldName && isset($fields[$sourceFieldName])) {
475
					$this->getQueryGenerator()->setRelatedOrder([
476 1
						'sourceField' => $sourceFieldName,
477
						'relatedModule' => $moduleName,
478 1
						'relatedField' => $fieldName,
479 1
						'relatedSortOrder' => $sortFlag,
480
					]);
481
				} elseif (isset($fields[$fieldName])) {
482 1
					$this->getQueryGenerator()->setOrder($fieldName, $sortFlag);
483 1
				}
484
			}
485
		}
486 1
	}
487 1
488
	/**
489 1
	 * Load list view conditions.
490
	 */
491
	public function loadListViewCondition()
492
	{
493
		$queryGenerator = $this->getQueryGenerator();
494
		if ($entityState = $this->get('entityState')) {
495
			$queryGenerator->setStateCondition($entityState);
496
		}
497 1
		$srcRecord = $this->get('src_record');
498 1
		if ($this->getModule()->get('name') === $this->get('src_module') && !empty($srcRecord)) {
499
			$queryGenerator->addCondition('id', $srcRecord, 'n');
500
		}
501 1
		if ($searchParams = $this->get('search_params')) {
502 1
			$queryGenerator->parseAdvFilter($searchParams);
503
		}
504
		if ($operator = $this->get('operator')) {
505
			$searchKey = $this->get('search_key');
506
			$searchValue = $this->get('search_value');
507
			if ('s' === $operator && 1 === \strlen($searchValue)) {
0 ignored issues
show
Bug introduced by
It seems like $searchValue can also be of type null; however, parameter $string of strlen() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

507
			if ('s' === $operator && 1 === \strlen(/** @scrutinizer ignore-type */ $searchValue)) {
Loading history...
508
				$searchValue = [$searchValue, strtolower($searchValue)];
0 ignored issues
show
Bug introduced by
It seems like $searchValue can also be of type null; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

508
				$searchValue = [$searchValue, strtolower(/** @scrutinizer ignore-type */ $searchValue)];
Loading history...
509
			}
510
			$queryGenerator->addCondition($searchKey, $searchValue, $operator);
511
		}
512 1
		$searchResult = $this->get('searchResult');
513
		if ($searchResult && \is_array($searchResult)) {
514
			$queryGenerator->addNativeCondition(['vtiger_crmentity.crmid' => $searchResult]);
515
		}
516
		$sourceModule = $this->get('src_module');
517
		if ($sourceModule) {
518
			$moduleModel = $this->getModule();
519
520
			if (method_exists($moduleModel, 'getQueryByModuleField')) {
521 1
				$moduleModel->getQueryByModuleField($sourceModule, $this->get('src_field'), $this->get('src_record'), $queryGenerator);
522
			}
523 1
			if (method_exists($moduleModel, 'getQueryByRelatedField')) {
524 1
				$moduleModel->getQueryByRelatedField($this, $queryGenerator);
525 1
			}
526 1
		}
527 1
	}
528 1
529
	/**
530 1
	 * Function to get the list view entries.
531 1
	 *
532 1
	 * @param Vtiger_Paging_Model $pagingModel
533 1
	 *
534
	 * @return Vtiger_Record_Model[] - Associative array of record id mapped to Vtiger_Record_Model instance.
535
	 */
536
	public function getListViewEntries(Vtiger_Paging_Model $pagingModel)
537 1
	{
538
		$this->loadListViewCondition();
539
		$this->loadListViewOrderBy();
540 1
		$pageLimit = $pagingModel->getPageLimit();
541 1
		$query = $this->getQueryGenerator()->createQuery();
542 1
		$query->limit($pageLimit + 1)->offset($pagingModel->getStartIndex());
543
		$rows = $query->all();
544
		$count = \count($rows);
545
		$pagingModel->calculatePageRange($count);
546
		if ($count > $pageLimit) {
547
			array_pop($rows);
548
			$pagingModel->set('nextPageExists', true);
549
		} else {
550
			$pagingModel->set('nextPageExists', false);
551
		}
552 1
		$listViewRecordModels = $this->getRecordsFromArray($rows);
553
		unset($rows);
554 1
		return $listViewRecordModels;
555 1
	}
556 1
557
	/**
558
	 * Function to get the list view all entries.
559 1
	 *
560 1
	 * @return Vtiger_Record_Model[] - Associative array of record id mapped to Vtiger_Record_Model instance.
561 1
	 */
562
	public function getAllEntries()
563
	{
564
		$this->loadListViewCondition();
565
		$this->loadListViewOrderBy();
566
		return $this->getRecordsFromArray($this->getQueryGenerator()->createQuery()->all());
567
	}
568
569
	/**
570
	 * Get models of records from array.
571
	 *
572
	 * @param array $rows
573 1
	 *
574 1
	 * @return \Vtiger_Record_Model[]
575 1
	 */
576
	public function getRecordsFromArray(array $rows)
577 1
	{
578
		$listViewRecordModels = $relatedFields = [];
579
		$moduleModel = $this->getModule();
580
		foreach ($this->getQueryGenerator()->getRelatedFields() as $fieldInfo) {
581
			$relatedFields[$fieldInfo['relatedModule']][$fieldInfo['sourceField']][] = $fieldInfo['relatedField'];
582
		}
583
		foreach ($rows as $row) {
584
			$extRecordModel = [];
585
			foreach ($relatedFields as $relatedModuleName => $fields) {
586
				foreach ($fields as $sourceField => $field) {
587
					$recordData = [
588
						'id' => $row[$sourceField . $relatedModuleName . 'id'] ?? 0,
589
					];
590
					foreach ($field as $relatedFieldName) {
591
						$recordData[$relatedFieldName] = $row[$sourceField . $relatedModuleName . $relatedFieldName];
592
						unset($row[$sourceField . $relatedModuleName . $relatedFieldName]);
593
					}
594
					$extRecordModel[$sourceField][$relatedModuleName] = Vtiger_Module_Model::getInstance($relatedModuleName)->getRecordFromArray($recordData);
595
				}
596
			}
597
			$recordModel = $moduleModel->getRecordFromArray($row);
598
			$recordModel->ext = $extRecordModel;
599
			$listViewRecordModels[$row['id']] = $recordModel;
600
		}
601
		return $listViewRecordModels;
602
	}
603
604
	/**
605
	 * Function to get the list view entries.
606
	 *
607
	 * @param Vtiger_Paging_Model $pagingModel
608
	 *
609
	 * @return array - Associative array of record id mapped to Vtiger_Record_Model instance.
610
	 */
611
	public function getListViewCount()
612
	{
613
		$this->loadListViewCondition();
614
		return $this->getQueryGenerator()->createQuery()->count();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getQueryGe...>createQuery()->count() returns the type integer|string which is incompatible with the documented return type array.
Loading history...
615
	}
616
617
	/**
618
	 * Locked fields according to parameters passed.
619
	 *
620
	 * @param App\Request $request
621
	 *
622
	 * @return void
623
	 */
624
	public function loadSearchLockedFields(App\Request $request): void
625
	{
626
		$moduleModel = $this->getModule();
627
		if (!$request->isEmpty('lockedFields')) {
628
			foreach ($request->getArray('lockedFields') as $value) {
629
				$fieldModel = $moduleModel->getFieldByName($value);
630
				$fieldModel->set('searchLockedFields', true);
631
			}
632
		}
633
		if (!$request->isEmpty('lockedEmptyFields')) {
634
			foreach ($request->getArray('lockedEmptyFields') as $value) {
635
				$fieldModel = $moduleModel->getFieldByName($value);
636
				$fieldModel->set('searchLockedEmptyFields', true);
637
			}
638
		}
639
	}
640
}
641