-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathdbobject.class.php
More file actions
6979 lines (6382 loc) · 204 KB
/
dbobject.class.php
File metadata and controls
6979 lines (6382 loc) · 204 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Core\MetaModel\FriendlyNameType;
use Combodo\iTop\Service\Events\EventData;
use Combodo\iTop\Service\Events\EventException;
use Combodo\iTop\Service\Events\EventService;
use Combodo\iTop\Service\Events\EventServiceLog;
use Combodo\iTop\Service\Module\ModuleService;
use Combodo\iTop\Service\SummaryCard\SummaryCardService;
use Combodo\iTop\Service\TemporaryObjects\TemporaryObjectManager;
/**
* All objects to be displayed in the application (either as a list or as details)
* must implement this interface.
*
* @internal this interface is implemented by DBObject, you should extends DBObject instead of implementing iDisplay
*/
interface iDisplay
{
/**
* Maps the given context parameter name to the appropriate filter/search code for this class
* @param string $sContextParam Name of the context parameter, i.e. 'org_id'
* @return string Filter code, i.e. 'customer_id'
*/
public static function MapContextParam($sContextParam);
/**
* This function returns a 'hilight' CSS class, used to hilight a given row in a table
* There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
* HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
* To Be overridden by derived classes
* @param void
* @return String The desired higlight class for the object/row
*/
public function GetHilightClass();
/**
* Returns the relative path to the page that handles the display of the object
* @return string
*/
public static function GetUIPage();
/**
* Displays the details of the object
*/
public function DisplayDetails(WebPage $oPage, $bEditMode = false);
}
/**
* Class dbObject: the root of persistent classes
*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
*/
require_once('metamodel.class.php');
require_once('deletionplan.class.inc.php');
require_once('mutex.class.inc.php');
/**
* A persistent object, as defined by the metamodel
*
* @package iTopORM
* @api
* @overwritable-hook
*/
abstract class DBObject implements iDisplay
{
/**
* @var string For sorting based on the XML order (like in iTop 3.0 and older)
* @since 3.1.0 N°1345
*/
public const ENUM_TRANSITIONS_SORT_TYPE_XML = 'xml';
/**
* @var string For sorting based on the transitions labels
* @since 3.1.0 N°1345
*/
public const ENUM_TRANSITIONS_SORT_TYPE_ALPHABETICAL = 'alphabetical';
/**
* @var string For sorting based on the arrival states rank, ascending sort
* @since 3.1.0 N°1345
*/
public const ENUM_TRANSITIONS_SORT_TYPE_FIXED = 'fixed';
/**
* @var string For sorting based on the arrival states rank but depending on the current state (first transitions to states with higher ranks, then transitions to states with lower ranks)
* @since 3.1.0 N°1345
*/
public const ENUM_TRANSITIONS_SORT_TYPE_RELATIVE = 'relative';
/**
* @var string Default sort type of the transitions
* @since 3.1.0 N°1345
*/
public const DEFAULT_TRANSITIONS_SORT_TYPE = self::ENUM_TRANSITIONS_SORT_TYPE_RELATIVE;
private static $m_aMemoryObjectsByClass = array();
/** @var array class => array of ('table' => array of (array of <sql_value>)) */
private static $m_aBulkInsertItems = array();
/** @var array class => array of ('table' => array of <sql_column>) */
private static $m_aBulkInsertCols = array();
private static $m_bBulkInsert = false;
/** @var bool true IF the object is mapped to a DB record */
protected $m_bIsInDB = false;
protected $m_iKey = null;
/** @var array attcode => value : corresponding current value (the new value passed to {@see DBObject::Set()}). Reset during {@see DBObject::DBUpdate()} */
private $m_aCurrValues = array();
/** @var array attcode => value : previous values before the {@see DBObject::Set()} call. Array is reset at the end of {@see DBObject::DBUpdate()} */
protected $m_aOrigValues = array();
protected $m_aExtendedData = null;
/**
* @var bool Is dirty (true) if a modification is ongoing.
*
* @internal The object may have incorrect external keys, then any attempt of reload must be avoided
*/
private $m_bDirty = false;
/**
* @var boolean|null true if the object has been verified and is consistent with integrity rules.
* If null, then the check has to be performed again to know the status
* @see CheckToWrite()
*/
private $m_bCheckStatus = null;
/**
* @var null|boolean true if cannot be saved because of security reason
* @see CheckToWrite()
*/
protected $m_bSecurityIssue = null;
/**
* @var null|string[] list of issues preventing DB write
* @see CheckToWrite()
*/
protected $m_aCheckIssues = null;
/**
* @var null|string[] list of warnings thrown during DB write
* @see CheckToWrite()
* @since 2.6.0 N°659 uniqueness constraints
*/
protected $m_aCheckWarnings = null;
protected $m_aDeleteIssues = null;
/** @var bool Compound objects can be partially loaded */
private $m_bFullyLoaded = false;
/** @var array Compound objects can be partially loaded, array of sAttCode */
private $m_aLoadedAtt = array();
/** @var array list of (potentially) modified sAttCodes */
protected $m_aTouchedAtt = array();
/**
* @var array real modification status
* for each attCode can be:
* * unset => don't know,
* * true => modified,
* * false => not modified (the same value as the original value was set)
*/
protected $m_aModifiedAtt = array();
/**
* @var array attname => value : value before the last {@see DBObject::Set()} call. Set at the beginning of {@see DBObject::DBUpdate()}.
* @see DBObject::ListPreviousValuesForUpdatedAttributes() getter for this attribute
* @since 2.7.0 N°2293
*/
protected $m_aPreviousValuesForUpdatedAttributes;
/**
* @var array Set of Synch data related to this object
* <ul>
* <li>key: sourceId
* <li>value : array of source, attributes, replica
* </ul>
*
* @see #GetSynchroData
*/
protected $m_aSynchroData = null;
protected $m_sHighlightCode = null;
protected $m_aCallbacks = array();
/**
* @var string local events suffix
*/
protected $m_sObjectUniqId = '';
protected $m_bIsReadOnly = false;
protected $m_sReadOnlyMessage = '';
/** @var \DBObject Source object when updating links */
protected $m_oLinkHostObject = null;
/**
* @var array{array{
* type: string,
* class: string,
* id: string,
* }} List all the CRUD stack in progress, with :
* - type: CRUD operation (INSERT, UPDATE, DELETE)',
* - class: class of the object in the CRUD process, leaf (object finalclass) if we have a hierarchy
*
* @since 3.1.0 N°5906
*/
protected static array $m_aCrudStack = [];
/** @var array Context for update insert operations */
private array $aContext = [];
// Protect DBUpdate against infinite loop
protected $iUpdateLoopCount;
const MAX_UPDATE_LOOP_COUNT = 10;
private $aEventListeners = [];
private array $aAllowedTransitions = [];
private ?string $sStimulusBeingApplied = null;
/**
* DBObject constructor.
*
* You should preferably use MetaModel::NewObject() instead of this constructor.
* The whole collection of parameters is [*optional*] please refer to DBObjectSet::FromRow()
*
* @internal The availability of this method is not guaranteed in the long term, you should preferably use MetaModel::NewObject().
* @see MetaModel::NewObject()
*
* @param null|array $aRow If given : DBObjectSet::FromRow() will be used to fetch the object
* @param string $sClassAlias
* @param null|array $aAttToLoad
* @param null|array $aExtendedDataSpec
*
* @throws CoreException
*/
public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
{
$this->iUpdateLoopCount = 0;
if (!empty($aRow))
{
$this->FromRow($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
$this->m_bFullyLoaded = $this->IsFullyLoaded();
$this->m_aTouchedAtt = array();
$this->m_aModifiedAtt = array();
$this->m_sObjectUniqId = get_class($this).'::'.$this->GetKey().'_'.uniqId('', true);
$this->RegisterEventListeners();
return;
}
// Creation of a brand new object
//
$this->m_iKey = self::GetNextTempId(get_class($this));
// set default values
foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
{
$this->m_aCurrValues[$sAttCode] = $this->GetDefaultValue($sAttCode);
$this->m_aOrigValues[$sAttCode] = null;
if (!$oAttDef->IsExternalField() && !$oAttDef instanceof AttributeFriendlyName) {
// No need to trigger a reload action for that attribute
// Let's consider it as being already fully loaded
$this->m_aLoadedAtt[$sAttCode] = true;
}
}
$this->UpdateMetaAttributes();
$this->m_sObjectUniqId = get_class($this).'::0'.'_'.uniqId('', true);
$this->RegisterEventListeners();
}
/**
* @see RegisterCRUDListener
* @see EventService::RegisterListener()
*/
protected function RegisterEventListeners()
{
}
/**
* Update meta-attributes depending on the given attribute list
*
* @internal
*
* @param array|null $aAttCodes List of att codes
*
* @throws \CoreException
*/
protected function UpdateMetaAttributes($aAttCodes = null)
{
if (is_null($aAttCodes))
{
$aAttCodes = MetaModel::GetAttributesList(get_class($this));
}
foreach ($aAttCodes as $sAttCode)
{
foreach (MetaModel::ListMetaAttributes(get_class($this), $sAttCode) as $sMetaAttCode => $oMetaAttDef)
{
/** @var \AttributeMetaEnum $oMetaAttDef */
$this->_Set($sMetaAttCode, $oMetaAttDef->MapValue($this));
}
}
}
/**
* Mark the object as dirty
*
* Once dirty the object may be written to the DB, it is NOT possible to reload it
* or at least not possible to reload it the same way
*
* @internal
*/
public function RegisterAsDirty()
{
$this->m_bDirty = true;
}
/**
* Whether the object is already persisted in DB or not.
*
* @api
*
* @return bool
*/
public function IsNew()
{
return (!$this->m_bIsInDB);
}
/**
* Returns an Id for memory objects
*
* @internal
*
* @param string $sClass
*
* @return int
* @throws CoreException
*/
static protected function GetNextTempId($sClass)
{
$sRootClass = MetaModel::GetRootClass($sClass);
if (!array_key_exists($sRootClass, self::$m_aMemoryObjectsByClass))
{
self::$m_aMemoryObjectsByClass[$sRootClass] = 0;
}
self::$m_aMemoryObjectsByClass[$sRootClass]++;
return (- self::$m_aMemoryObjectsByClass[$sRootClass]);
}
/**
* HTML String representation of the object
*
* Only a few meaningful information will be returned.
* This representation is for debugging purposes, and is subject to change.
* The returned string is raw HTML
*
* @return string
* @throws CoreException
*/
public function __toString()
{
$sRet = '';
$sClass = get_class($this);
$sRootClass = MetaModel::GetRootClass($sClass);
$iPKey = $this->GetKey();
$sFriendlyname = $this->GetAsHTML('friendlyname');
$sRet .= "<b title=\"$sRootClass\">$sClass</b>::$iPKey ($sFriendlyname)<br/>\n";
return $sRet;
}
/**
* Alias of DBObject::Reload()
*
* Restore initial values
*
* @see Reload()
*
* @throws CoreException
*/
public function DBRevert()
{
$this->Reload();
}
/**
* Is the current instance fully or partially loaded.
*
* This method compute the state in realtime.
* In almost every case it is preferable to use DBObject::m_bFullyLoaded.
*
* @internal
* @see m_bFullyLoaded
*
* @return bool
* @throws CoreException
*/
protected function IsFullyLoaded()
{
foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
{
if (!$oAttDef->LoadInObject()) continue;
if (!isset($this->m_aLoadedAtt[$sAttCode]) || !$this->m_aLoadedAtt[$sAttCode])
{
return false;
}
}
return true;
}
/**
* Reload the object from the DB.
*
* This is mostly used after a lazy load (automatically performed by the framework)
* This will erase any pending changes.
*
* @throws CoreException
*/
public function Reload()
{
assert($this->m_bIsInDB);
$this->FireEvent(EVENT_DB_OBJECT_RELOAD);
$aRow = MetaModel::MakeSingleRow(get_class($this), $this->m_iKey, false /* must be found */, true /* AllowAllData */);
if (empty($aRow))
{
$sErrorMessage = "Failed to reload object of class '".get_class($this)."', id = ".$this->m_iKey.', DBIsReadOnly = '.(int) MetaModel::DBIsReadOnly();
IssueLog::Error("$sErrorMessage:\n".MyHelpers::get_callstack_text(1));
throw new CoreException("$sErrorMessage (see the log for more information)");
}
$this->FromRow($aRow);
// Process linked set attributes
//
foreach(MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode=>$oAttDef)
{
if (!$oAttDef->IsLinkSet()) continue;
$this->m_aCurrValues[$sAttCode] = $oAttDef->GetDefaultValue($this);
$this->m_aOrigValues[$sAttCode] = clone $this->m_aCurrValues[$sAttCode];
$this->m_aLoadedAtt[$sAttCode] = true;
}
$this->m_bFullyLoaded = true;
$this->m_aTouchedAtt = array();
$this->m_aModifiedAtt = array();
}
/**
* Initialize the instance against a given structured array
*
* @internal
* @see GetExtendedData() extended data
*
* @param array $aRow an array under the form: `<AttributeCode> => <value>`
* @param string $sClassAlias if not null, it is preprended to the `<AttributeCode>` part of $aRow
* @param null|array $aAttToLoad List of attribute that will be fetched against the database anyway
* @param null|array $aExtendedDataSpec List of attribute that will be marked as DBObject::GetExtendedData()
*
* @return bool
* @throws CoreException
*/
protected function FromRow($aRow, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
{
if (strlen($sClassAlias) == 0)
{
// Default to the current class
$sClassAlias = get_class($this);
}
$this->m_iKey = null;
$this->m_bIsInDB = true;
$this->m_aCurrValues = array();
$this->m_aOrigValues = array();
$this->m_aLoadedAtt = array();
$this->m_bCheckStatus = true;
$this->m_aCheckIssues = [];
$this->m_bSecurityIssue = [];
// Get the key
//
$sKeyField = $sClassAlias."id";
if (!array_key_exists($sKeyField, $aRow))
{
// #@# Bug ?
throw new CoreException("Missing key for class '".get_class($this)."'");
}
$iPKey = $aRow[$sKeyField];
if (!self::IsValidPKey($iPKey))
{
if (is_null($iPKey))
{
throw new CoreException("Missing object id in query result (found null)");
}
else
{
throw new CoreException("An object id must be an integer value ($iPKey)");
}
}
$this->m_iKey = $iPKey;
// Build the object from an array of "attCode"=>"value")
//
$bFullyLoaded = true; // ... set to false if any attribute is not found
if (is_null($aAttToLoad) || !array_key_exists($sClassAlias, $aAttToLoad))
{
$aAttList = MetaModel::ListAttributeDefs(get_class($this));
}
else
{
$aAttList = $aAttToLoad[$sClassAlias];
}
foreach($aAttList as $sAttCode=>$oAttDef)
{
// Skip links (could not be loaded by the mean of this query)
/** @var \AttributeDefinition $oAttDef */
if ($oAttDef->IsLinkSet()) continue;
if (!$oAttDef->LoadInObject()) continue;
unset($value);
$bIsDefined = false;
if ($oAttDef->LoadFromClassTables())
{
// Note: we assume that, for a given attribute, if it can be loaded,
// then one column will be found with an empty suffix, the others have a suffix
// Take care: the function isset will return false in case the value is null,
// which is something that could happen on open joins
$sAttRef = $sClassAlias.$sAttCode;
// Due to custom formatting rules, empty friendlynames may be rendered as non-empty strings
// let's fix this and make sure we render an empty string if the key == 0
if ($oAttDef instanceof AttributeExternalField && $oAttDef->IsFriendlyName()) {
$sKeyRef = $sClassAlias.$oAttDef->GetKeyAttCode();
if (array_key_exists($sKeyRef, $aRow) && $aRow[$sKeyRef] == '0') {
$value = '';
$bIsDefined = true;
}
}
if (!$bIsDefined && array_key_exists($sAttRef, $aRow))
{
$value = $oAttDef->FromSQLToValue($aRow, $sAttRef);
$bIsDefined = true;
}
}
else
{
$value = $oAttDef->ReadExternalValues($this);
$bIsDefined = true;
}
if ($bIsDefined)
{
$this->m_aCurrValues[$sAttCode] = $value;
if (is_object($value))
{
$this->m_aOrigValues[$sAttCode] = clone $value;
}
else
{
$this->m_aOrigValues[$sAttCode] = $value;
}
$this->m_aLoadedAtt[$sAttCode] = true;
}
else
{
// This attribute was expected and not found in the query columns
$bFullyLoaded = false;
}
}
// Load extended data
if ($aExtendedDataSpec != null)
{
foreach($aExtendedDataSpec['fields'] as $sColumn)
{
$sColRef = $sClassAlias.'_extdata_'.$sColumn;
if (array_key_exists($sColRef, $aRow))
{
$this->m_aExtendedData[$sColumn] = $aRow[$sColRef];
}
}
}
return $bFullyLoaded;
}
/**
* Protected raw Setter
*
* This method is an internal plumbing : it sets the value without doing any of the required processes.
* The exposed API Setter is DBObject::Set()
*
* @internal
* @see Set()
*
* @param string $sAttCode
* @param mixed $value
*/
protected function _Set($sAttCode, $value)
{
$this->m_aCurrValues[$sAttCode] = $value;
$this->m_aTouchedAtt[$sAttCode] = true;
unset($this->m_aModifiedAtt[$sAttCode]);
}
/**
* Attributes setter
*
* Set $sAttCode to $value.
* The value must be valid according to the type of attribute : see the different {@see AttributeDefinition::MakeRealValue()} implementations
* The value will not be recorded into the DB until DBObject::DBWrite() is called.
*
* @api
*
* @param string $sAttCode
* @param mixed $value
*
* @return bool
* @throws CoreException
* @throws CoreUnexpectedValue
*
* @see DBWrite()
*/
public function Set($sAttCode, $value)
{
if (!utils::StartsWith(get_class($this), 'CMDBChange') && $this->GetKey() > 0) {
if (is_object($value) || is_array($value)) {
$this->LogCRUDEnter(__METHOD__, "$sAttCode => object or array");
} else {
$this->LogCRUDEnter(__METHOD__, "$sAttCode => ".print_r($value, true));
}
}
$sMessage = $this->IsReadOnly();
if ($sMessage !== false) {
throw new CoreException($sMessage);
}
if ($sAttCode == 'finalclass') {
// Ignore it - this attribute is set upon object creation and that's it
return false;
}
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
if (!$oAttDef->IsWritable()) {
$sClass = get_class($this);
throw new Exception("Attempting to set the value on the read-only attribute $sClass::$sAttCode");
}
if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty) {
// First time Set is called... ensure that the object gets fully loaded
// Otherwise we would lose the values on a further Reload
// + consistency does not make sense !
$sFullyLoaded = $this->m_bFullyLoaded ? 'true' : 'false';
$sDirty = $this->m_bDirty ? 'true' : 'false';
$this->LogCRUDDebug(__METHOD__, "IsInDB: $this->m_bIsInDB, FullyLoaded: $sFullyLoaded, Dirty: $sDirty");
$this->Reload();
}
if ($oAttDef->IsExternalKey() && is_object($value)) {
// Setting an external key with a whole object (instead of just an ID)
// let's initialize also the external fields that depend on it
// (useful when building objects in memory and not from a query)
/** @var \AttributeExternalKey $oAttDef */
if ((get_class($value) != $oAttDef->GetTargetClass()) && (!is_subclass_of($value, $oAttDef->GetTargetClass()))) {
throw new CoreUnexpectedValue("Trying to set the value of '$sAttCode', to an object of class '".get_class($value)."', whereas it's an ExtKey to '".$oAttDef->GetTargetClass()."'. Ignored");
}
foreach (MetaModel::GetDependentAttributes(get_class($this), $sAttCode) as $sCode) {
$oDef = MetaModel::GetAttributeDef(get_class($this), $sCode);
/** @var \AttributeExternalField $oDef */
if ($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode)) {
/** @var \DBObject $value */
$this->m_aCurrValues[$sCode] = $value->Get($oDef->GetExtAttCode());
$this->m_aLoadedAtt[$sCode] = true;
}
elseif ($oDef->IsBasedOnOQLExpression()) {
$this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
unset($this->m_aLoadedAtt[$sCode]);
}
}
} else {
if ($this->m_aCurrValues[$sAttCode] !== $value) {
// Invalidate dependent fields so that they get reloaded in case they are needed (See Get())
//
foreach (MetaModel::GetDependentAttributes(get_class($this), $sAttCode) as $sCode) {
$oDef = MetaModel::GetAttributeDef(get_class($this), $sCode);
if (($oDef->IsExternalField() && ($oDef->GetKeyAttCode() == $sAttCode)) || $oDef->IsBasedOnOQLExpression()) {
$this->m_aCurrValues[$sCode] = $this->GetDefaultValue($sCode);
unset($this->m_aLoadedAtt[$sCode]);
}
}
}
}
if ($oAttDef->IsLinkSet() && ($value != null)) {
$realvalue = clone $this->m_aCurrValues[$sAttCode];
/** @var iDBObjectSetIterator $value */
$realvalue->UpdateFromCompleteList($value);
} else {
$realvalue = $oAttDef->MakeRealValue($value, $this);
}
$this->_Set($sAttCode, $realvalue);
$this->UpdateMetaAttributes(array($sAttCode));
// The object has changed, reset caches
$this->m_bCheckStatus = null;
// Make sure we do not reload it anymore... before saving it
$this->RegisterAsDirty();
// This function is eligible as a lifecycle action: returning true upon success is a must
return true;
}
/**
* Helper to set a value only if it is currently undefined
*
* Call Set() only of the internal representation of the attribute is null.
*
* @api
* @see Set()
*
* @param string $sAttCode
* @param mixed $value
*
* @throws \CoreException
* @throws \CoreUnexpectedValue
* @throws \Exception
* @since 2.6.0
*/
public function SetIfNull($sAttCode, $value)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
$oCurrentValue = $this->Get($sAttCode);
if ($oAttDef->IsNull($oCurrentValue))
{
$this->Set($sAttCode, $value);
}
}
/**
* Helper to copy a value only if the target is currently undefined
*
* Call Copy() only of the internal representation of the target attribute is null.
*
* @api
* @see Copy()
* @see SetIfNull())
*
* @param string $sDestAttCode
* @param string $sSourceAttCode
*
* @return bool true if copy was successfull or was not performed because target attribute isn't null
*
* @throws \CoreException
* @throws \CoreUnexpectedValue
* @throws \Exception
*/
public function CopyIfNull($sDestAttCode, $sSourceAttCode)
{
$this->SetIfNull($sDestAttCode, $this->Get($sSourceAttCode));
return true;
}
/**
* Helper to set a value that fits the attribute max size
*
* compare $sValue against the field's max size in the database, and truncate it's ending in order to make it fit.
* If $sValue is short enough, nothing is done.
*
* @api
*
* @param string $sAttCode
* @param string $sValue
*
* @throws CoreException
* @throws CoreUnexpectedValue
*/
public function SetTrim($sAttCode, $sValue)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
$iMaxSize = $oAttDef->GetMaxSize();
$sLength = mb_strlen($sValue);
if ($iMaxSize && ($sLength > $iMaxSize)) {
$sMessage = " -truncated ($sLength chars)";
$sValue = mb_substr($sValue, 0, $iMaxSize - mb_strlen($sMessage)).$sMessage;
}
$this->Set($sAttCode, $sValue);
}
/**
* @throws \CoreException
* @throws \CoreUnexpectedValue
* @throws \MySQLException
* @throws \OQLException
* @throws \ReflectionException
*/
protected function PreDeleteActions(): void
{
$this->SetReadOnly('No modification allowed before delete');
$this->FireEventAboutToDelete();
$oKPI = new ExecutionKPI();
$this->OnDelete();
$oKPI->ComputeStatsForExtension($this, 'OnDelete');
// Activate any existing trigger
$sClass = get_class($this);
$aParams = array('class_list' => MetaModel::EnumParentClasses($sClass, ENUM_PARENT_CLASSES_ALL));
$oSet = new DBObjectSet(DBObjectSearch::FromOQL('SELECT TriggerOnObjectDelete AS t WHERE t.target_class IN (:class_list)'), array(),
$aParams);
while ($oTrigger = $oSet->Fetch()) {
/** @var \TriggerOnObjectDelete $oTrigger */
try {
$oKPI = new ExecutionKPI();
$oTrigger->DoActivate($this->ToArgs('this'));
}
catch (Exception $e) {
$oTrigger->LogException($e, $this);
utils::EnrichRaisedException($oTrigger, $e);
}
finally {
$oKPI->ComputeStatsForExtension($this, 'TriggerOnObjectDelete');
}
}
}
/**
* @return void
* @throws \ReflectionException
*/
protected function PostDeleteActions(): void
{
$this->FireEventAfterDelete();
$oKPI = new ExecutionKPI();
$this->AfterDelete();
$oKPI->ComputeStatsForExtension($this, 'AfterDelete');
}
/**
* Compute (and optionally start) the StopWatches deadlines
*
* @param string $sClass
* @param bool $bStartStopWatches
*
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \CoreUnexpectedValue
*/
private function ComputeStopWatchesDeadline(bool $bStartStopWatches)
{
$sState = $this->GetState();
if ($sState != '') {
foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sAttCode => $oAttDef) {
if ($oAttDef instanceof AttributeStopWatch) {
if (in_array($sState, $oAttDef->GetStates())) {
/** @var \ormStopWatch $oSW */
$oSW = $this->Get($sAttCode);
if ($bStartStopWatches) {
$oSW->Start($this, $oAttDef);
}
$oSW->ComputeDeadlines($this, $oAttDef);
$this->Set($sAttCode, $oSW);
}
}
}
}
}
/**
* Get the label of an attribute.
*
* Shortcut to the field's AttributeDefinition->GetLabel()
*
* @api
*
* @param string $sAttCode
*
* @return string
*
* @throws Exception
*/
public function GetLabel($sAttCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
return $oAttDef->GetLabel();
}
/**
* Getter : get a value from the current object of from a related object
*
* Get the value of the attribute $sAttCode
* This call may involve an object reload if the object was not completely loaded (lazy loading)
*
* @api
*
* @param string $sAttCode Could be an extended attribute code in the form extkey_id->anotherkey_id->remote_attr
*
* @return mixed|string
*
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \Exception
*/
public function Get($sAttCode)
{
if (($iPos = strpos($sAttCode, '->')) === false)
{
return $this->GetStrict($sAttCode);
}
else
{
$sExtKeyAttCode = substr($sAttCode, 0, $iPos);
$sRemoteAttCode = substr($sAttCode, $iPos + 2);
if (!MetaModel::IsValidAttCode(get_class($this), $sExtKeyAttCode))
{
throw new CoreException("Unknown external key '$sExtKeyAttCode' for the class ".get_class($this));
}
$oExtFieldAtt = MetaModel::FindExternalField(get_class($this), $sExtKeyAttCode, $sRemoteAttCode);
if (!is_null($oExtFieldAtt))
{
/** @var \AttributeExternalField $oExtFieldAtt */
return $this->GetStrict($oExtFieldAtt->GetCode());
}
else
{
$oKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
/** @var \AttributeExternalKey $oKeyAttDef */
$sRemoteClass = $oKeyAttDef->GetTargetClass();
$oRemoteObj = MetaModel::GetObject($sRemoteClass, $this->GetStrict($sExtKeyAttCode), false);
if (is_null($oRemoteObj))
{
return '';
}
else
{
return $oRemoteObj->Get($sRemoteAttCode);
}
}
}
}
/**
* Getter : get values from the current object
*
* @internal
* @see Get
*
* @param string $sAttCode
*
* @return int|mixed|null
* @throws ArchivedObjectException
* @throws CoreException
*/
public function GetStrict($sAttCode)
{
if ($sAttCode == 'id') {
return $this->m_iKey;
}
$oAttDef = MetaModel::GetAttributeDef(get_class($this), $sAttCode);
if (!$oAttDef->LoadInObject()) {
$value = $oAttDef->GetValue($this);
} elseif (!isset($this->m_aLoadedAtt[$sAttCode])) {
if ($this->m_bIsInDB && !$this->m_bFullyLoaded && !$this->m_bDirty) {
// Lazy load (polymorphism): complete by reloading the entire object
$oKPI = new ExecutionKPI();
$this->Reload();
$oKPI->ComputeStats('Reload', get_class($this).'/'.$sAttCode);
} elseif ($oAttDef->IsBasedOnOQLExpression()) {
// Recompute -which is likely to call Get()
//
/** @var AttributeFriendlyName|\AttributeObsolescenceFlag $oAttDef */
$this->m_aCurrValues[$sAttCode] = $this->EvaluateExpression($oAttDef->GetOQLExpression());
$this->m_aLoadedAtt[$sAttCode] = true;
} elseif ($oAttDef->IsExternalField()) {
// Let's get the object and compute all the corresponding attributes
// (i.e. not only the requested attribute)
//
/** @var \AttributeExternalField $oAttDef */
$sExtKeyAttCode = $oAttDef->GetKeyAttCode();
if (($iRemote = $this->Get($sExtKeyAttCode)) && ($iRemote > 0)) // Objects in memory have negative IDs
{
$oExtKeyAttDef = MetaModel::GetAttributeDef(get_class($this), $sExtKeyAttCode);
// Note: "allow all data" must be enabled because the external fields are always visible
// to the current user even if this is not the case for the remote object
// This is consistent with the behavior of the lists
/** @var \AttributeExternalKey $oExtKeyAttDef */
$oRemote = MetaModel::GetObject($oExtKeyAttDef->GetTargetClass(), $iRemote, true, true);
} else {
$oRemote = null;
}
foreach (MetaModel::ListAttributeDefs(get_class($this)) as $sCode => $oDef) {