synchrodatasource.class.inc.php 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Data Exchange - synchronization with external applications (incoming data)
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. class SynchroExceptionNotStarted extends CoreException
  25. {
  26. }
  27. class SynchroDataSource extends cmdbAbstractObject
  28. {
  29. public static function Init()
  30. {
  31. $aParams = array
  32. (
  33. "category" => "core/cmdb,view_in_gui",
  34. "key_type" => "autoincrement",
  35. "name_attcode" => array('name'),
  36. "state_attcode" => "",
  37. "reconc_keys" => array(),
  38. "db_table" => "priv_sync_datasource",
  39. "db_key_field" => "id",
  40. "db_finalclass_field" => "realclass",
  41. "display_template" => "",
  42. "icon" => "../images/synchro.png",
  43. );
  44. MetaModel::Init_Params($aParams);
  45. //MetaModel::Init_InheritAttributes();
  46. MetaModel::Init_AddAttribute(new AttributeString("name", array("allowed_values"=>null, "sql"=>"name", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  47. MetaModel::Init_AddAttribute(new AttributeString("description", array("allowed_values"=>null, "sql"=>"description", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  48. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('implementation,production,obsolete'), "sql"=>"status", "default_value"=>"implementation", "is_null_allowed"=>false, "depends_on"=>array())));
  49. MetaModel::Init_AddAttribute(new AttributeExternalKey("user_id", array("targetclass"=>"User", "jointype"=>null, "allowed_values"=>null, "sql"=>"user_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  50. MetaModel::Init_AddAttribute(new AttributeExternalKey("notify_contact_id", array("targetclass"=>"Contact", "jointype"=>null, "allowed_values"=>null, "sql"=>"notify_contact_id", "is_null_allowed"=>true, "on_target_delete"=>DEL_MANUAL, "depends_on"=>array())));
  51. MetaModel::Init_AddAttribute(new AttributeClass("scope_class", array("class_category"=>"bizmodel,addon/authentication", "more_values"=>"", "sql"=>"scope_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  52. MetaModel::Init_AddAttribute(new AttributeString("database_table_name", array("allowed_values"=>null, "sql"=>"database_table_name", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array(), "validation_pattern" => "^[A-Za-z0-9_]*$")));
  53. // Declared here for a future usage, but ignored so far
  54. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  55. //MetaModel::Init_AddAttribute(new AttributeDateTime("last_synchro_date", array("allowed_values"=>null, "sql"=>"last_synchro_date", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  56. // Format: seconds (int)
  57. MetaModel::Init_AddAttribute(new AttributeDuration("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  58. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  59. MetaModel::Init_AddAttribute(new AttributeEnum("reconciliation_policy", array("allowed_values"=>new ValueSetEnum('use_primary_key,use_attributes'), "sql"=>"reconciliation_policy", "default_value"=>"use_attributes", "is_null_allowed"=>false, "depends_on"=>array())));
  60. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_zero", array("allowed_values"=>new ValueSetEnum('create,error'), "sql"=>"action_on_zero", "default_value"=>"create", "is_null_allowed"=>false, "depends_on"=>array())));
  61. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_one", array("allowed_values"=>new ValueSetEnum('update,error'), "sql"=>"action_on_one", "default_value"=>"update", "is_null_allowed"=>false, "depends_on"=>array())));
  62. MetaModel::Init_AddAttribute(new AttributeEnum("action_on_multiple", array("allowed_values"=>new ValueSetEnum('take_first,create,error'), "sql"=>"action_on_multiple", "default_value"=>"error", "is_null_allowed"=>false, "depends_on"=>array())));
  63. MetaModel::Init_AddAttribute(new AttributeEnum("delete_policy", array("allowed_values"=>new ValueSetEnum('ignore,delete,update,update_then_delete'), "sql"=>"delete_policy", "default_value"=>"ignore", "is_null_allowed"=>false, "depends_on"=>array())));
  64. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_update", array("allowed_values"=>null, "sql"=>"delete_policy_update", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  65. // Format: seconds (unsigned int)
  66. MetaModel::Init_AddAttribute(new AttributeDuration("delete_policy_retention", array("allowed_values"=>null, "sql"=>"delete_policy_retention", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  67. MetaModel::Init_AddAttribute(new AttributeLinkedSet("attribute_list", array("linked_class"=>"SynchroAttribute", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array(), 'tracking_level' => LINKSET_TRACKING_DETAILS)));
  68. // Not used yet !
  69. MetaModel::Init_AddAttribute(new AttributeEnum("user_delete_policy", array("allowed_values"=>new ValueSetEnum('everybody,administrators,nobody'), "sql"=>"user_delete_policy", "default_value"=>"nobody", "is_null_allowed"=>true, "depends_on"=>array())));
  70. MetaModel::Init_AddAttribute(new AttributeURL("url_icon", array("allowed_values"=>null, "sql"=>"url_icon", "default_value"=>null, "is_null_allowed"=>true, "target"=> '_top', "depends_on"=>array())));
  71. // The field below is not a real URL since it can contain placeholders like $replica->primary_key$ which are not syntactically allowed in a real URL
  72. MetaModel::Init_AddAttribute(new AttributeString("url_application", array("allowed_values"=>null, "sql"=>"url_application", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  73. // Display lists
  74. MetaModel::Init_SetZListItems('details', array(
  75. 'col:0'=> array(
  76. 'fieldset:SynchroDataSource:Description' => array('name','description','status','scope_class','user_id','notify_contact_id','url_icon','url_application', 'database_table_name')),
  77. 'col:1'=> array(
  78. 'fieldset:SynchroDataSource:Reconciliation' => array('reconciliation_policy','action_on_zero','action_on_one','action_on_multiple'),
  79. 'fieldset:SynchroDataSource:Deletion' => array('user_delete_policy','full_load_periodicity','delete_policy','delete_policy_update','delete_policy_retention'))
  80. )
  81. );
  82. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  83. // Search criteria
  84. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  85. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  86. }
  87. public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  88. {
  89. if (!$this->IsNew())
  90. {
  91. $this->Set('database_table_name', $this->GetDataTable());
  92. }
  93. return parent::DisplayBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  94. }
  95. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  96. {
  97. if (!$this->IsNew())
  98. {
  99. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  100. $oAttributeSet = $this->Get('attribute_list');
  101. $aAttributes = array();
  102. while($oAttribute = $oAttributeSet->Fetch())
  103. {
  104. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  105. }
  106. // Columns of the form
  107. $aAttribs = array();
  108. foreach(array('attcode', 'reconciliation', 'update', 'update_policy', 'reconciliation_attcode') as $s )
  109. {
  110. $aAttribs[$s] = array( 'label' => Dict::S("Core:SynchroAtt:$s"), "description" => Dict::S("Core:SynchroAtt:$s+"));
  111. }
  112. // Rows of the form
  113. $aValues = array();
  114. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  115. {
  116. if ($oAttDef->IsWritable())
  117. {
  118. if (isset($aAttributes[$sAttCode]))
  119. {
  120. $oAttribute = $aAttributes[$sAttCode];
  121. }
  122. else
  123. {
  124. if ($oAttDef->IsExternalKey())
  125. {
  126. $oAttribute = new SynchroAttExtKey();
  127. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  128. }
  129. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  130. {
  131. $oAttribute = new SynchroAttLinkSet();
  132. // Todo - add these settings into the form
  133. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  134. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  135. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  136. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  137. }
  138. elseif ($oAttDef->IsScalar())
  139. {
  140. $oAttribute = new SynchroAttribute();
  141. }
  142. else
  143. {
  144. $oAttribute = null;
  145. }
  146. if (!is_null($oAttribute))
  147. {
  148. $oAttribute->Set('sync_source_id', $this->GetKey());
  149. $oAttribute->Set('attcode', $sAttCode);
  150. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  151. $oAttribute->Set('update', 1);
  152. $oAttribute->Set('update_policy', 'master_locked');
  153. }
  154. }
  155. if (!is_null($oAttribute))
  156. {
  157. if (!$bEditMode)
  158. {
  159. // Read-only mode
  160. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  161. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  162. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  163. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  164. if ($oAttDef->IsExternalKey())
  165. {
  166. $aRow['reconciliation_attcode'] = $oAttribute->GetAsHTML('reconciliation_attcode');
  167. }
  168. else
  169. {
  170. $aRow['reconciliation_attcode'] = '&nbsp;';
  171. }
  172. }
  173. else
  174. {
  175. // Edit mode
  176. $sAttCode = $oAttribute->Get('attcode');
  177. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  178. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  179. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  180. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  181. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  182. $oUpdateAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  183. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oUpdateAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  184. if ($oAttDef->IsExternalKey())
  185. {
  186. $aRow['reconciliation_attcode'] = $oAttribute->GetReconciliationFormElement($oAttDef->GetTargetClass(), "attr_reconciliation_attcode[$sAttCode]");
  187. }
  188. else
  189. {
  190. $aRow['reconciliation_attcode'] = '&nbsp;';
  191. }
  192. }
  193. $aValues[] = $aRow;
  194. }
  195. }
  196. }
  197. $oPage->p(Dict::Format('Class:SynchroDataSource:DataTable', $this->GetDataTable()));
  198. $oPage->Table($aAttribs, $aValues);
  199. $this->DisplayStatusTab($oPage);
  200. }
  201. parent::DisplayBareRelations($oPage, $bEditMode);
  202. }
  203. /**
  204. * Displays the status (SynchroLog) of the datasource in a graphical manner
  205. * @param $oPage WebPage
  206. * @return void
  207. */
  208. protected function DisplayStatusTab(WebPage $oPage)
  209. {
  210. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  211. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  212. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  213. $oSetSynchroLog->SetLimit(100); // Display only the 100 latest runs
  214. if ($oSetSynchroLog->Count() > 0)
  215. {
  216. $oLastLog = $oSetSynchroLog->Fetch();
  217. $sStartDate = $oLastLog->Get('start_date');
  218. $oLastLog->Get('stats_nb_replica_seen');
  219. $iLastLog = 0;
  220. $iDSid = $this->GetKey();
  221. if ($oLastLog->Get('status') == 'running')
  222. {
  223. // Still running !
  224. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  225. }
  226. else
  227. {
  228. $sEndDate = $oLastLog->Get('end_date');
  229. $iLastLog = $oLastLog->GetKey();
  230. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  231. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid";
  232. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  233. $iCountAllReplicas = $oSet->Count();
  234. $sAllReplicas = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllReplicas</a>";
  235. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_error !=''";
  236. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  237. $iCountAllErrors = $oSet->Count();
  238. $sAllErrors = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllErrors</a>";
  239. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_warning !=''";
  240. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  241. $iCountAllWarnings = $oSet->Count();
  242. $sAllWarnings = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllWarnings</a>";
  243. $oPage->p('<h2>'.Dict::Format('Core:Synchro:ListReplicas_AllReplicas_Errors_Warnings', $sAllReplicas, $sAllErrors, $sAllWarnings).'</h2>');
  244. }
  245. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  246. // List all the log entries for the user to select
  247. $oPage->add('<h2 style="line-height:55px;">'.Dict::S('Core:Synchro:History').'</h2>');
  248. $oSetSynchroLog->Rewind();
  249. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  250. $sSelected = ' selected'; // First log is selected by default
  251. $sScript = "var aSynchroLog = {\n";
  252. while($oLog = $oSetSynchroLog->Fetch())
  253. {
  254. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  255. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  256. $sSelected = ''; // only the first log is selected by default
  257. $aData = $this->ProcessLog($oLog);
  258. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  259. }
  260. $sScript .= "end: 'Done'";
  261. $sScript .= "};\n";
  262. $sScript .= <<<EOF
  263. var sLastLog = '$iLastLog';
  264. function ToggleSynoptics(sId, bShow)
  265. {
  266. if (bShow)
  267. {
  268. $(sId).show();
  269. }
  270. else
  271. {
  272. $(sId).hide();
  273. }
  274. }
  275. function UpdateSynoptics(id)
  276. {
  277. var aValues = aSynchroLog[id];
  278. if (aValues == undefined) return;
  279. for (var sKey in aValues)
  280. {
  281. $('#c_'+sKey).html(aValues[sKey]);
  282. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  283. $('#'+sKey).fadeTo("slow", fOpacity);
  284. }
  285. //alert('id = '+id+', lastLog='+sLastLog+', id==sLastLog: '+(id==sLastLog)+' obj_updated_errors: '+aValues['obj_updated_errors']);
  286. if ( (id == sLastLog) && (aValues['obj_new_errors'] > 0) )
  287. {
  288. $('#new_errors_link').show();
  289. }
  290. else
  291. {
  292. $('#new_errors_link').hide();
  293. }
  294. if ( (id == sLastLog) && (aValues['obj_updated_errors'] > 0) )
  295. {
  296. $('#updated_errors_link').show();
  297. }
  298. else
  299. {
  300. $('#updated_errors_link').hide();
  301. }
  302. if ( (id == sLastLog) && (aValues['obj_disappeared_errors'] > 0) )
  303. {
  304. $('#disappeared_errors_link').show();
  305. }
  306. else
  307. {
  308. $('#disappeared_errors_link').hide();
  309. }
  310. ToggleSynoptics('#cw_obj_created_warnings', aValues['obj_created_warnings'] > 0);
  311. ToggleSynoptics('#cw_obj_new_updated_warnings', aValues['obj_new_updated_warnings'] > 0);
  312. ToggleSynoptics('#cw_obj_new_unchanged_warnings', aValues['obj_new_unchanged_warnings'] > 0);
  313. ToggleSynoptics('#cw_obj_updated_warnings', aValues['obj_updated_warnings'] > 0);
  314. ToggleSynoptics('#cw_obj_unchanged_warnings', aValues['obj_unchanged_warnings'] > 0);
  315. }
  316. EOF
  317. ;
  318. $oPage->add_script($sScript);
  319. $oPage->add('</select>');
  320. $oPage->add('</td><td style="vertical-align:top;">');
  321. // Now build the big "synoptics" view
  322. $aData = $this->ProcessLog($oLastLog);
  323. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  324. $sNbObjects = MetaModel::GetClassIcon($this->GetTargetClass())."&nbsp;".Dict::Format('Core:Synchro:Nb_Class:Objects', $this->GetTargetClass(), "<span id=\"c_nb_obj_total\">{$aData['nb_obj_total']}</span>");
  325. $oPage->add(
  326. <<<EOF
  327. <table class="synoptics">
  328. <tr class="synoptics_header">
  329. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  330. </tr>
  331. <tr>
  332. EOF
  333. );
  334. $sBaseOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  335. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  336. $oPage->add("</tr>\n<tr>");
  337. $oPage->add($this->HtmlBox('repl_disappeared', $aData, '#630', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_disappeared_no_action', $aData, '#333'));
  338. $oPage->add("</tr>\n<tr>");
  339. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  340. $oPage->add("</tr>\n<tr>");
  341. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  342. $oPage->add("</tr>\n<tr>");
  343. $sOQL = urlencode($sBaseOQL." AND status='obsolete'");
  344. $oPage->add($this->HtmlBox('obj_disappeared_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"disappeared_errors_link\">Show</a>"));
  345. $oPage->add("</tr>\n<tr>");
  346. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  347. $oPage->add("</tr>\n<tr>");
  348. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  349. $oPage->add("</tr>\n<tr>");
  350. $sOQL = urlencode($sBaseOQL." AND status='modified'");
  351. $oPage->add($this->HtmlBox('obj_updated_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"updated_errors_link\">Show</a>"));
  352. $oPage->add("</tr>\n<tr>");
  353. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  354. $oPage->add("</tr>\n<tr>");
  355. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  356. $oPage->add("</tr>\n<tr>");
  357. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  358. $oPage->add("</tr>\n<tr>");
  359. $sOQL = urlencode($sBaseOQL." AND status='new'");
  360. $oPage->add($this->HtmlBox('obj_new_errors', $aData, '#C00', '', " <a style=\"color:#fff\" href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\" id=\"new_errors_link\">Show</a>"));
  361. $oPage->add("</tr>\n</table>\n");
  362. $oPage->add('</td></tr></table>');
  363. $oPage->add_ready_script("UpdateSynoptics('$iLastLog')");
  364. }
  365. else
  366. {
  367. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  368. }
  369. }
  370. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '', $sErrorLink = '')
  371. {
  372. $iCount = $aData[$sId];
  373. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  374. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  375. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  376. if (isset($aData[$sId.'_warnings']))
  377. {
  378. $sLabel .= " <span id=\"cw_{$sId}_warnings\"><img src=\"../images/error.png\" style=\"vertical-align:middle\"/> (<span id=\"c_{$sId}_warnings\">".$aData[$sId.'_warnings']."</span>)</span>";
  379. }
  380. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>{$sLabel}{$sErrorLink}</td>";
  381. }
  382. protected function ProcessLog($oLastLog)
  383. {
  384. $aData = array(
  385. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  386. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  387. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  388. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  389. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  390. 'obj_updated_warnings' => $oLastLog->Get('stats_nb_obj_updated_warnings'),
  391. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  392. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  393. 'obj_new_updated_warnings' => $oLastLog->Get('stats_nb_obj_new_updated_warnings'),
  394. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  395. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  396. 'obj_created_warnings' => $oLastLog->Get('stats_nb_obj_created_warnings'),
  397. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  398. 'obj_unchanged_warnings' => $oLastLog->Get('stats_nb_obj_unchanged_warnings'),
  399. );
  400. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  401. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  402. $aData['repl_disappeared'] = $iDisappeared;
  403. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  404. $aData['obj_new_errors'] = $iNewErrors;
  405. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  406. $aData['repl_new'] = $iNew;
  407. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  408. $aData['repl_existing'] = $iExisting;
  409. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  410. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  411. $aData['repl_ignored'] = $iIgnored;
  412. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  413. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  414. return $aData;
  415. }
  416. public function GetIcon($bImgTag = true, $sMoreStyles = '')
  417. {
  418. if ($this->Get('url_icon') == '') return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  419. if ($bImgTag)
  420. {
  421. return "<img src=\"".$this->Get('url_icon')."\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  422. }
  423. return $this->Get('url_icon');
  424. }
  425. /**
  426. * Get the actual hyperlink to the remote application for the given replica and dest object
  427. */
  428. public function GetApplicationUrl(DBObject $oDestObj, SynchroReplica $oReplica)
  429. {
  430. if ($this->Get('url_application') == '') return '';
  431. $aSearches = array();
  432. $aReplacements = array();
  433. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  434. {
  435. if ($oAttDef->IsScalar())
  436. {
  437. $aSearches[] = '$this->'.$sAttCode.'$';
  438. $aReplacements[] = $oDestObj->Get($sAttCode);
  439. }
  440. }
  441. $aData = $oReplica->LoadExtendedDataFromTable($this->GetDataTable());
  442. foreach($aData as $sColumn => $value)
  443. {
  444. $aSearches[] = '$replica->'.$sColumn.'$';
  445. $aReplacements[] = $value;
  446. }
  447. return str_replace($aSearches, $aReplacements, $this->Get('url_application'));
  448. }
  449. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  450. {
  451. if ( (($sAttCode == 'scope_class') || ($sAttCode == 'database_table_name')) && (!$this->IsNew()))
  452. {
  453. return OPT_ATT_READONLY;
  454. }
  455. return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
  456. }
  457. public function UpdateObjectFromPostedForm($sFormPrefix = '', $sAttList = null, $sTargetState = '')
  458. {
  459. parent::UpdateObjectFromPostedForm($sFormPrefix, $sAttList, $sTargetState);
  460. // And now read the other post parameters...
  461. $oAttributeSet = $this->Get('attribute_list');
  462. $aAttributes = array();
  463. while($oAttribute = $oAttributeSet->Fetch())
  464. {
  465. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  466. }
  467. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  468. $aUpdate = utils::ReadPostedParam('update', array());
  469. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  470. $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array());
  471. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  472. // through all the writable attributes
  473. foreach($aUpdatePolicy as $sAttCode => $sValue)
  474. {
  475. if(!isset($aAttributes[$sAttCode]))
  476. {
  477. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  478. }
  479. else
  480. {
  481. $oAttribute = $aAttributes[$sAttCode];
  482. }
  483. $bReconcile = 0;
  484. if (isset($aReconcile[$sAttCode]))
  485. {
  486. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  487. }
  488. $bUpdate = 0 ; // Default / initial value
  489. if (isset($aUpdate[$sAttCode]))
  490. {
  491. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  492. }
  493. $oAttribute->Set('reconcile', $bReconcile);
  494. $oAttribute->Set('update', $bUpdate);
  495. $oAttribute->Set('update_policy', $sValue);
  496. if ($oAttribute instanceof SynchroAttExtKey)
  497. {
  498. $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]);
  499. }
  500. elseif ($oAttribute instanceof SynchroAttLinkSet)
  501. {
  502. }
  503. $oAttributeSet->AddObject($oAttribute);
  504. }
  505. $this->Set('attribute_list', $oAttributeSet);
  506. }
  507. /**
  508. * Creates a new SynchroAttXXX object in memory with the default values
  509. */
  510. protected function CreateSynchroAtt($sAttCode)
  511. {
  512. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  513. if ($oAttDef->IsExternalKey())
  514. {
  515. $oAttribute = new SynchroAttExtKey();
  516. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  517. }
  518. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  519. {
  520. $oAttribute = new SynchroAttLinkSet();
  521. // Todo - set those value from the form
  522. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  523. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  524. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  525. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  526. }
  527. else
  528. {
  529. $oAttribute = new SynchroAttribute();
  530. }
  531. $oAttribute->Set('sync_source_id', $this->GetKey());
  532. $oAttribute->Set('attcode', $sAttCode);
  533. $oAttribute->Set('reconcile', 0);
  534. $oAttribute->Set('update', 0);
  535. $oAttribute->Set('update_policy', 'master_locked');
  536. return $oAttribute;
  537. }
  538. /**
  539. * Overload the standard behavior
  540. */
  541. public function ComputeValues()
  542. {
  543. parent::ComputeValues();
  544. if ($this->IsNew())
  545. {
  546. // Compute the database_table_name
  547. $sDataTable = $this->Get('database_table_name');
  548. if (!empty($sDataTable))
  549. {
  550. $this->Set('database_table_name', $this->ComputeDataTableName());
  551. }
  552. // When inserting a new datasource object, also create the SynchroAttribute objects
  553. // for each field of the target class
  554. // Create all the SynchroAttribute records
  555. $oAttributeSet = $this->Get('attribute_list');
  556. if ($oAttributeSet->Count() == 0)
  557. {
  558. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  559. {
  560. if ($oAttDef->IsWritable())
  561. {
  562. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  563. if ($oAttDef->IsExternalKey())
  564. {
  565. $oAttribute = new SynchroAttExtKey();
  566. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  567. }
  568. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  569. {
  570. $oAttribute = new SynchroAttLinkSet();
  571. // Todo - set those value from the form
  572. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  573. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  574. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  575. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  576. }
  577. elseif ($oAttDef->IsScalar())
  578. {
  579. $oAttribute = new SynchroAttribute();
  580. }
  581. else
  582. {
  583. $oAttribute = null;
  584. }
  585. if (!is_null($oAttribute))
  586. {
  587. $oAttribute->Set('sync_source_id', $this->GetKey());
  588. $oAttribute->Set('attcode', $sAttCode);
  589. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  590. $oAttribute->Set('update', 1);
  591. $oAttribute->Set('update_policy', 'master_locked');
  592. $oAttributeSet->AddObject($oAttribute);
  593. }
  594. }
  595. }
  596. $this->Set('attribute_list', $oAttributeSet);
  597. }
  598. }
  599. else
  600. {
  601. $sDataTable = $this->Get('database_table_name');
  602. if (empty($sDataTable))
  603. {
  604. $this->Set('database_table_name', $this->ComputeDataTableName());
  605. }
  606. }
  607. }
  608. public function DoCheckToWrite()
  609. {
  610. parent::DoCheckToWrite();
  611. // Check that there is at least one reconciliation key defined
  612. if ($this->Get('reconciliation_policy') == 'use_attributes')
  613. {
  614. $oSet = $this->Get('attribute_list');
  615. $oSynchroAttributeList = $oSet->ToArray();
  616. $bReconciliationKey = false;
  617. foreach($oSynchroAttributeList as $oSynchroAttribute)
  618. {
  619. if ($oSynchroAttribute->Get('reconcile') == 1)
  620. {
  621. $bReconciliationKey = true; // At least one key is defined
  622. break;
  623. }
  624. }
  625. if (!$bReconciliationKey)
  626. {
  627. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  628. }
  629. }
  630. // If 'update_then_delete' is specified there must be a delete_retention_period
  631. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  632. {
  633. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  634. }
  635. // If update is specified, then something to update must be defined
  636. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  637. && ($this->Get('delete_policy_update') == ''))
  638. {
  639. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  640. }
  641. // When creating the data source with a specified database_table_name, this table must NOT exist
  642. if ($this->IsNew())
  643. {
  644. $sDataTable = $this->GetDataTable();
  645. if (!empty($sDataTable) && CMDBSource::IsTable($this->GetDataTable()))
  646. {
  647. // Hmm, the synchro_data_xxx table already exists !!
  648. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DataTableAlreadyExists', $this->GetDataTable());
  649. }
  650. }
  651. }
  652. public function GetTargetClass()
  653. {
  654. return $this->Get('scope_class');
  655. }
  656. public function GetDataTable()
  657. {
  658. $sTable = $this->Get('database_table_name');
  659. if (empty($sTable))
  660. {
  661. $sTable = $this->ComputeDataTableName();
  662. }
  663. return $sTable;
  664. }
  665. protected function ComputeDataTableName()
  666. {
  667. $sDBTableName = $this->Get('database_table_name');
  668. if (empty($sDBTableName))
  669. {
  670. $sDBTableName = strtolower($this->GetTargetClass());
  671. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  672. $sDBTableName .= '_'.$this->GetKey(); // Add a suffix for unicity
  673. }
  674. else
  675. {
  676. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  677. }
  678. $sPrefix = MetaModel::GetConfig()->GetDBSubName()."synchro_data_";
  679. if (strpos($sDBTableName, $sPrefix) !== 0)
  680. {
  681. $sDBTableName = $sPrefix.$sDBTableName;
  682. }
  683. return $sDBTableName;
  684. }
  685. /**
  686. * When the new datasource has been created, let's create the synchro_data table
  687. * that will hold the data records and the correspoding triggers which will maintain
  688. * both tables in sync
  689. */
  690. protected function AfterInsert()
  691. {
  692. parent::AfterInsert();
  693. $sTable = $this->GetDataTable();
  694. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  695. $aColumns = $this->GetSQLColumns();
  696. $aFieldDefs = array();
  697. // Allow '0', otherwise mysql will render an error when the id is not given
  698. // (the trigger is expected to set the value, but it is not executed soon enough)
  699. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  700. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  701. foreach($aColumns as $sColumn => $ColSpec)
  702. {
  703. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  704. }
  705. $aFieldDefs[] = "INDEX (id)";
  706. $aFieldDefs[] = "INDEX (primary_key)";
  707. $sFieldDefs = implode(', ', $aFieldDefs);
  708. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
  709. CMDBSource::Query($sCreateTable);
  710. $aTriggers = $this->GetTriggersDefinition();
  711. foreach($aTriggers as $key => $sTriggerSQL)
  712. {
  713. CMDBSource::Query($sTriggerSQL);
  714. }
  715. $sDataTable = $this->Get('database_table_name');
  716. if (empty($sDataTable))
  717. {
  718. $this->Set('database_table_name', $this->ComputeDataTableName());
  719. $this->DBUpdate();
  720. }
  721. }
  722. /**
  723. * Gets the definitions of the 3 triggers: before insert, before update and after delete
  724. * @return array An array with 3 entries, one for each of the SQL queries
  725. */
  726. protected function GetTriggersDefinition()
  727. {
  728. $sTable = $this->GetDataTable();
  729. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  730. $aColumns = $this->GetSQLColumns();
  731. $aResult = array();
  732. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON `$sTable`";
  733. $sTriggerInsert .= " FOR EACH ROW";
  734. $sTriggerInsert .= " BEGIN";
  735. $sTriggerInsert .= " INSERT INTO `{$sReplicaTable}` (`sync_source_id`, `status_last_seen`, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  736. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  737. $sTriggerInsert .= " END;";
  738. $aResult['bi'] = $sTriggerInsert;
  739. $aModified = array();
  740. foreach($aColumns as $sColumn => $ColSpec)
  741. {
  742. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  743. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  744. }
  745. $sIsModified = '('.implode(') OR (', $aModified).')';
  746. // Update the replica
  747. //
  748. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  749. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  750. // otherwise, the status is left as is
  751. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON `$sTable`";
  752. $sTriggerUpdate .= " FOR EACH ROW";
  753. $sTriggerUpdate .= " BEGIN";
  754. $sTriggerUpdate .= " IF @itopuser is null THEN";
  755. $sTriggerUpdate .= " UPDATE `{$sReplicaTable}` SET status_last_seen = NOW(), `status` = IF(`status` = 'obsolete', IF(`dest_id` IS NULL, 'new', 'modified'), IF(`status` IN ('synchronized') AND ($sIsModified), 'modified', `status`)) WHERE sync_source_id = {$this->GetKey()} AND id = OLD.id;";
  756. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  757. $sTriggerUpdate .= " END IF;";
  758. $sTriggerUpdate .= " END;";
  759. $aResult['bu'] = $sTriggerUpdate;
  760. $sTriggerDelete = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON `$sTable`";
  761. $sTriggerDelete .= " FOR EACH ROW";
  762. $sTriggerDelete .= " BEGIN";
  763. $sTriggerDelete .= " DELETE FROM `{$sReplicaTable}` WHERE id = OLD.id;";
  764. $sTriggerDelete .= " END;";
  765. $aResult['ad'] = $sTriggerDelete;
  766. return $aResult;
  767. }
  768. protected function AfterDelete()
  769. {
  770. parent::AfterDelete();
  771. $sTable = $this->GetDataTable();
  772. $sDropTable = "DROP TABLE `$sTable`";
  773. CMDBSource::Query($sDropTable);
  774. // TO DO - check that triggers get dropped with the table
  775. }
  776. /**
  777. * Checks if the data source definition is consistent with the schema of the target class
  778. * @param $bDiagnostics boolean True to only diagnose the consistency, false to actually apply some changes
  779. * @param $bVerbose boolean True to get some information in the std output (echo)
  780. * @return bool Whether or not the database needs fixing for this data source
  781. */
  782. public function CheckDBConsistency($bDiagnostics, $bVerbose, $oChange = null)
  783. {
  784. $bFixNeeded = false;
  785. $bTriggerRebuildNeeded = false;
  786. $aMissingFields = array();
  787. $oAttributeSet = $this->Get('attribute_list');
  788. $aAttributes = array();
  789. while($oAttribute = $oAttributeSet->Fetch())
  790. {
  791. $sAttCode = $oAttribute->Get('attcode');
  792. if (MetaModel::IsValidAttCode($this->GetTargetClass(), $sAttCode))
  793. {
  794. $aAttributes[$sAttCode] = $oAttribute;
  795. }
  796. else
  797. {
  798. // Old field remaining
  799. $bTriggerRebuildNeeded = true;
  800. if ($bVerbose)
  801. {
  802. echo "Irrelevant field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be removed.\n";
  803. }
  804. $bFixNeeded = true;
  805. if (!$bDiagnostics)
  806. {
  807. // Fix the issue
  808. $oAttribute->DBDelete();
  809. }
  810. }
  811. }
  812. $sTable = $this->GetDataTable();
  813. foreach($this->ListTargetAttributes() as $sAttCode=>$oAttDef)
  814. {
  815. if (!isset($aAttributes[$sAttCode]))
  816. {
  817. $bFixNeeded = true;
  818. $aMissingFields[] = $sAttCode;
  819. $bTriggerRebuildNeeded = true;
  820. // New field missing...
  821. if ($bVerbose)
  822. {
  823. echo "Missing field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be created with default values.\n";
  824. }
  825. if (!$bDiagnostics)
  826. {
  827. // Fix the issue
  828. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  829. $oAttribute->DBInsert();
  830. }
  831. }
  832. else
  833. {
  834. $aColumns = $this->GetSQLColumns(array($sAttCode));
  835. foreach($aColumns as $sColName => $sColumnDef)
  836. {
  837. $bOneColIsMissing = false;
  838. if (!CMDBSource::IsField($sTable, $sColName))
  839. {
  840. $bFixNeeded = true;
  841. $bOneColIsMissing = true;
  842. if ($bVerbose)
  843. {
  844. if (count($aColumns) > 1)
  845. {
  846. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  847. }
  848. else
  849. {
  850. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  851. }
  852. }
  853. }
  854. else if (strcasecmp(CMDBSource::GetFieldType($sTable, $sColName), $sColumnDef) != 0)
  855. {
  856. $bFixNeeded = true;
  857. $bOneColIsMissing = true;
  858. if (count($aColumns) > 1)
  859. {
  860. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  861. }
  862. else
  863. {
  864. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  865. }
  866. }
  867. if ($bOneColIsMissing)
  868. {
  869. $bTriggerRebuildNeeded = true;
  870. $aMissingFields[] = $sAttCode;
  871. }
  872. }
  873. }
  874. }
  875. $sDBName = MetaModel::GetConfig()->GetDBName();
  876. try
  877. {
  878. // Note: as per the MySQL documentation, using information_schema behaves exactly like SHOW TRIGGERS (user privileges)
  879. // and this is in fact the recommended way for better portability
  880. $iTriggerCount = CMDBSource::QueryToScalar("select count(*) from information_schema.triggers where EVENT_OBJECT_SCHEMA='$sDBName' and EVENT_OBJECT_TABLE='$sTable'");
  881. }
  882. catch (Exception $e)
  883. {
  884. if ($bVerbose)
  885. {
  886. echo "Failed to investigate on the synchro triggers (skipping the check): ".$e->getMessage().".\n";
  887. }
  888. // Ignore this error: consider that the trigger are there
  889. $iTriggerCount = 3;
  890. }
  891. if ($iTriggerCount < 3)
  892. {
  893. $bFixNeeded = true;
  894. $bTriggerRebuildNeeded = true;
  895. if ($bVerbose)
  896. {
  897. echo "Missing trigger(s) for the data synchro task ".$this->GetName()." (table {$sTable}).\n";
  898. }
  899. }
  900. $aRepairQueries = array();
  901. if (count($aMissingFields) > 0)
  902. {
  903. // The structure of the table needs adjusting
  904. $aColumns = $this->GetSQLColumns($aMissingFields);
  905. $aFieldDefs = array();
  906. foreach($aColumns as $sAttCode => $sColumnDef)
  907. {
  908. if (CMDBSource::IsField($sTable, $sAttCode))
  909. {
  910. $aRepairQueries[] = "ALTER TABLE `$sTable` CHANGE `$sAttCode` `$sAttCode` $sColumnDef";
  911. }
  912. else
  913. {
  914. $aFieldDefs[] = "`$sAttCode` $sColumnDef";
  915. }
  916. }
  917. if (count($aFieldDefs) > 0)
  918. {
  919. $aRepairQueries[] = "ALTER TABLE `$sTable` ADD (".implode(',', $aFieldDefs).");";
  920. }
  921. if ($bDiagnostics)
  922. {
  923. if ($bVerbose)
  924. {
  925. echo "The structure of the table $sTable for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be altered (missing or incorrect fields: ".implode(',', $aMissingFields).").\n";
  926. }
  927. }
  928. }
  929. // Repair the triggers
  930. // Must be done after updating the columns because MySQL does check the validity of the query found into the procedure!
  931. if ($bTriggerRebuildNeeded)
  932. {
  933. // The triggers as well must be adjusted
  934. $aTriggersDefs = $this->GetTriggersDefinition();
  935. $aTriggerRepair = array();
  936. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bi`;";
  937. $aTriggerRepair[] = $aTriggersDefs['bi'];
  938. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bu`;";
  939. $aTriggerRepair[] = $aTriggersDefs['bu'];
  940. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_ad`;";
  941. $aTriggerRepair[] = $aTriggersDefs['ad'];
  942. if ($bDiagnostics)
  943. {
  944. if ($bVerbose)
  945. {
  946. echo "The triggers {$sTable}_bi, {$sTable}_bu, {$sTable}_ad for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be re-created.\n";
  947. echo implode("\n", $aTriggerRepair)."\n";
  948. }
  949. }
  950. $aRepairQueries = array_merge($aRepairQueries, $aTriggerRepair); // The order matters!
  951. }
  952. // Execute the repair statements
  953. //
  954. if (!$bDiagnostics && (count($aRepairQueries) > 0))
  955. {
  956. // Fix the issue
  957. foreach($aRepairQueries as $sSQL)
  958. {
  959. CMDBSource::Query($sSQL);
  960. if ($bVerbose)
  961. {
  962. echo "$sSQL\n";
  963. }
  964. }
  965. }
  966. return $bFixNeeded;
  967. }
  968. public function SendNotification($sSubject, $sBody)
  969. {
  970. $iContact = $this->Get('notify_contact_id');
  971. if ($iContact == 0)
  972. {
  973. // Leave silently...
  974. return;
  975. }
  976. $oContact = MetaModel::GetObject('Contact', $iContact);
  977. // Determine the email attribute (the first one will be our choice)
  978. $sEmailAttCode = null;
  979. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  980. {
  981. if ($oAttDef instanceof AttributeEmailAddress)
  982. {
  983. $sEmailAttCode = $sAttCode;
  984. // we've got one, exit the loop
  985. break;
  986. }
  987. }
  988. if (is_null($sEmailAttCode))
  989. {
  990. // Leave silently...
  991. return;
  992. }
  993. $sTo = $oContact->Get($sEmailAttCode);
  994. $sFrom = $sTo;
  995. $sBody = '<p>Data synchronization: '.$this->GetHyperlink().'</p>'.$sBody;
  996. $sSubject = 'iTop Data Sync - '.$this->GetName().' - '.$sSubject;
  997. $oEmail = new Email();
  998. $oEmail->SetRecipientTO($sTo);
  999. $oEmail->SetRecipientFrom($sFrom);
  1000. $oEmail->SetSubject($sSubject);
  1001. $oEmail->SetBody($sBody);
  1002. if ($oEmail->Send($aIssues) == EMAIL_SEND_ERROR)
  1003. {
  1004. // mmmm, what can I do?
  1005. }
  1006. }
  1007. /**
  1008. * Get the list of attributes eligible to the synchronization
  1009. */
  1010. public function ListTargetAttributes()
  1011. {
  1012. $aRet = array();
  1013. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode => $oAttDef)
  1014. {
  1015. if ($sAttCode == 'finalclass') continue;
  1016. if (!$oAttDef->IsWritable()) continue;
  1017. if ($oAttDef->IsLinkSet() && !$oAttDef->IsIndirect()) continue;
  1018. $aRet[$sAttCode] = $oAttDef;
  1019. }
  1020. return $aRet;
  1021. }
  1022. /**
  1023. * Get the list of SQL columns corresponding to a particular list of attribute codes
  1024. * Defaults to the whole list of columns for the current class
  1025. */
  1026. public function GetSQLColumns($aAttributeCodes = null)
  1027. {
  1028. $aColumns = array();
  1029. $sClass = $this->GetTargetClass();
  1030. if (is_null($aAttributeCodes))
  1031. {
  1032. $aAttributeCodes = array();
  1033. foreach($this->ListTargetAttributes() as $sAttCode => $oAttDef)
  1034. {
  1035. $aAttributeCodes[] = $sAttCode;
  1036. }
  1037. }
  1038. foreach($aAttributeCodes as $sAttCode)
  1039. {
  1040. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1041. if ($oAttDef->IsExternalKey())
  1042. {
  1043. // The pkey might be used as well as any other key column
  1044. $aColumns[$sAttCode] = 'VARCHAR(255)';
  1045. }
  1046. else
  1047. {
  1048. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  1049. {
  1050. $aColumns[$sField] = $sDBFieldType;
  1051. }
  1052. }
  1053. }
  1054. return $aColumns;
  1055. }
  1056. /**
  1057. * Get the list of Date and Datetime SQL columns
  1058. */
  1059. public function GetDateSQLColumns()
  1060. {
  1061. $aDateAttributes = array();
  1062. $sClass = $this->GetTargetClass();
  1063. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1064. {
  1065. if ($oAttDef instanceof AttributeDateTime)
  1066. {
  1067. $aDateAttributes[] = $sAttCode;
  1068. }
  1069. }
  1070. return $this->GetSQLColumns($aDateAttributes);
  1071. }
  1072. public function IsRunning()
  1073. {
  1074. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  1075. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1076. if ($oSet->Count() < 1)
  1077. {
  1078. $bRet = false;
  1079. }
  1080. else
  1081. {
  1082. $bRet = true;
  1083. }
  1084. return $bRet;
  1085. }
  1086. public function GetLatestLog()
  1087. {
  1088. $oLog = null;
  1089. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  1090. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1091. if ($oSet->Count() >= 1)
  1092. {
  1093. $oLog = $oSet->Fetch();
  1094. }
  1095. return $oLog;
  1096. }
  1097. // TO DO: remove if still unused
  1098. /**
  1099. * Retrieve from the log, the date of the last completed import
  1100. * @return DateTime
  1101. */
  1102. public function GetLastCompletedImportDate()
  1103. {
  1104. $date = null;
  1105. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  1106. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  1107. if ($oSet->Count() >= 1)
  1108. {
  1109. $oLog = $oSet->Fetch();
  1110. $date = $oLog->Get('end_date');
  1111. }
  1112. return $date;
  1113. }
  1114. }
  1115. class SynchroAttribute extends cmdbAbstractObject
  1116. {
  1117. public static function Init()
  1118. {
  1119. $aParams = array
  1120. (
  1121. "category" => "core/cmdb,view_in_gui",
  1122. "key_type" => "autoincrement",
  1123. "name_attcode" => "attcode",
  1124. "state_attcode" => "",
  1125. "reconc_keys" => array(),
  1126. "db_table" => "priv_sync_att",
  1127. "db_key_field" => "id",
  1128. "db_finalclass_field" => "",
  1129. "display_template" => "",
  1130. );
  1131. MetaModel::Init_Params($aParams);
  1132. MetaModel::Init_InheritAttributes();
  1133. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  1134. MetaModel::Init_AddAttribute(new AttributeExternalField("sync_source_name", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"name")));
  1135. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  1136. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  1137. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  1138. MetaModel::Init_AddAttribute(new AttributeEnum("update_policy", array("allowed_values"=>new ValueSetEnum('master_locked,master_unlocked,write_if_empty'), "sql"=>"update_policy", "default_value"=>"master_locked", "is_null_allowed"=>false, "depends_on"=>array())));
  1139. // Display lists
  1140. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  1141. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1142. // Search criteria
  1143. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1144. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1145. }
  1146. }
  1147. class SynchroAttExtKey extends SynchroAttribute
  1148. {
  1149. public static function Init()
  1150. {
  1151. $aParams = array
  1152. (
  1153. "category" => "core/cmdb,view_in_gui",
  1154. "key_type" => "autoincrement",
  1155. "name_attcode" => "attcode",
  1156. "state_attcode" => "",
  1157. "reconc_keys" => array(),
  1158. "db_table" => "priv_sync_att_extkey",
  1159. "db_key_field" => "id",
  1160. "db_finalclass_field" => "",
  1161. "display_template" => "",
  1162. );
  1163. MetaModel::Init_Params($aParams);
  1164. MetaModel::Init_InheritAttributes();
  1165. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1166. // Display lists
  1167. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  1168. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1169. // Search criteria
  1170. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1171. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1172. }
  1173. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  1174. {
  1175. $sHtml = "<select name=\"$sFieldName\">\n";
  1176. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1177. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  1178. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1179. {
  1180. if ($oAttDef->IsScalar())
  1181. {
  1182. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1183. $sHtml .= "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  1184. }
  1185. }
  1186. $sHtml .= "</select>\n";
  1187. return $sHtml;
  1188. }
  1189. }
  1190. class SynchroAttLinkSet extends SynchroAttribute
  1191. {
  1192. public static function Init()
  1193. {
  1194. $aParams = array
  1195. (
  1196. "category" => "core/cmdb,view_in_gui",
  1197. "key_type" => "autoincrement",
  1198. "name_attcode" => "attcode",
  1199. "state_attcode" => "",
  1200. "reconc_keys" => array(),
  1201. "db_table" => "priv_sync_att_linkset",
  1202. "db_key_field" => "id",
  1203. "db_finalclass_field" => "",
  1204. "display_template" => "",
  1205. );
  1206. MetaModel::Init_Params($aParams);
  1207. MetaModel::Init_InheritAttributes();
  1208. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1209. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1210. MetaModel::Init_AddAttribute(new AttributeString("value_separator", array("allowed_values"=>null, "sql"=>"value_separator", "default_value"=>':', "is_null_allowed"=>true, "depends_on"=>array())));
  1211. MetaModel::Init_AddAttribute(new AttributeString("attribute_qualifier", array("allowed_values"=>null, "sql"=>"attribute_qualifier", "default_value"=>'\'', "is_null_allowed"=>true, "depends_on"=>array())));
  1212. // Display lists
  1213. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'row_separator', 'attribute_separator', 'value_separator', 'attribute_qualifier')); // Attributes to be displayed for the complete details
  1214. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1215. // Search criteria
  1216. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1217. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1218. }
  1219. }
  1220. //class SynchroLog extends Event
  1221. class SynchroLog extends DBObject
  1222. {
  1223. public static function Init()
  1224. {
  1225. $aParams = array
  1226. (
  1227. "category" => "core/cmdb,view_in_gui",
  1228. "key_type" => "autoincrement",
  1229. "name_attcode" => "",
  1230. "state_attcode" => "",
  1231. "reconc_keys" => array(),
  1232. "db_table" => "priv_sync_log",
  1233. "db_key_field" => "id",
  1234. "db_finalclass_field" => "",
  1235. "display_template" => "",
  1236. );
  1237. MetaModel::Init_Params($aParams);
  1238. MetaModel::Init_InheritAttributes();
  1239. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1240. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  1241. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1242. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1243. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('running,completed,error'), "sql"=>"status", "default_value"=>"running", "is_null_allowed"=>false, "depends_on"=>array())));
  1244. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_job", array("allowed_values"=>null, "sql"=>"status_curr_job", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1245. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_pos", array("allowed_values"=>null, "sql"=>"status_curr_pos", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1246. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_seen", array("allowed_values"=>null, "sql"=>"stats_nb_replica_seen", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1247. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_total", array("allowed_values"=>null, "sql"=>"stats_nb_replica_total", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1248. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_deleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1249. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_deleted_errors", array("allowed_values"=>null, "sql"=>"stats_deleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1250. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1251. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_obsoleted_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_obsoleted_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1252. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1253. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1254. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1255. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1256. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_errors", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1257. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1258. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1259. // MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1260. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_reconciled_errors", array("allowed_values"=>null, "sql"=>"stats_nb_replica_reconciled_errors", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1261. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_replica_disappeared_no_action", array("allowed_values"=>null, "sql"=>"stats_nb_replica_disappeared_no_action", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1262. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_updated", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_updated", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1263. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1264. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_unchanged", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_unchanged", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1265. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1266. MetaModel::Init_AddAttribute(new AttributeText("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1267. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1268. MetaModel::Init_AddAttribute(new AttributeInteger("memory_usage_peak", array("allowed_values"=>null, "sql"=>"memory_usage_peak", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1269. // Display lists
  1270. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_total', 'stats_nb_replica_seen', 'stats_nb_obj_created', /*'stats_nb_replica_reconciled',*/ 'stats_nb_obj_updated', 'stats_nb_obj_obsoleted', 'stats_nb_obj_deleted',
  1271. 'stats_nb_obj_created_errors', 'stats_nb_replica_reconciled_errors', 'stats_nb_replica_disappeared_no_action', 'stats_nb_obj_updated_errors', 'stats_nb_obj_obsoleted_errors', 'stats_nb_obj_deleted_errors', 'stats_nb_obj_new_unchanged', 'stats_nb_obj_new_updated', 'traces')); // Attributes to be displayed for the complete details
  1272. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1273. // Search criteria
  1274. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1275. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1276. }
  1277. /**
  1278. * Helper
  1279. */
  1280. function GetErrorCount()
  1281. {
  1282. return $this->Get('stats_nb_obj_deleted_errors')
  1283. + $this->Get('stats_nb_obj_obsoleted_errors')
  1284. + $this->Get('stats_nb_obj_created_errors')
  1285. + $this->Get('stats_nb_obj_updated_errors')
  1286. + $this->Get('stats_nb_replica_reconciled_errors');
  1287. }
  1288. /**
  1289. * Increments a statistics counter
  1290. */
  1291. function Inc($sCode)
  1292. {
  1293. $this->Set($sCode, 1+$this->Get($sCode));
  1294. }
  1295. /**
  1296. * Implement traces management
  1297. */
  1298. protected $m_aTraces = array();
  1299. public function AddTrace($sMsg, $oReplica = null)
  1300. {
  1301. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1302. {
  1303. return;
  1304. }
  1305. if ($oReplica)
  1306. {
  1307. $sDestClass = $oReplica->Get('dest_class');
  1308. if (!empty($sDestClass))
  1309. {
  1310. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1311. }
  1312. else
  1313. {
  1314. $sPrefix = $oReplica->GetKey().',,';
  1315. }
  1316. }
  1317. else
  1318. {
  1319. $sPrefix = ',,';
  1320. }
  1321. $this->m_aTraces[] = $sPrefix.$sMsg;
  1322. }
  1323. public function GetTraces()
  1324. {
  1325. return $this->m_aTraces;
  1326. }
  1327. protected function TraceToText()
  1328. {
  1329. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1330. {
  1331. // none, or display only
  1332. return;
  1333. }
  1334. $sPrevTrace = $this->Get('traces');
  1335. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1336. $iMaxSize = $oAttDef->GetMaxSize();
  1337. if (strlen($sPrevTrace) > 0)
  1338. {
  1339. $sTrace = $sPrevTrace."\n".implode("\n", $this->m_aTraces);
  1340. }
  1341. else
  1342. {
  1343. $sTrace = implode("\n", $this->m_aTraces);
  1344. }
  1345. if (strlen($sTrace) >= $iMaxSize)
  1346. {
  1347. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1348. }
  1349. $this->Set('traces', $sTrace);
  1350. //DBUpdate may be called many times... the operation should not be repeated
  1351. $this->m_aTraces = array();
  1352. }
  1353. protected function OnInsert()
  1354. {
  1355. $this->TraceToText();
  1356. parent::OnInsert();
  1357. }
  1358. protected function OnUpdate()
  1359. {
  1360. $this->TraceToText();
  1361. $sMemPeak = max($this->Get('memory_usage_peak'), ExecutionKPI::memory_get_peak_usage());
  1362. $this->Set('memory_usage_peak', $sMemPeak);
  1363. parent::OnUpdate();
  1364. }
  1365. }
  1366. class SynchroReplica extends DBObject implements iDisplay
  1367. {
  1368. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1369. protected $aWarnings;
  1370. public static function Init()
  1371. {
  1372. $aParams = array
  1373. (
  1374. "category" => "core/cmdb,view_in_gui",
  1375. "key_type" => "autoincrement",
  1376. "name_attcode" => "",
  1377. "state_attcode" => "",
  1378. "reconc_keys" => array(),
  1379. "db_table" => "priv_sync_replica",
  1380. "db_key_field" => "id",
  1381. "db_finalclass_field" => "",
  1382. "display_template" => "",
  1383. );
  1384. MetaModel::Init_Params($aParams);
  1385. MetaModel::Init_InheritAttributes();
  1386. MetaModel::Init_AddAttribute(new AttributeExternalKey("sync_source_id", array("targetclass"=>"SynchroDataSource", "jointype"=> "", "allowed_values"=>null, "sql"=>"sync_source_id", "is_null_allowed"=>false, "on_target_delete"=>DEL_SILENT, "depends_on"=>array())));
  1387. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1388. MetaModel::Init_AddAttribute(new AttributeObjectKey("dest_id", array("allowed_values"=>null, "class_attcode"=>"dest_class", "sql"=>"dest_id", "is_null_allowed"=>true, "depends_on"=>array())));
  1389. MetaModel::Init_AddAttribute(new AttributeClass("dest_class", array("class_category"=>"", "more_values"=>"", "sql"=>"dest_class", "default_value"=>'Organization', "is_null_allowed"=>true, "depends_on"=>array())));
  1390. MetaModel::Init_AddAttribute(new AttributeDateTime("status_last_seen", array("allowed_values"=>null, "sql"=>"status_last_seen", "default_value"=>"", "is_null_allowed"=>false, "depends_on"=>array())));
  1391. MetaModel::Init_AddAttribute(new AttributeEnum("status", array("allowed_values"=>new ValueSetEnum('new,synchronized,modified,orphan,obsolete'), "sql"=>"status", "default_value"=>"new", "is_null_allowed"=>false, "depends_on"=>array())));
  1392. MetaModel::Init_AddAttribute(new AttributeBoolean("status_dest_creator", array("allowed_values"=>null, "sql"=>"status_dest_creator", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1393. MetaModel::Init_AddAttribute(new AttributeString("status_last_error", array("allowed_values"=>null, "sql"=>"status_last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1394. MetaModel::Init_AddAttribute(new AttributeString("status_last_warning", array("allowed_values"=>null, "sql"=>"status_last_warning", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1395. MetaModel::Init_AddAttribute(new AttributeDateTime("info_creation_date", array("allowed_values"=>null, "sql"=>"info_creation_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1396. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_modified", array("allowed_values"=>null, "sql"=>"info_last_modified", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1397. // Display lists
  1398. MetaModel::Init_SetZListItems('details', array('' .
  1399. 'col:0'=> array(
  1400. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1401. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error','status_last_warning'),
  1402. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1403. )
  1404. );
  1405. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'status_last_warning')); // Attributes to be displayed for a list
  1406. // Search criteria
  1407. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error', 'status_last_warning')); // Criteria of the std search form
  1408. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1409. }
  1410. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  1411. {
  1412. parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  1413. $this->aWarnings = array();
  1414. }
  1415. protected function AddWarning($sWarningMessage)
  1416. {
  1417. $this->aWarnings[] = $sWarningMessage;
  1418. }
  1419. protected function ResetWarnings()
  1420. {
  1421. $this->aWarnings = array();
  1422. }
  1423. protected function HasWarnings()
  1424. {
  1425. return (count($this->aWarnings) > 0);
  1426. }
  1427. protected function RecordWarnings()
  1428. {
  1429. $sWarningMessage = '';
  1430. $MAX_WARNING_LENGTH = 255;
  1431. switch(count($this->aWarnings))
  1432. {
  1433. case 0:
  1434. $sWarningMessage = '';
  1435. break;
  1436. case 1:
  1437. $sWarningMessage = $this->aWarnings[0];
  1438. break;
  1439. default:
  1440. $sWarningMessage = count($this->aWarnings)." warnings: ".implode(' ', $this->aWarnings);
  1441. break;
  1442. }
  1443. if (strlen($sWarningMessage) > $MAX_WARNING_LENGTH)
  1444. {
  1445. $sWarningMessage = substr($sWarningMessage, 0, $MAX_WARNING_LENGTH - 3).'...';
  1446. }
  1447. $this->Set('status_last_warning', $sWarningMessage);
  1448. }
  1449. public function DBInsert()
  1450. {
  1451. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1452. }
  1453. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1454. // it will be deleted by the mean of a trigger too
  1455. protected function DBDeleteSingleObject()
  1456. {
  1457. $this->OnDelete();
  1458. if (!MetaModel::DBIsReadOnly())
  1459. {
  1460. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'), false);
  1461. if ($oDataSource)
  1462. {
  1463. $sTable = $oDataSource->GetDataTable();
  1464. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1465. CMDBSource::Query($sSQL);
  1466. }
  1467. // else the whole datasource has probably been already deleted
  1468. }
  1469. $this->AfterDelete();
  1470. $this->m_bIsInDB = false;
  1471. $this->m_iKey = null;
  1472. }
  1473. public function SetLastError($sMessage, $oException = null)
  1474. {
  1475. if ($oException)
  1476. {
  1477. $sText = $sMessage.$oException->getMessage();
  1478. }
  1479. else
  1480. {
  1481. $sText = $sMessage;
  1482. }
  1483. if (strlen($sText) > 255)
  1484. {
  1485. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1486. }
  1487. $this->Set('status_last_error', $sText);
  1488. }
  1489. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1490. {
  1491. $this->ResetWarnings();
  1492. switch($this->Get('status'))
  1493. {
  1494. case 'new':
  1495. $this->Set('status_dest_creator', false);
  1496. // If needed, construct the query used for the reconciliation
  1497. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1498. {
  1499. $aCriterias = array();
  1500. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1501. {
  1502. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1503. }
  1504. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1505. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1506. }
  1507. // Get the criterias for the search
  1508. $aFilterValues = array();
  1509. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1510. {
  1511. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1512. if (!is_null($value))
  1513. {
  1514. $aFilterValues[$sFilterCode] = $value;
  1515. }
  1516. else
  1517. {
  1518. // TO DO: can we retry this ??
  1519. // Reconciliation could not be performed - log and EXIT
  1520. $oStatLog->AddTrace("Could not reconcile on null value for attribute '$sFilterCode'", $this);
  1521. $this->SetLastError("Could not reconcile on null value for attribute '$sFilterCode'");
  1522. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1523. return;
  1524. }
  1525. }
  1526. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1527. $iCount = $oDestSet->Count();
  1528. $aConditions = array();
  1529. foreach($aFilterValues as $sCode => $sValue)
  1530. {
  1531. $aConditions[] = $sCode.'='.$sValue;
  1532. }
  1533. $sConditionDesc = implode(' AND ', $aConditions);
  1534. // How many objects match the reconciliation criterias
  1535. switch($iCount)
  1536. {
  1537. case 0:
  1538. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1539. if ($oDataSource->Get('action_on_zero') == 'create')
  1540. {
  1541. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1542. if ($bCreated)
  1543. {
  1544. if ($this->HasWarnings())
  1545. {
  1546. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1547. }
  1548. }
  1549. else
  1550. {
  1551. // Creation error has precedence over any warning
  1552. $this->ResetWarnings();
  1553. }
  1554. }
  1555. else // assumed to be 'error'
  1556. {
  1557. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1558. // Recoverable error
  1559. $this->SetLastError('Could not find a match for reconciliation');
  1560. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1561. }
  1562. break;
  1563. case 1:
  1564. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1565. if ($oDataSource->Get('action_on_one') == 'update')
  1566. {
  1567. $oDestObj = $oDestSet->Fetch();
  1568. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1569. $this->Set('dest_id', $oDestObj->GetKey());
  1570. $this->Set('dest_class', get_class($oDestObj));
  1571. if ($this->HasWarnings())
  1572. {
  1573. if ($bModified)
  1574. {
  1575. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1576. }
  1577. else
  1578. {
  1579. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1580. }
  1581. }
  1582. }
  1583. else
  1584. {
  1585. // assumed to be 'error'
  1586. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1587. // Recoverable error
  1588. $this->SetLastError('Found a match while expecting several');
  1589. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1590. }
  1591. break;
  1592. default:
  1593. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1594. if ($oDataSource->Get('action_on_multiple') == 'error')
  1595. {
  1596. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1597. // Recoverable error
  1598. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1599. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1600. }
  1601. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1602. {
  1603. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1604. if ($bCreated)
  1605. {
  1606. if ($this->HasWarnings())
  1607. {
  1608. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1609. }
  1610. }
  1611. else
  1612. {
  1613. // Creation error has precedence over any warning
  1614. $this->ResetWarnings();
  1615. }
  1616. }
  1617. else
  1618. {
  1619. // assumed to be 'take_first'
  1620. $oDestObj = $oDestSet->Fetch();
  1621. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1622. $this->Set('dest_id', $oDestObj->GetKey());
  1623. $this->Set('dest_class', get_class($oDestObj));
  1624. if ($this->HasWarnings())
  1625. {
  1626. if ($bModified)
  1627. {
  1628. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1629. }
  1630. else
  1631. {
  1632. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1633. }
  1634. }
  1635. }
  1636. }
  1637. $this->RecordWarnings();
  1638. break;
  1639. case 'synchronized': // try to recover synchronized replicas with warnings
  1640. case 'modified':
  1641. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1642. if ($oDestObj == null)
  1643. {
  1644. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1645. $this->SetLastError('Destination object deleted unexpectedly');
  1646. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1647. }
  1648. else
  1649. {
  1650. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1651. if ($this->HasWarnings())
  1652. {
  1653. if ($bModified)
  1654. {
  1655. $oStatLog->Inc('stats_nb_obj_updated_warnings');
  1656. }
  1657. else
  1658. {
  1659. $oStatLog->Inc('stats_nb_obj_unchanged_warnings');
  1660. }
  1661. }
  1662. }
  1663. $this->RecordWarnings();
  1664. break;
  1665. default: // Do nothing in all other cases
  1666. }
  1667. }
  1668. /**
  1669. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1670. */
  1671. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1672. {
  1673. $aValueTrace = array();
  1674. $bModified = false;
  1675. try
  1676. {
  1677. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1678. {
  1679. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1680. if (!is_null($value))
  1681. {
  1682. if ($oSyncAtt->Get('update_policy') == 'write_if_empty')
  1683. {
  1684. $oAttDef = MetaModel::GetAttributeDef(get_class($oDestObj), $sAttCode);
  1685. if ($oAttDef->IsNull($oDestObj->Get($sAttCode)))
  1686. {
  1687. // The value is still "empty" in the target object, we are allowed to write the new value
  1688. $oDestObj->Set($sAttCode, $value);
  1689. $aValueTrace[] = "$sAttCode: $value";
  1690. }
  1691. }
  1692. else
  1693. {
  1694. $oDestObj->Set($sAttCode, $value);
  1695. $aValueTrace[] = "$sAttCode: $value";
  1696. }
  1697. }
  1698. }
  1699. // Really modified ?
  1700. if ($oDestObj->IsModified())
  1701. {
  1702. $oDestObj->DBUpdateTracked($oChange);
  1703. $bModified = true;
  1704. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1705. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_updated')))
  1706. {
  1707. $oStatLog->Inc($sStatsCode.'_updated');
  1708. }
  1709. $this->Set('info_last_modified', date(AttributeDateTime::GetSQLFormat()));
  1710. }
  1711. else
  1712. {
  1713. $oStatLog->AddTrace('Unchanged object', $this);
  1714. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_unchanged')))
  1715. {
  1716. $oStatLog->Inc($sStatsCode.'_unchanged');
  1717. }
  1718. }
  1719. $this->Set('status_last_error', '');
  1720. $this->Set('status', 'synchronized');
  1721. }
  1722. catch(Exception $e)
  1723. {
  1724. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1725. $this->SetLastError('Unable to update destination object: ', $e);
  1726. $oStatLog->Inc($sStatsCodeError);
  1727. }
  1728. return $bModified;
  1729. }
  1730. /**
  1731. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1732. * @return bool Whether or not the object was created
  1733. */
  1734. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1735. {
  1736. $bCreated = false;
  1737. $oDestObj = MetaModel::NewObject($sClass);
  1738. try
  1739. {
  1740. $aValueTrace = array();
  1741. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1742. {
  1743. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1744. if (!is_null($value))
  1745. {
  1746. $oDestObj->Set($sAttCode, $value);
  1747. $aValueTrace[] = "$sAttCode: $value";
  1748. }
  1749. }
  1750. $iNew = $oDestObj->DBInsertTracked($oChange);
  1751. $this->Set('dest_id', $oDestObj->GetKey());
  1752. $this->Set('dest_class', get_class($oDestObj));
  1753. $this->Set('status_dest_creator', true);
  1754. $this->Set('status_last_error', '');
  1755. $this->Set('status', 'synchronized');
  1756. $this->Set('info_creation_date', date(AttributeDateTime::GetSQLFormat()));
  1757. $bCreated = true;
  1758. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1759. $oStatLog->Inc('stats_nb_obj_created');
  1760. }
  1761. catch(Exception $e)
  1762. {
  1763. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1764. $this->SetLastError('Unable to create destination object: ', $e);
  1765. $oStatLog->Inc('stats_nb_obj_created_errors');
  1766. }
  1767. return $bCreated;
  1768. }
  1769. /**
  1770. * Update the destination object with given values
  1771. */
  1772. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1773. {
  1774. try
  1775. {
  1776. if ($this->Get('dest_class') == '')
  1777. {
  1778. $this->SetLastError('No destination object to update');
  1779. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1780. }
  1781. else
  1782. {
  1783. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1784. foreach($aValues as $sAttCode => $value)
  1785. {
  1786. if (!MetaModel::IsValidAttCode(get_class($oDestObj), $sAttCode))
  1787. {
  1788. throw new Exception("Unknown attribute code '$sAttCode'");
  1789. }
  1790. $oDestObj->Set($sAttCode, $value);
  1791. }
  1792. $this->Set('info_last_modified', date(AttributeDateTime::GetSQLFormat()));
  1793. $oDestObj->DBUpdateTracked($oChange);
  1794. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1795. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1796. }
  1797. }
  1798. catch(Exception $e)
  1799. {
  1800. $this->SetLastError('Unable to update the destination object: ', $e);
  1801. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1802. }
  1803. }
  1804. /**
  1805. * Delete the destination object
  1806. */
  1807. public function DeleteDestObject($oChange, &$oStatLog)
  1808. {
  1809. if($this->Get('status_dest_creator'))
  1810. {
  1811. try
  1812. {
  1813. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1814. $oCheckDeletionPlan = new DeletionPlan();
  1815. if ($oDestObj->CheckToDelete($oCheckDeletionPlan))
  1816. {
  1817. $oActualDeletionPlan = new DeletionPlan();
  1818. $oDestObj->DBDeleteTracked($oChange, null, $oActualDeletionPlan);
  1819. $this->DBDeleteTracked($oChange);
  1820. $oStatLog->Inc('stats_nb_obj_deleted');
  1821. }
  1822. else
  1823. {
  1824. $sIssues = implode("\n", $oCheckDeletionPlan->GetIssues());
  1825. throw(new Exception($sIssues));
  1826. }
  1827. }
  1828. catch(Exception $e)
  1829. {
  1830. $this->SetLastError('Unable to delete the destination object: ', $e);
  1831. $this->Set('status', 'obsolete');
  1832. $this->DBUpdateTracked($oChange);
  1833. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1834. }
  1835. }
  1836. else
  1837. {
  1838. $this->DBDeleteTracked($oChange);
  1839. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1840. }
  1841. }
  1842. /**
  1843. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1844. * Note: sExtAttCode could be a standard attcode, or 'primary_key'
  1845. */
  1846. protected function GetValueFromExtData($sExtAttCode, $oSyncAtt, &$oStatLog)
  1847. {
  1848. // $aData should contain attributes defined either for reconciliation or create/update
  1849. $aData = $this->GetExtendedData();
  1850. if ($sExtAttCode == 'primary_key')
  1851. {
  1852. return $aData['primary_key'];
  1853. }
  1854. // $sExtAttCode is a valid attribute code
  1855. //
  1856. $sClass = $this->Get('base_class');
  1857. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExtAttCode);
  1858. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1859. {
  1860. $rawValue = $aData[$sExtAttCode];
  1861. if (is_null($rawValue))
  1862. {
  1863. // Null means "ignore" this attribute
  1864. return null;
  1865. }
  1866. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1867. if (!empty($sReconcAttCode))
  1868. {
  1869. $sRemoteClass = $oAttDef->GetTargetClass();
  1870. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1871. if ($oObj)
  1872. {
  1873. $retValue = $oObj->GetKey();
  1874. }
  1875. else
  1876. {
  1877. if ($rawValue != '')
  1878. {
  1879. // Note: differs from null (in which case the value would be left unchanged)
  1880. $oStatLog->AddTrace("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1881. $this->AddWarning("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'");
  1882. }
  1883. $retValue = 0;
  1884. }
  1885. }
  1886. else
  1887. {
  1888. $retValue = $rawValue;
  1889. }
  1890. }
  1891. elseif (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttLinkSet))
  1892. {
  1893. $rawValue = $aData[$sExtAttCode];
  1894. if (is_null($rawValue))
  1895. {
  1896. // Null means "ignore" this attribute
  1897. return null;
  1898. }
  1899. // MakeValueFromString() throws an exception in case of failure
  1900. $bLocalizedValue = false;
  1901. $retValue = $oAttDef->MakeValueFromString($rawValue, $bLocalizedValue, $oSyncAtt->Get('row_separator'), $oSyncAtt->Get('attribute_separator'), $oSyncAtt->Get('value_separator'), $oSyncAtt->Get('attribute_qualifier'));
  1902. }
  1903. else
  1904. {
  1905. $aColumns = $oAttDef->GetImportColumns();
  1906. foreach($aColumns as $sColumn => $sFormat)
  1907. {
  1908. // In any case, a null column means "ignore this attribute"
  1909. //
  1910. if (is_null($aData[$sColumn]))
  1911. {
  1912. return null;
  1913. }
  1914. }
  1915. $retValue = $oAttDef->FromImportToValue($aData, $sExtAttCode);
  1916. }
  1917. return $retValue;
  1918. }
  1919. /**
  1920. * Maps the given context parameter name to the appropriate filter/search code for this class
  1921. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1922. * @return string Filter code, i.e. 'customer_id'
  1923. */
  1924. public static function MapContextParam($sContextParam)
  1925. {
  1926. if ($sContextParam == 'menu')
  1927. {
  1928. return null;
  1929. }
  1930. else
  1931. {
  1932. return $sContextParam;
  1933. }
  1934. }
  1935. /**
  1936. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1937. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1938. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1939. * To Be overridden by derived classes
  1940. * @param void
  1941. * @return String The desired higlight class for the object/row
  1942. */
  1943. public function GetHilightClass()
  1944. {
  1945. // Possible return values are:
  1946. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1947. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1948. }
  1949. public static function GetUIPage()
  1950. {
  1951. return '../synchro/replica.php';
  1952. }
  1953. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1954. {
  1955. // Object's details
  1956. //$this->DisplayBareHeader($oPage, $bEditMode);
  1957. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1958. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1959. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1960. $this->DisplayBareProperties($oPage, $bEditMode);
  1961. }
  1962. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  1963. {
  1964. if ($bEditMode) return; // Not editable
  1965. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1966. $aDetails = array();
  1967. $sClass = get_class($this);
  1968. $oPage->add('<fieldset>');
  1969. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1970. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1971. foreach( $aZList as $sAttCode)
  1972. {
  1973. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1974. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1975. }
  1976. $oPage->Details($aDetails);
  1977. $oPage->add('</fieldset>');
  1978. if (strlen($this->Get('dest_class')) > 0)
  1979. {
  1980. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'), false);
  1981. if (is_object($oDestObj))
  1982. {
  1983. $oPage->add('<fieldset>');
  1984. $oPage->add('<legend>'.Dict::Format('Core:SynchroReplica:TargetObject', $oDestObj->GetHyperlink()).'</legend>');
  1985. $oDestObj->DisplayBareProperties($oPage, false, $sPrefix, $aExtraParams);
  1986. $oPage->add('<fieldset>');
  1987. }
  1988. }
  1989. $oPage->add('</td><td>');
  1990. $oPage->add('<fieldset>');
  1991. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  1992. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1993. $sSQLTable = $oSource->GetDataTable();
  1994. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  1995. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  1996. 'data' => array('label' => 'Value', 'description' => ''));
  1997. $aRows = array();
  1998. foreach($aData as $sKey => $value)
  1999. {
  2000. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  2001. }
  2002. $oPage->Table($aHeaders, $aRows);
  2003. $oPage->add('</fieldset>');
  2004. $oPage->add('</td></tr></table>');
  2005. }
  2006. public function LoadExtendedDataFromTable($sSQLTable)
  2007. {
  2008. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  2009. $rQuery = CMDBSource::Query($sSQL);
  2010. return CMDBSource::FetchArray($rQuery);
  2011. }
  2012. }
  2013. /**
  2014. * Context of an ongoing synchronization
  2015. * Two usages:
  2016. * 1) Public usage: execute the synchronization
  2017. * $oSynchroExec = new SynchroExecution($oDataSource[, $iLastFullLoad]);
  2018. * $oSynchroExec->Process($iMaxChunkSize);
  2019. *
  2020. * 2) Internal usage: continue the synchronization (split into chunks, each performed in a separate process)
  2021. * This is implemented in the page priv_sync_chunk.php
  2022. * $oSynchroExec = SynchroExecution::Resume($oDataSource, $iLastFullLoad, $iSynchroLog, $iChange, $iMaxToProcess, $iJob, $iNextInJob);
  2023. * $oSynchroExec->Process()
  2024. */
  2025. class SynchroExecution
  2026. {
  2027. protected $m_oDataSource = null;
  2028. protected $m_oLastFullLoadStartDate = null;
  2029. protected $m_oChange = null;
  2030. protected $m_oStatLog = null;
  2031. // Context computed one for optimization and report inconsistencies ASAP
  2032. protected $m_aExtDataSpec = array();
  2033. protected $m_aReconciliationKeys = array();
  2034. protected $m_aAttributes = array();
  2035. protected $m_iCountAllReplicas = 0;
  2036. /**
  2037. * Constructor
  2038. * @param SynchroDataSource $oDataSource Synchronization task
  2039. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  2040. * @return void
  2041. */
  2042. public function __construct($oDataSource, $oLastFullLoadStartDate = null)
  2043. {
  2044. $this->m_oDataSource = $oDataSource;
  2045. $this->m_oLastFullLoadStartDate = $oLastFullLoadStartDate;
  2046. }
  2047. /**
  2048. * Create the persistant information records, for the current synchronization
  2049. * In fact, those records ARE defining what is the "current" synchronization
  2050. */
  2051. protected function PrepareLogs()
  2052. {
  2053. if (!is_null($this->m_oChange))
  2054. {
  2055. return;
  2056. }
  2057. // Create a change used for logging all the modifications/creations happening during the synchro
  2058. $this->m_oChange = MetaModel::NewObject("CMDBChange");
  2059. $this->m_oChange->Set("date", time());
  2060. $sUserString = CMDBChange::GetCurrentUserName();
  2061. $this->m_oChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  2062. $this->m_oChange->Set("origin", 'synchro-data-source');
  2063. $iChangeId = $this->m_oChange->DBInsert();
  2064. // Start logging this execution (stats + protection against reentrance)
  2065. //
  2066. $this->m_oStatLog = new SynchroLog();
  2067. $this->m_oStatLog->Set('sync_source_id', $this->m_oDataSource->GetKey());
  2068. $this->m_oStatLog->Set('start_date', time());
  2069. $this->m_oStatLog->Set('status', 'running');
  2070. $this->m_oStatLog->Set('stats_nb_replica_seen', 0);
  2071. $this->m_oStatLog->Set('stats_nb_replica_total', 0);
  2072. $this->m_oStatLog->Set('stats_nb_obj_deleted', 0);
  2073. $this->m_oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  2074. $this->m_oStatLog->Set('stats_nb_obj_obsoleted', 0);
  2075. $this->m_oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  2076. $this->m_oStatLog->Set('stats_nb_obj_created', 0);
  2077. $this->m_oStatLog->Set('stats_nb_obj_created_errors', 0);
  2078. $this->m_oStatLog->Set('stats_nb_obj_created_warnings', 0);
  2079. $this->m_oStatLog->Set('stats_nb_obj_updated', 0);
  2080. $this->m_oStatLog->Set('stats_nb_obj_updated_warnings', 0);
  2081. $this->m_oStatLog->Set('stats_nb_obj_updated_errors', 0);
  2082. $this->m_oStatLog->Set('stats_nb_obj_unchanged_warnings', 0);
  2083. // $this->m_oStatLog->Set('stats_nb_replica_reconciled', 0);
  2084. $this->m_oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  2085. $this->m_oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  2086. $this->m_oStatLog->Set('stats_nb_obj_new_updated', 0);
  2087. $this->m_oStatLog->Set('stats_nb_obj_new_updated_warnings', 0);
  2088. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged',0);
  2089. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged_warnings',0);
  2090. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  2091. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()));
  2092. $this->m_iCountAllReplicas = $oSetTotal->Count();
  2093. $this->m_oStatLog->Set('stats_nb_replica_total', $this->m_iCountAllReplicas);
  2094. $this->m_oStatLog->DBInsertTracked($this->m_oChange);
  2095. }
  2096. /**
  2097. * Prevent against the reentrance... or allow the current task to do things forbidden by the others !
  2098. */
  2099. public static $m_oCurrentTask = null;
  2100. public static function GetCurrentTaskId()
  2101. {
  2102. if (is_object(self::$m_oCurrentTask))
  2103. {
  2104. return self::$m_oCurrentTask->GetKey();
  2105. }
  2106. else
  2107. {
  2108. return null;
  2109. }
  2110. }
  2111. /**
  2112. * Prepare structures in memory, to speedup the processing of a given replica
  2113. */
  2114. public function PrepareProcessing($bFirstPass = true)
  2115. {
  2116. if ($this->m_oDataSource->Get('status') == 'obsolete')
  2117. {
  2118. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  2119. }
  2120. if (!UserRights::IsAdministrator() && $this->m_oDataSource->Get('user_id') != UserRights::GetUserId())
  2121. {
  2122. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  2123. }
  2124. // Get the list of SQL columns
  2125. $sClass = $this->m_oDataSource->GetTargetClass();
  2126. $aAttCodesExpected = array();
  2127. $aAttCodesToReconcile = array();
  2128. $aAttCodesToUpdate = array();
  2129. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  2130. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()) /* aArgs */);
  2131. while ($oSyncAtt = $oSetAtt->Fetch())
  2132. {
  2133. if ($oSyncAtt->Get('update'))
  2134. {
  2135. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2136. }
  2137. if ($oSyncAtt->Get('reconcile'))
  2138. {
  2139. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2140. }
  2141. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2142. }
  2143. $aColumns = $this->m_oDataSource->GetSQLColumns(array_keys($aAttCodesExpected));
  2144. $aExtDataFields = array_keys($aColumns);
  2145. $aExtDataFields[] = 'primary_key';
  2146. $this->m_aExtDataSpec = array(
  2147. 'table' => $this->m_oDataSource->GetDataTable(),
  2148. 'join_key' => 'id',
  2149. 'fields' => $aExtDataFields
  2150. );
  2151. // Get the list of attributes, determine reconciliation keys and update targets
  2152. //
  2153. if ($this->m_oDataSource->Get('reconciliation_policy') == 'use_attributes')
  2154. {
  2155. $this->m_aReconciliationKeys = $aAttCodesToReconcile;
  2156. }
  2157. elseif ($this->m_oDataSource->Get('reconciliation_policy') == 'use_primary_key')
  2158. {
  2159. // Override the settings made at the attribute level !
  2160. $this->m_aReconciliationKeys = array("primary_key" => null);
  2161. }
  2162. if ($bFirstPass)
  2163. {
  2164. $this->m_oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  2165. $this->m_oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($this->m_aReconciliationKeys))."}");
  2166. }
  2167. if (count($aAttCodesToUpdate) == 0)
  2168. {
  2169. $this->m_oStatLog->AddTrace("No attribute to update");
  2170. throw new SynchroExceptionNotStarted('There is no attribute to update');
  2171. }
  2172. if (count($this->m_aReconciliationKeys) == 0)
  2173. {
  2174. $this->m_oStatLog->AddTrace("No attribute for reconciliation");
  2175. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  2176. }
  2177. $this->m_aAttributes = array();
  2178. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  2179. {
  2180. $oAttDef = MetaModel::GetAttributeDef($this->m_oDataSource->GetTargetClass(), $sAttCode);
  2181. if ($oAttDef->IsWritable())
  2182. {
  2183. $this->m_aAttributes[$sAttCode] = $oSyncAtt;
  2184. }
  2185. }
  2186. // Compute and keep track of the limit date taken into account for obsoleting replicas
  2187. //
  2188. if ($this->m_oLastFullLoadStartDate == null)
  2189. {
  2190. // No previous import known, use the full_load_periodicity value... and the current date
  2191. $this->m_oLastFullLoadStartDate = new DateTime(); // Now
  2192. $iLoadPeriodicity = $this->m_oDataSource->Get('full_load_periodicity'); // Duration in seconds
  2193. if ($iLoadPeriodicity > 0)
  2194. {
  2195. $sInterval = "-$iLoadPeriodicity seconds";
  2196. $this->m_oLastFullLoadStartDate->Modify($sInterval);
  2197. }
  2198. else
  2199. {
  2200. $this->m_oLastFullLoadStartDate = new DateTime('1970-01-01');
  2201. }
  2202. }
  2203. if ($bFirstPass)
  2204. {
  2205. $this->m_oStatLog->AddTrace("Limit Date: ".$this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'));
  2206. }
  2207. }
  2208. /**
  2209. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  2210. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  2211. * is used to determine which records are obsolete.
  2212. * @return void
  2213. */
  2214. public function Process()
  2215. {
  2216. $this->PrepareLogs();
  2217. self::$m_oCurrentTask = $this->m_oDataSource;
  2218. $oMutex = new iTopMutex('synchro_process_'.$this->m_oDataSource->GetKey());
  2219. try
  2220. {
  2221. $oMutex->Lock();
  2222. $this->DoSynchronize();
  2223. $oMutex->Unlock();
  2224. $this->m_oStatLog->Set('end_date', time());
  2225. $this->m_oStatLog->Set('status', 'completed');
  2226. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2227. $iErrors = $this->m_oStatLog->GetErrorCount();
  2228. if ($iErrors > 0)
  2229. {
  2230. $sIssuesOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->m_oDataSource->GetKey()." AND status_last_error!=''";
  2231. $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
  2232. $sIssuesURL = "{$sAbsoluteUrl}synchro/replica.php?operation=oql&datasource=".$this->m_oDataSource->GetKey()."&oql=".urlencode($sIssuesOQL);
  2233. $sSeeIssues = "<p></p>";
  2234. $sStatistics = "<h1>Statistics</h1>\n";
  2235. $sStatistics .= "<ul>\n";
  2236. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('start_date').": ".$this->m_oStatLog->Get('start_date')."</li>\n";
  2237. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('end_date').": ".$this->m_oStatLog->Get('end_date')."</li>\n";
  2238. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_seen').": ".$this->m_oStatLog->Get('stats_nb_replica_seen')."</li>\n";
  2239. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_total').": ".$this->m_oStatLog->Get('stats_nb_replica_total')."</li>\n";
  2240. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted')."</li>\n";
  2241. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted_errors')."</li>\n";
  2242. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted')."</li>\n";
  2243. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted_errors')."</li>\n";
  2244. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created').": ".$this->m_oStatLog->Get('stats_nb_obj_created')." (".$this->m_oStatLog->Get('stats_nb_obj_created_warnings')." warnings)"."</li>\n";
  2245. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_created_errors')."</li>\n";
  2246. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_updated_warnings')." warnings)"."</li>\n";
  2247. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_updated_errors')."</li>\n";
  2248. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_reconciled_errors').": ".$this->m_oStatLog->Get('stats_nb_replica_reconciled_errors')."</li>\n";
  2249. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_disappeared_no_action').": ".$this->m_oStatLog->Get('stats_nb_replica_disappeared_no_action')."</li>\n";
  2250. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_new_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_new_updated_warnings')." warnings)"."</li>\n";
  2251. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_unchanged').": ".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged')." (".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged_warnings')." warnings)"."</li>\n";
  2252. $sStatistics .= "</ul>\n";
  2253. $this->m_oDataSource->SendNotification("errors ($iErrors)", "<p>The synchronization has been executed, $iErrors errors have been encountered. Click <a href=\"$sIssuesURL\">here</a> to see the records being currently in error.</p>".$sStatistics);
  2254. }
  2255. else
  2256. {
  2257. //$this->m_oDataSource->SendNotification('success', '<p>The synchronization has been successfully executed.</p>');
  2258. }
  2259. }
  2260. catch (SynchroExceptionNotStarted $e)
  2261. {
  2262. $oMutex->Unlock();
  2263. // Set information for reporting... but delete the object in DB
  2264. $this->m_oStatLog->Set('end_date', time());
  2265. $this->m_oStatLog->Set('status', 'error');
  2266. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2267. $this->m_oStatLog->DBDeleteTracked($this->m_oChange);
  2268. $this->m_oDataSource->SendNotification('fatal error', '<p>The synchronization could not start: \''.$e->getMessage().'\'</p><p>Please check its configuration</p>');
  2269. }
  2270. catch (Exception $e)
  2271. {
  2272. $oMutex->Unlock();
  2273. $this->m_oStatLog->Set('end_date', time());
  2274. $this->m_oStatLog->Set('status', 'error');
  2275. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2276. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2277. $this->m_oDataSource->SendNotification('exception', '<p>The synchronization has been interrupted: \''.$e->getMessage().'\'</p><p>Please contact the application support team</p>');
  2278. }
  2279. self::$m_oCurrentTask = null;
  2280. return $this->m_oStatLog;
  2281. }
  2282. /**
  2283. * Do the entire synchronization job
  2284. */
  2285. protected function DoSynchronize()
  2286. {
  2287. $this->m_oStatLog->Set('status_curr_job', 1);
  2288. $this->m_oStatLog->Set('status_curr_pos', -1);
  2289. $iMaxChunkSize = utils::ReadParam('max_chunk_size', 0, true /* allow CLI */);
  2290. if ($iMaxChunkSize > 0)
  2291. {
  2292. // Split the execution into several processes
  2293. // Each process will call DoSynchronizeChunk()
  2294. // The loop will end when a process does not reply "continue" on the last line of its output
  2295. if (!utils::IsModeCLI())
  2296. {
  2297. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncSplitModeCLIOnly'));
  2298. }
  2299. $aArguments = array();
  2300. $aArguments['source'] = $this->m_oDataSource->GetKey();
  2301. $aArguments['log'] = $this->m_oStatLog->GetKey();
  2302. $aArguments['change'] = $this->m_oChange->GetKey();
  2303. $aArguments['chunk'] = $iMaxChunkSize;
  2304. if ($this->m_oLastFullLoadStartDate)
  2305. {
  2306. $aArguments['last_full_load'] = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2307. }
  2308. else
  2309. {
  2310. $aArguments['last_full_load'] = '';
  2311. }
  2312. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2313. $iStepCount = 0;
  2314. do
  2315. {
  2316. $aArguments['step_count'] = $iStepCount;
  2317. $iStepCount++;
  2318. list ($iRes, $aOut) = utils::ExecITopScript('synchro/priv_sync_chunk.php', $aArguments);
  2319. // Reload the log that has been modified by the processes
  2320. $this->m_oStatLog->Reload();
  2321. $sLastRes = strtolower(trim(end($aOut)));
  2322. switch($sLastRes)
  2323. {
  2324. case 'continue':
  2325. $bContinue = true;
  2326. break;
  2327. case 'finished':
  2328. $bContinue = false;
  2329. break;
  2330. default:
  2331. $this->m_oStatLog->AddTrace("The script did not reply with the expected keywords:");
  2332. $aIndentedOut = array();
  2333. foreach ($aOut as $sOut)
  2334. {
  2335. $aIndentedOut[] = "-> $sOut";
  2336. $this->m_oStatLog->AddTrace(">>> $sOut");
  2337. }
  2338. throw new Exception("Encountered an error in an underspinned process:\n".implode("\n", $aIndentedOut));
  2339. }
  2340. }
  2341. while ($bContinue);
  2342. }
  2343. else
  2344. {
  2345. $this->PrepareProcessing(/* first pass */);
  2346. $this->DoJob1();
  2347. $this->DoJob2();
  2348. $this->DoJob3();
  2349. }
  2350. }
  2351. /**
  2352. * Do the synchronization job, limited to some amount of work
  2353. * This verb has been designed to be called from within a separate process
  2354. * @return true if the process has to be continued
  2355. */
  2356. public function DoSynchronizeChunk($oLog, $oChange, $iMaxChunkSize)
  2357. {
  2358. // Initialize the structures...
  2359. self::$m_oCurrentTask = $this->m_oDataSource;
  2360. $this->m_oStatLog = $oLog;
  2361. $this->m_oChange = $oChange;
  2362. // Prepare internal structures (not the first pass)
  2363. $this->PrepareProcessing(false);
  2364. $iCurrJob = $this->m_oStatLog->Get('status_curr_job');
  2365. $iCurrPos = $this->m_oStatLog->Get('status_curr_pos');
  2366. $this->m_oStatLog->AddTrace("Synchronizing chunk - curr_job:$iCurrJob, curr_pos:$iCurrPos, max_chunk_size:$iMaxChunkSize");
  2367. $bContinue = false;
  2368. switch ($iCurrJob)
  2369. {
  2370. case 1:
  2371. default:
  2372. $this->DoJob1($iMaxChunkSize, $iCurrPos);
  2373. $bContinue = true;
  2374. break;
  2375. case 2:
  2376. $this->DoJob2($iMaxChunkSize, $iCurrPos);
  2377. $bContinue = true;
  2378. break;
  2379. case 3:
  2380. $bContinue = $this->DoJob3($iMaxChunkSize, $iCurrPos);
  2381. break;
  2382. }
  2383. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2384. self::$m_oCurrentTask = null;
  2385. return $bContinue;
  2386. }
  2387. /**
  2388. * Do the synchronization job #1: Obsolete replica "untouched" for some time
  2389. * @param integer $iMaxReplica Limit the number of replicas to process
  2390. * @param integer $iCurrPos Current position where to resume the processing
  2391. * @return true if the process must be continued
  2392. */
  2393. protected function DoJob1($iMaxReplica = null, $iCurrPos = -1)
  2394. {
  2395. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2396. // Get all the replicas that were not seen in the last import and mark them as obsolete
  2397. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2398. if ($sDeletePolicy != 'ignore')
  2399. {
  2400. $sSelectToObsolete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  2401. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2402. $iCountScope = $oSetScope->Count();
  2403. if (($this->m_iCountAllReplicas > 10) && ($this->m_iCountAllReplicas == $iCountScope) && MetaModel::GetConfig()->Get('synchro_prevent_delete_all'))
  2404. {
  2405. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  2406. }
  2407. if ($iMaxReplica)
  2408. {
  2409. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2410. // The replica have to be ordered by id
  2411. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2412. $oSetToProcess->SetLimit($iMaxReplica);
  2413. }
  2414. else
  2415. {
  2416. $oSetToProcess = $oSetScope;
  2417. }
  2418. $iLastReplicaProcessed = -1;
  2419. while($oReplica = $oSetToProcess->Fetch())
  2420. {
  2421. $iLastReplicaProcessed = $oReplica->GetKey();
  2422. switch ($sDeletePolicy)
  2423. {
  2424. case 'update':
  2425. case 'update_then_delete':
  2426. $this->m_oStatLog->AddTrace("Destination object to be updated", $oReplica);
  2427. $aToUpdate = array();
  2428. $aToUpdateSpec = explode(';', $this->m_oDataSource->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  2429. foreach($aToUpdateSpec as $sUpdateSpec)
  2430. {
  2431. $aUpdateSpec = explode(':', $sUpdateSpec);
  2432. if (count($aUpdateSpec) == 2)
  2433. {
  2434. $sAttCode = $aUpdateSpec[0];
  2435. $sValue = $aUpdateSpec[1];
  2436. $aToUpdate[$sAttCode] = $sValue;
  2437. }
  2438. }
  2439. $oReplica->Set('status_last_error', '');
  2440. if ($oReplica->Get('dest_id') == '')
  2441. {
  2442. $oReplica->Set('status', 'obsolete');
  2443. $this->m_oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  2444. }
  2445. else
  2446. {
  2447. $oReplica->UpdateDestObject($aToUpdate, $this->m_oChange, $this->m_oStatLog);
  2448. if ($oReplica->Get('status_last_error') == '')
  2449. {
  2450. // Change the status of the replica IIF
  2451. $oReplica->Set('status', 'obsolete');
  2452. }
  2453. }
  2454. $oReplica->DBUpdateTracked($this->m_oChange);
  2455. break;
  2456. case 'delete':
  2457. default:
  2458. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2459. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2460. }
  2461. }
  2462. if ($iMaxReplica)
  2463. {
  2464. if ($iMaxReplica < $iCountScope)
  2465. {
  2466. // Continue with this job!
  2467. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2468. return true;
  2469. }
  2470. }
  2471. } // if ($sDeletePolicy != 'ignore'
  2472. //Count "seen" objects
  2473. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  2474. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate));
  2475. $this->m_oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  2476. // Job complete!
  2477. $this->m_oStatLog->Set('status_curr_job', 2);
  2478. $this->m_oStatLog->Set('status_curr_pos', -1);
  2479. return false;
  2480. }
  2481. /**
  2482. * Do the synchronization job #2: Create and modify object for new/modified replicas
  2483. * @param integer $iMaxReplica Limit the number of replicas to process
  2484. * @param integer $iCurrPos Current position where to resume the processing
  2485. * @return true if the process must be continued
  2486. */
  2487. protected function DoJob2($iMaxReplica = null, $iCurrPos = -1)
  2488. {
  2489. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2490. // Get all the replicas that are 'new' or modified or synchronized with a warning
  2491. //
  2492. $sSelectToSync = "SELECT SynchroReplica WHERE id > :curr_pos AND (status = 'new' OR status = 'modified' OR (status = 'synchronized' AND status_last_warning != '')) AND sync_source_id = :source_id AND status_last_seen >= :last_import";
  2493. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2494. $iCountScope = $oSetScope->Count();
  2495. if ($iMaxReplica)
  2496. {
  2497. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2498. // The replica have to be ordered by id
  2499. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2500. $oSetToProcess->SetLimit($iMaxReplica);
  2501. }
  2502. else
  2503. {
  2504. $oSetToProcess = $oSetScope;
  2505. }
  2506. $iLastReplicaProcessed = -1;
  2507. while($oReplica = $oSetToProcess->Fetch())
  2508. {
  2509. $iLastReplicaProcessed = $oReplica->GetKey();
  2510. $oReplica->Synchro($this->m_oDataSource, $this->m_aReconciliationKeys, $this->m_aAttributes, $this->m_oChange, $this->m_oStatLog);
  2511. $oReplica->DBUpdateTracked($this->m_oChange);
  2512. }
  2513. if ($iMaxReplica)
  2514. {
  2515. if ($iMaxReplica < $iCountScope)
  2516. {
  2517. // Continue with this job!
  2518. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2519. return true;
  2520. }
  2521. }
  2522. // Job complete!
  2523. $this->m_oStatLog->Set('status_curr_job', 3);
  2524. $this->m_oStatLog->Set('status_curr_pos', -1);
  2525. return false;
  2526. }
  2527. /**
  2528. * Do the synchronization job #3: Delete replica depending on the obsolescence scheme
  2529. * @param integer $iMaxReplica Limit the number of replicas to process
  2530. * @param integer $iCurrPos Current position where to resume the processing
  2531. * @return true if the process must be continued
  2532. */
  2533. protected function DoJob3($iMaxReplica = null, $iCurrPos = -1)
  2534. {
  2535. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2536. if ($sDeletePolicy != 'update_then_delete')
  2537. {
  2538. // Job complete!
  2539. $this->m_oStatLog->Set('status_curr_job', 0);
  2540. $this->m_oStatLog->Set('status_curr_pos', -1);
  2541. return false;
  2542. }
  2543. $bFirstPass = ($iCurrPos == -1);
  2544. // Get all the replicas that are to be deleted
  2545. //
  2546. $oDeletionDate = $this->m_oLastFullLoadStartDate;
  2547. $iDeleteRetention = $this->m_oDataSource->Get('delete_policy_retention'); // Duration in seconds
  2548. if ($iDeleteRetention > 0)
  2549. {
  2550. $sInterval = "-$iDeleteRetention seconds";
  2551. $oDeletionDate->Modify($sInterval);
  2552. }
  2553. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  2554. if ($bFirstPass)
  2555. {
  2556. $this->m_oStatLog->AddTrace("Deletion date: $sDeletionDate");
  2557. }
  2558. $sSelectToDelete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  2559. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2560. $iCountScope = $oSetScope->Count();
  2561. if ($iMaxReplica)
  2562. {
  2563. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2564. // The replica have to be ordered by id
  2565. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2566. $oSetToProcess->SetLimit($iMaxReplica);
  2567. }
  2568. else
  2569. {
  2570. $oSetToProcess = $oSetScope;
  2571. }
  2572. $iLastReplicaProcessed = -1;
  2573. while($oReplica = $oSetToProcess->Fetch())
  2574. {
  2575. $iLastReplicaProcessed = $oReplica->GetKey();
  2576. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2577. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2578. }
  2579. if ($iMaxReplica)
  2580. {
  2581. if ($iMaxReplica < $iCountScope)
  2582. {
  2583. // Continue with this job!
  2584. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2585. return true;
  2586. }
  2587. }
  2588. // Job complete!
  2589. $this->m_oStatLog->Set('status_curr_job', 0);
  2590. $this->m_oStatLog->Set('status_curr_pos', -1);
  2591. return false;
  2592. }
  2593. }
  2594. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2595. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2596. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2597. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  2598. ?>