synchrodatasource.class.inc.php 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818
  1. <?php
  2. // Copyright (C) 2010-2012 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-2012 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. }
  600. public function DoCheckToWrite()
  601. {
  602. parent::DoCheckToWrite();
  603. // Check that there is at least one reconciliation key defined
  604. if ($this->Get('reconciliation_policy') == 'use_attributes')
  605. {
  606. $oSet = $this->Get('attribute_list');
  607. $oSynchroAttributeList = $oSet->ToArray();
  608. $bReconciliationKey = false;
  609. foreach($oSynchroAttributeList as $oSynchroAttribute)
  610. {
  611. if ($oSynchroAttribute->Get('reconcile') == 1)
  612. {
  613. $bReconciliationKey = true; // At least one key is defined
  614. break;
  615. }
  616. }
  617. if (!$bReconciliationKey)
  618. {
  619. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  620. }
  621. }
  622. // If 'update_then_delete' is specified there must be a delete_retention_period
  623. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  624. {
  625. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  626. }
  627. // If update is specified, then something to update must be defined
  628. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  629. && ($this->Get('delete_policy_update') == ''))
  630. {
  631. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  632. }
  633. // When creating the data source with a specified database_table_name, this table must NOT exist
  634. if ($this->IsNew())
  635. {
  636. $sDataTable = $this->GetDataTable();
  637. if (!empty($sDataTable) && CMDBSource::IsTable($this->GetDataTable()))
  638. {
  639. // Hmm, the synchro_data_xxx table already exists !!
  640. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DataTableAlreadyExists', $this->GetDataTable());
  641. }
  642. }
  643. }
  644. public function GetTargetClass()
  645. {
  646. return $this->Get('scope_class');
  647. }
  648. public function GetDataTable()
  649. {
  650. $sTable = $this->Get('database_table_name');
  651. if (empty($sTable))
  652. {
  653. $sTable = $this->ComputeDataTableName();
  654. }
  655. return $sTable;
  656. }
  657. protected function ComputeDataTableName()
  658. {
  659. $sDBTableName = $this->Get('database_table_name');
  660. if (empty($sDBTableName))
  661. {
  662. $sDBTableName = strtolower($this->GetTargetClass());
  663. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  664. $sDBTableName .= '_'.$this->GetKey(); // Add a suffix for unicity
  665. }
  666. else
  667. {
  668. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  669. }
  670. $sPrefix = MetaModel::GetConfig()->GetDBSubName()."synchro_data_";
  671. if (strpos($sDBTableName, $sPrefix) !== 0)
  672. {
  673. $sDBTableName = $sPrefix.$sDBTableName;
  674. }
  675. return $sDBTableName;
  676. }
  677. /**
  678. * When the new datasource has been created, let's create the synchro_data table
  679. * that will hold the data records and the correspoding triggers which will maintain
  680. * both tables in sync
  681. */
  682. protected function AfterInsert()
  683. {
  684. parent::AfterInsert();
  685. $sTable = $this->GetDataTable();
  686. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  687. $aColumns = $this->GetSQLColumns();
  688. $aFieldDefs = array();
  689. // Allow '0', otherwise mysql will render an error when the id is not given
  690. // (the trigger is expected to set the value, but it is not executed soon enough)
  691. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  692. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  693. foreach($aColumns as $sColumn => $ColSpec)
  694. {
  695. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  696. }
  697. $aFieldDefs[] = "INDEX (id)";
  698. $aFieldDefs[] = "INDEX (primary_key)";
  699. $sFieldDefs = implode(', ', $aFieldDefs);
  700. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
  701. CMDBSource::Query($sCreateTable);
  702. $aTriggers = $this->GetTriggersDefinition();
  703. foreach($aTriggers as $key => $sTriggerSQL)
  704. {
  705. CMDBSource::Query($sTriggerSQL);
  706. }
  707. }
  708. /**
  709. * Gets the definitions of the 3 triggers: before insert, before update and after delete
  710. * @return array An array with 3 entries, one for each of the SQL queries
  711. */
  712. protected function GetTriggersDefinition()
  713. {
  714. $sTable = $this->GetDataTable();
  715. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  716. $aColumns = $this->GetSQLColumns();
  717. $aResult = array();
  718. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON `$sTable`";
  719. $sTriggerInsert .= " FOR EACH ROW";
  720. $sTriggerInsert .= " BEGIN";
  721. $sTriggerInsert .= " INSERT INTO `{$sReplicaTable}` (`sync_source_id`, `status_last_seen`, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  722. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  723. $sTriggerInsert .= " END;";
  724. $aResult['bi'] = $sTriggerInsert;
  725. $aModified = array();
  726. foreach($aColumns as $sColumn => $ColSpec)
  727. {
  728. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  729. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  730. }
  731. $sIsModified = '('.implode(') OR (', $aModified).')';
  732. // Update the replica
  733. //
  734. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  735. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  736. // otherwise, the status is left as is
  737. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON `$sTable`";
  738. $sTriggerUpdate .= " FOR EACH ROW";
  739. $sTriggerUpdate .= " BEGIN";
  740. $sTriggerUpdate .= " IF @itopuser is null THEN";
  741. $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;";
  742. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  743. $sTriggerUpdate .= " END IF;";
  744. $sTriggerUpdate .= " END;";
  745. $aResult['bu'] = $sTriggerUpdate;
  746. $sTriggerDelete = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON `$sTable`";
  747. $sTriggerDelete .= " FOR EACH ROW";
  748. $sTriggerDelete .= " BEGIN";
  749. $sTriggerDelete .= " DELETE FROM `{$sReplicaTable}` WHERE id = OLD.id;";
  750. $sTriggerDelete .= " END;";
  751. $aResult['ad'] = $sTriggerDelete;
  752. return $aResult;
  753. }
  754. protected function AfterDelete()
  755. {
  756. parent::AfterDelete();
  757. $sTable = $this->GetDataTable();
  758. $sDropTable = "DROP TABLE `$sTable`";
  759. CMDBSource::Query($sDropTable);
  760. // TO DO - check that triggers get dropped with the table
  761. }
  762. /**
  763. * Checks if the data source definition is consistent with the schema of the target class
  764. * @param $bDiagnostics boolean True to only diagnose the consistency, false to actually apply some changes
  765. * @param $bVerbose boolean True to get some information in the std output (echo)
  766. * @return bool Whether or not the database needs fixing for this data source
  767. */
  768. public function CheckDBConsistency($bDiagnostics, $bVerbose, $oChange = null)
  769. {
  770. $bFixNeeded = false;
  771. $bTriggerRebuildNeeded = false;
  772. $aMissingFields = array();
  773. $oAttributeSet = $this->Get('attribute_list');
  774. $aAttributes = array();
  775. while($oAttribute = $oAttributeSet->Fetch())
  776. {
  777. $sAttCode = $oAttribute->Get('attcode');
  778. if (MetaModel::IsValidAttCode($this->GetTargetClass(), $sAttCode))
  779. {
  780. $aAttributes[$sAttCode] = $oAttribute;
  781. }
  782. else
  783. {
  784. // Old field remaining
  785. if ($bVerbose)
  786. {
  787. echo "Irrelevant field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be removed.\n";
  788. }
  789. $bFixNeeded = true;
  790. if (!$bDiagnostics)
  791. {
  792. // Fix the issue
  793. $oAttribute->DBDelete();
  794. }
  795. }
  796. }
  797. $sTable = $this->GetDataTable();
  798. foreach($this->ListTargetAttributes() as $sAttCode=>$oAttDef)
  799. {
  800. if (!isset($aAttributes[$sAttCode]))
  801. {
  802. $bFixNeeded = true;
  803. $aMissingFields[] = $sAttCode;
  804. // New field missing...
  805. if ($bVerbose)
  806. {
  807. echo "Missing field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be created with default values.\n";
  808. }
  809. if (!$bDiagnostics)
  810. {
  811. // Fix the issue
  812. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  813. $oAttribute->DBInsert();
  814. }
  815. }
  816. else
  817. {
  818. $aColumns = $this->GetSQLColumns(array($sAttCode));
  819. foreach($aColumns as $sColName => $sColumnDef)
  820. {
  821. $bOneColIsMissing = false;
  822. if (!CMDBSource::IsField($sTable, $sColName))
  823. {
  824. $bFixNeeded = true;
  825. $bOneColIsMissing = true;
  826. if ($bVerbose)
  827. {
  828. if (count($aColumns) > 1)
  829. {
  830. 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";
  831. }
  832. else
  833. {
  834. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  835. }
  836. }
  837. }
  838. else if (strcasecmp(CMDBSource::GetFieldType($sTable, $sColName), $sColumnDef) != 0)
  839. {
  840. $bFixNeeded = true;
  841. $bOneColIsMissing = true;
  842. if (count($aColumns) > 1)
  843. {
  844. 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";
  845. }
  846. else
  847. {
  848. 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";
  849. }
  850. }
  851. if ($bOneColIsMissing)
  852. {
  853. $bTriggerRebuildNeeded = true;
  854. $aMissingFields[] = $sAttCode;
  855. }
  856. }
  857. }
  858. }
  859. $sDBName = MetaModel::GetConfig()->GetDBName();
  860. try
  861. {
  862. // Note: as per the MySQL documentation, using information_schema behaves exactly like SHOW TRIGGERS (user privileges)
  863. // and this is in fact the recommended way for better portability
  864. $iTriggerCount = CMDBSource::QueryToScalar("select count(*) from information_schema.triggers where EVENT_OBJECT_SCHEMA='$sDBName' and EVENT_OBJECT_TABLE='$sTable'");
  865. }
  866. catch (Exception $e)
  867. {
  868. if ($bVerbose)
  869. {
  870. echo "Failed to investigate on the synchro triggers (skipping the check): ".$e->getMessage().".\n";
  871. }
  872. // Ignore this error: consider that the trigger are there
  873. $iTriggerCount = 3;
  874. }
  875. if ($iTriggerCount < 3)
  876. {
  877. $bFixNeeded = true;
  878. $bTriggerRebuildNeeded = true;
  879. if ($bVerbose)
  880. {
  881. echo "Missing trigger(s) for the data synchro task ".$this->GetName()." (table {$sTable}).\n";
  882. }
  883. }
  884. $aRepairQueries = array();
  885. if (count($aMissingFields) > 0)
  886. {
  887. // The structure of the table needs adjusting
  888. $aColumns = $this->GetSQLColumns($aMissingFields);
  889. $aFieldDefs = array();
  890. foreach($aColumns as $sAttCode => $sColumnDef)
  891. {
  892. if (CMDBSource::IsField($sTable, $sAttCode))
  893. {
  894. $aRepairQueries[] = "ALTER TABLE `$sTable` CHANGE `$sAttCode` `$sAttCode` $sColumnDef";
  895. }
  896. else
  897. {
  898. $aFieldDefs[] = "`$sAttCode` $sColumnDef";
  899. }
  900. }
  901. if (count($aFieldDefs) > 0)
  902. {
  903. $aRepairQueries[] = "ALTER TABLE `$sTable` ADD (".implode(',', $aFieldDefs).");";
  904. }
  905. if ($bDiagnostics)
  906. {
  907. if ($bVerbose)
  908. {
  909. 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";
  910. }
  911. }
  912. }
  913. // Repair the triggers
  914. // Must be done after updating the columns because MySQL does check the validity of the query found into the procedure!
  915. if ($bTriggerRebuildNeeded)
  916. {
  917. // The triggers as well must be adjusted
  918. $aTriggersDefs = $this->GetTriggersDefinition();
  919. $aTriggerRepair = array();
  920. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bi`;";
  921. $aTriggerRepair[] = $aTriggersDefs['bi'];
  922. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bu`;";
  923. $aTriggerRepair[] = $aTriggersDefs['bu'];
  924. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_ad`;";
  925. $aTriggerRepair[] = $aTriggersDefs['ad'];
  926. if ($bDiagnostics)
  927. {
  928. if ($bVerbose)
  929. {
  930. echo "The triggers {$sTable}_bi, {$sTable}_bu, {$sTable}_ad for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be re-created.\n";
  931. echo implode("\n", $aTriggerRepair)."\n";
  932. }
  933. }
  934. $aRepairQueries = array_merge($aRepairQueries, $aTriggerRepair); // The order matters!
  935. }
  936. // Execute the repair statements
  937. //
  938. if (!$bDiagnostics && (count($aRepairQueries) > 0))
  939. {
  940. // Fix the issue
  941. foreach($aRepairQueries as $sSQL)
  942. {
  943. CMDBSource::Query($sSQL);
  944. if ($bVerbose)
  945. {
  946. echo "$sSQL\n";
  947. }
  948. }
  949. }
  950. return $bFixNeeded;
  951. }
  952. public function SendNotification($sSubject, $sBody)
  953. {
  954. $iContact = $this->Get('notify_contact_id');
  955. if ($iContact == 0)
  956. {
  957. // Leave silently...
  958. return;
  959. }
  960. $oContact = MetaModel::GetObject('Contact', $iContact);
  961. // Determine the email attribute (the first one will be our choice)
  962. $sEmailAttCode = null;
  963. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  964. {
  965. if ($oAttDef instanceof AttributeEmailAddress)
  966. {
  967. $sEmailAttCode = $sAttCode;
  968. // we've got one, exit the loop
  969. break;
  970. }
  971. }
  972. if (is_null($sEmailAttCode))
  973. {
  974. // Leave silently...
  975. return;
  976. }
  977. $sTo = $oContact->Get($sEmailAttCode);
  978. $sFrom = $sTo;
  979. $sBody = '<p>Data synchronization: '.$this->GetHyperlink().'</p>'.$sBody;
  980. $sSubject = 'iTop Data Sync - '.$this->GetName().' - '.$sSubject;
  981. $oEmail = new Email();
  982. $oEmail->SetRecipientTO($sTo);
  983. $oEmail->SetRecipientFrom($sFrom);
  984. $oEmail->SetSubject($sSubject);
  985. $oEmail->SetBody($sBody);
  986. if ($oEmail->Send($aIssues) == EMAIL_SEND_ERROR)
  987. {
  988. // mmmm, what can I do?
  989. }
  990. }
  991. /**
  992. * Get the list of attributes eligible to the synchronization
  993. */
  994. public function ListTargetAttributes()
  995. {
  996. $aRet = array();
  997. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode => $oAttDef)
  998. {
  999. if ($sAttCode == 'finalclass') continue;
  1000. if (!$oAttDef->IsWritable()) continue;
  1001. if ($oAttDef->IsLinkSet() && !$oAttDef->IsIndirect()) continue;
  1002. $aRet[$sAttCode] = $oAttDef;
  1003. }
  1004. return $aRet;
  1005. }
  1006. /**
  1007. * Get the list of SQL columns corresponding to a particular list of attribute codes
  1008. * Defaults to the whole list of columns for the current class
  1009. */
  1010. public function GetSQLColumns($aAttributeCodes = null)
  1011. {
  1012. $aColumns = array();
  1013. $sClass = $this->GetTargetClass();
  1014. if (is_null($aAttributeCodes))
  1015. {
  1016. $aAttributeCodes = array();
  1017. foreach($this->ListTargetAttributes() as $sAttCode => $oAttDef)
  1018. {
  1019. $aAttributeCodes[] = $sAttCode;
  1020. }
  1021. }
  1022. foreach($aAttributeCodes as $sAttCode)
  1023. {
  1024. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1025. if ($oAttDef->IsExternalKey())
  1026. {
  1027. // The pkey might be used as well as any other key column
  1028. $aColumns[$sAttCode] = 'VARCHAR(255)';
  1029. }
  1030. else
  1031. {
  1032. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  1033. {
  1034. $aColumns[$sField] = $sDBFieldType;
  1035. }
  1036. }
  1037. }
  1038. return $aColumns;
  1039. }
  1040. /**
  1041. * Get the list of Date and Datetime SQL columns
  1042. */
  1043. public function GetDateSQLColumns()
  1044. {
  1045. $aDateAttributes = array();
  1046. $sClass = $this->GetTargetClass();
  1047. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1048. {
  1049. if ($oAttDef instanceof AttributeDateTime)
  1050. {
  1051. $aDateAttributes[] = $sAttCode;
  1052. }
  1053. }
  1054. return $this->GetSQLColumns($aDateAttributes);
  1055. }
  1056. public function IsRunning()
  1057. {
  1058. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  1059. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1060. if ($oSet->Count() < 1)
  1061. {
  1062. $bRet = false;
  1063. }
  1064. else
  1065. {
  1066. $bRet = true;
  1067. }
  1068. return $bRet;
  1069. }
  1070. public function GetLatestLog()
  1071. {
  1072. $oLog = null;
  1073. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  1074. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1075. if ($oSet->Count() >= 1)
  1076. {
  1077. $oLog = $oSet->Fetch();
  1078. }
  1079. return $oLog;
  1080. }
  1081. // TO DO: remove if still unused
  1082. /**
  1083. * Retrieve from the log, the date of the last completed import
  1084. * @return DateTime
  1085. */
  1086. public function GetLastCompletedImportDate()
  1087. {
  1088. $date = null;
  1089. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  1090. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  1091. if ($oSet->Count() >= 1)
  1092. {
  1093. $oLog = $oSet->Fetch();
  1094. $date = $oLog->Get('end_date');
  1095. }
  1096. return $date;
  1097. }
  1098. }
  1099. class SynchroAttribute extends cmdbAbstractObject
  1100. {
  1101. public static function Init()
  1102. {
  1103. $aParams = array
  1104. (
  1105. "category" => "core/cmdb,view_in_gui",
  1106. "key_type" => "autoincrement",
  1107. "name_attcode" => "attcode",
  1108. "state_attcode" => "",
  1109. "reconc_keys" => array(),
  1110. "db_table" => "priv_sync_att",
  1111. "db_key_field" => "id",
  1112. "db_finalclass_field" => "",
  1113. "display_template" => "",
  1114. );
  1115. MetaModel::Init_Params($aParams);
  1116. MetaModel::Init_InheritAttributes();
  1117. 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())));
  1118. MetaModel::Init_AddAttribute(new AttributeExternalField("sync_source_name", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"name")));
  1119. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  1120. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  1121. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  1122. 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())));
  1123. // Display lists
  1124. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  1125. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1126. // Search criteria
  1127. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1128. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1129. }
  1130. }
  1131. class SynchroAttExtKey extends SynchroAttribute
  1132. {
  1133. public static function Init()
  1134. {
  1135. $aParams = array
  1136. (
  1137. "category" => "core/cmdb,view_in_gui",
  1138. "key_type" => "autoincrement",
  1139. "name_attcode" => "attcode",
  1140. "state_attcode" => "",
  1141. "reconc_keys" => array(),
  1142. "db_table" => "priv_sync_att_extkey",
  1143. "db_key_field" => "id",
  1144. "db_finalclass_field" => "",
  1145. "display_template" => "",
  1146. );
  1147. MetaModel::Init_Params($aParams);
  1148. MetaModel::Init_InheritAttributes();
  1149. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1150. // Display lists
  1151. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  1152. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1153. // Search criteria
  1154. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1155. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1156. }
  1157. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  1158. {
  1159. $sHtml = "<select name=\"$sFieldName\">\n";
  1160. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1161. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  1162. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1163. {
  1164. if ($oAttDef->IsScalar())
  1165. {
  1166. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1167. $sHtml .= "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  1168. }
  1169. }
  1170. $sHtml .= "</select>\n";
  1171. return $sHtml;
  1172. }
  1173. }
  1174. class SynchroAttLinkSet extends SynchroAttribute
  1175. {
  1176. public static function Init()
  1177. {
  1178. $aParams = array
  1179. (
  1180. "category" => "core/cmdb,view_in_gui",
  1181. "key_type" => "autoincrement",
  1182. "name_attcode" => "attcode",
  1183. "state_attcode" => "",
  1184. "reconc_keys" => array(),
  1185. "db_table" => "priv_sync_att_linkset",
  1186. "db_key_field" => "id",
  1187. "db_finalclass_field" => "",
  1188. "display_template" => "",
  1189. );
  1190. MetaModel::Init_Params($aParams);
  1191. MetaModel::Init_InheritAttributes();
  1192. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1193. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1194. MetaModel::Init_AddAttribute(new AttributeString("value_separator", array("allowed_values"=>null, "sql"=>"value_separator", "default_value"=>':', "is_null_allowed"=>true, "depends_on"=>array())));
  1195. MetaModel::Init_AddAttribute(new AttributeString("attribute_qualifier", array("allowed_values"=>null, "sql"=>"attribute_qualifier", "default_value"=>'\'', "is_null_allowed"=>true, "depends_on"=>array())));
  1196. // Display lists
  1197. 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
  1198. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1199. // Search criteria
  1200. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1201. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1202. }
  1203. }
  1204. //class SynchroLog extends Event
  1205. class SynchroLog extends DBObject
  1206. {
  1207. public static function Init()
  1208. {
  1209. $aParams = array
  1210. (
  1211. "category" => "core/cmdb,view_in_gui",
  1212. "key_type" => "autoincrement",
  1213. "name_attcode" => "",
  1214. "state_attcode" => "",
  1215. "reconc_keys" => array(),
  1216. "db_table" => "priv_sync_log",
  1217. "db_key_field" => "id",
  1218. "db_finalclass_field" => "",
  1219. "display_template" => "",
  1220. );
  1221. MetaModel::Init_Params($aParams);
  1222. MetaModel::Init_InheritAttributes();
  1223. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1224. 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())));
  1225. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1226. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1227. 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())));
  1228. 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())));
  1229. 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())));
  1230. 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())));
  1231. 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())));
  1232. 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())));
  1233. 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())));
  1234. 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())));
  1235. 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())));
  1236. 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())));
  1237. 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())));
  1238. 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())));
  1239. 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())));
  1240. 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())));
  1241. 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())));
  1242. 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())));
  1243. // 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())));
  1244. 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())));
  1245. 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())));
  1246. 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())));
  1247. 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())));
  1248. 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())));
  1249. 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())));
  1250. MetaModel::Init_AddAttribute(new AttributeText("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1251. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1252. 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())));
  1253. // Display lists
  1254. 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',
  1255. '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
  1256. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1257. // Search criteria
  1258. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1259. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1260. }
  1261. /**
  1262. * Helper
  1263. */
  1264. function GetErrorCount()
  1265. {
  1266. return $this->Get('stats_nb_obj_deleted_errors')
  1267. + $this->Get('stats_nb_obj_obsoleted_errors')
  1268. + $this->Get('stats_nb_obj_created_errors')
  1269. + $this->Get('stats_nb_obj_updated_errors')
  1270. + $this->Get('stats_nb_replica_reconciled_errors');
  1271. }
  1272. /**
  1273. * Increments a statistics counter
  1274. */
  1275. function Inc($sCode)
  1276. {
  1277. $this->Set($sCode, 1+$this->Get($sCode));
  1278. }
  1279. /**
  1280. * Implement traces management
  1281. */
  1282. protected $m_aTraces = array();
  1283. public function AddTrace($sMsg, $oReplica = null)
  1284. {
  1285. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1286. {
  1287. return;
  1288. }
  1289. if ($oReplica)
  1290. {
  1291. $sDestClass = $oReplica->Get('dest_class');
  1292. if (!empty($sDestClass))
  1293. {
  1294. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1295. }
  1296. else
  1297. {
  1298. $sPrefix = $oReplica->GetKey().',,';
  1299. }
  1300. }
  1301. else
  1302. {
  1303. $sPrefix = ',,';
  1304. }
  1305. $this->m_aTraces[] = $sPrefix.$sMsg;
  1306. }
  1307. public function GetTraces()
  1308. {
  1309. return $this->m_aTraces;
  1310. }
  1311. protected function TraceToText()
  1312. {
  1313. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1314. {
  1315. // none, or display only
  1316. return;
  1317. }
  1318. $sPrevTrace = $this->Get('traces');
  1319. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1320. $iMaxSize = $oAttDef->GetMaxSize();
  1321. if (strlen($sPrevTrace) > 0)
  1322. {
  1323. $sTrace = $sPrevTrace."\n".implode("\n", $this->m_aTraces);
  1324. }
  1325. else
  1326. {
  1327. $sTrace = implode("\n", $this->m_aTraces);
  1328. }
  1329. if (strlen($sTrace) >= $iMaxSize)
  1330. {
  1331. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1332. }
  1333. $this->Set('traces', $sTrace);
  1334. //DBUpdate may be called many times... the operation should not be repeated
  1335. $this->m_aTraces = array();
  1336. }
  1337. protected function OnInsert()
  1338. {
  1339. $this->TraceToText();
  1340. parent::OnInsert();
  1341. }
  1342. protected function OnUpdate()
  1343. {
  1344. $this->TraceToText();
  1345. $sMemPeak = max($this->Get('memory_usage_peak'), ExecutionKPI::memory_get_peak_usage());
  1346. $this->Set('memory_usage_peak', $sMemPeak);
  1347. parent::OnUpdate();
  1348. }
  1349. }
  1350. class SynchroReplica extends DBObject implements iDisplay
  1351. {
  1352. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1353. protected $aWarnings;
  1354. public static function Init()
  1355. {
  1356. $aParams = array
  1357. (
  1358. "category" => "core/cmdb,view_in_gui",
  1359. "key_type" => "autoincrement",
  1360. "name_attcode" => "",
  1361. "state_attcode" => "",
  1362. "reconc_keys" => array(),
  1363. "db_table" => "priv_sync_replica",
  1364. "db_key_field" => "id",
  1365. "db_finalclass_field" => "",
  1366. "display_template" => "",
  1367. );
  1368. MetaModel::Init_Params($aParams);
  1369. MetaModel::Init_InheritAttributes();
  1370. 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())));
  1371. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1372. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1373. 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())));
  1374. 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())));
  1375. 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())));
  1376. 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())));
  1377. 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())));
  1378. 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())));
  1379. 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())));
  1380. 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())));
  1381. // Display lists
  1382. MetaModel::Init_SetZListItems('details', array('' .
  1383. 'col:0'=> array(
  1384. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1385. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error','status_last_warning'),
  1386. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1387. )
  1388. );
  1389. 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
  1390. // Search criteria
  1391. 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
  1392. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1393. }
  1394. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  1395. {
  1396. parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  1397. $this->aWarnings = array();
  1398. }
  1399. protected function AddWarning($sWarningMessage)
  1400. {
  1401. $this->aWarnings[] = $sWarningMessage;
  1402. }
  1403. protected function ResetWarnings()
  1404. {
  1405. $this->aWarnings = array();
  1406. }
  1407. protected function HasWarnings()
  1408. {
  1409. return (count($this->aWarnings) > 0);
  1410. }
  1411. protected function RecordWarnings()
  1412. {
  1413. $sWarningMessage = '';
  1414. $MAX_WARNING_LENGTH = 255;
  1415. switch(count($this->aWarnings))
  1416. {
  1417. case 0:
  1418. $sWarningMessage = '';
  1419. break;
  1420. case 1:
  1421. $sWarningMessage = $this->aWarnings[0];
  1422. break;
  1423. default:
  1424. $sWarningMessage = count($this->aWarnings)." warnings: ".implode(' ', $this->aWarnings);
  1425. break;
  1426. }
  1427. if (strlen($sWarningMessage) > $MAX_WARNING_LENGTH)
  1428. {
  1429. $sWarningMessage = substr($sWarningMessage, 0, $MAX_WARNING_LENGTH - 3).'...';
  1430. }
  1431. $this->Set('status_last_warning', $sWarningMessage);
  1432. }
  1433. public function DBInsert()
  1434. {
  1435. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1436. }
  1437. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1438. // it will be deleted by the mean of a trigger too
  1439. protected function DBDeleteSingleObject()
  1440. {
  1441. $this->OnDelete();
  1442. if (!MetaModel::DBIsReadOnly())
  1443. {
  1444. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'), false);
  1445. if ($oDataSource)
  1446. {
  1447. $sTable = $oDataSource->GetDataTable();
  1448. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1449. CMDBSource::Query($sSQL);
  1450. }
  1451. // else the whole datasource has probably been already deleted
  1452. }
  1453. $this->AfterDelete();
  1454. $this->m_bIsInDB = false;
  1455. $this->m_iKey = null;
  1456. }
  1457. public function SetLastError($sMessage, $oException = null)
  1458. {
  1459. if ($oException)
  1460. {
  1461. $sText = $sMessage.$oException->getMessage();
  1462. }
  1463. else
  1464. {
  1465. $sText = $sMessage;
  1466. }
  1467. if (strlen($sText) > 255)
  1468. {
  1469. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1470. }
  1471. $this->Set('status_last_error', $sText);
  1472. }
  1473. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1474. {
  1475. $this->ResetWarnings();
  1476. switch($this->Get('status'))
  1477. {
  1478. case 'new':
  1479. $this->Set('status_dest_creator', false);
  1480. // If needed, construct the query used for the reconciliation
  1481. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1482. {
  1483. $aCriterias = array();
  1484. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1485. {
  1486. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1487. }
  1488. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1489. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1490. }
  1491. // Get the criterias for the search
  1492. $aFilterValues = array();
  1493. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1494. {
  1495. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1496. if (!is_null($value))
  1497. {
  1498. $aFilterValues[$sFilterCode] = $value;
  1499. }
  1500. else
  1501. {
  1502. // TO DO: can we retry this ??
  1503. // Reconciliation could not be performed - log and EXIT
  1504. $oStatLog->AddTrace("Could not reconcile on null value for attribute '$sFilterCode'", $this);
  1505. $this->SetLastError("Could not reconcile on null value for attribute '$sFilterCode'");
  1506. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1507. return;
  1508. }
  1509. }
  1510. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1511. $iCount = $oDestSet->Count();
  1512. $aConditions = array();
  1513. foreach($aFilterValues as $sCode => $sValue)
  1514. {
  1515. $aConditions[] = $sCode.'='.$sValue;
  1516. }
  1517. $sConditionDesc = implode(' AND ', $aConditions);
  1518. // How many objects match the reconciliation criterias
  1519. switch($iCount)
  1520. {
  1521. case 0:
  1522. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1523. if ($oDataSource->Get('action_on_zero') == 'create')
  1524. {
  1525. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1526. if ($bCreated)
  1527. {
  1528. if ($this->HasWarnings())
  1529. {
  1530. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1531. }
  1532. }
  1533. else
  1534. {
  1535. // Creation error has precedence over any warning
  1536. $this->ResetWarnings();
  1537. }
  1538. }
  1539. else // assumed to be 'error'
  1540. {
  1541. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1542. // Recoverable error
  1543. $this->SetLastError('Could not find a match for reconciliation');
  1544. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1545. }
  1546. break;
  1547. case 1:
  1548. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1549. if ($oDataSource->Get('action_on_one') == 'update')
  1550. {
  1551. $oDestObj = $oDestSet->Fetch();
  1552. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1553. $this->Set('dest_id', $oDestObj->GetKey());
  1554. $this->Set('dest_class', get_class($oDestObj));
  1555. if ($this->HasWarnings())
  1556. {
  1557. if ($bModified)
  1558. {
  1559. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1560. }
  1561. else
  1562. {
  1563. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1564. }
  1565. }
  1566. }
  1567. else
  1568. {
  1569. // assumed to be 'error'
  1570. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1571. // Recoverable error
  1572. $this->SetLastError('Found a match while expecting several');
  1573. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1574. }
  1575. break;
  1576. default:
  1577. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1578. if ($oDataSource->Get('action_on_multiple') == 'error')
  1579. {
  1580. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1581. // Recoverable error
  1582. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1583. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1584. }
  1585. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1586. {
  1587. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1588. if ($bCreated)
  1589. {
  1590. if ($this->HasWarnings())
  1591. {
  1592. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1593. }
  1594. }
  1595. else
  1596. {
  1597. // Creation error has precedence over any warning
  1598. $this->ResetWarnings();
  1599. }
  1600. }
  1601. else
  1602. {
  1603. // assumed to be 'take_first'
  1604. $oDestObj = $oDestSet->Fetch();
  1605. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1606. $this->Set('dest_id', $oDestObj->GetKey());
  1607. $this->Set('dest_class', get_class($oDestObj));
  1608. if ($this->HasWarnings())
  1609. {
  1610. if ($bModified)
  1611. {
  1612. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1613. }
  1614. else
  1615. {
  1616. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1617. }
  1618. }
  1619. }
  1620. }
  1621. $this->RecordWarnings();
  1622. break;
  1623. case 'synchronized': // try to recover synchronized replicas with warnings
  1624. case 'modified':
  1625. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1626. if ($oDestObj == null)
  1627. {
  1628. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1629. $this->SetLastError('Destination object deleted unexpectedly');
  1630. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1631. }
  1632. else
  1633. {
  1634. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1635. if ($this->HasWarnings())
  1636. {
  1637. if ($bModified)
  1638. {
  1639. $oStatLog->Inc('stats_nb_obj_updated_warnings');
  1640. }
  1641. else
  1642. {
  1643. $oStatLog->Inc('stats_nb_obj_unchanged_warnings');
  1644. }
  1645. }
  1646. }
  1647. $this->RecordWarnings();
  1648. break;
  1649. default: // Do nothing in all other cases
  1650. }
  1651. }
  1652. /**
  1653. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1654. */
  1655. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1656. {
  1657. $aValueTrace = array();
  1658. $bModified = false;
  1659. try
  1660. {
  1661. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1662. {
  1663. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1664. if (!is_null($value))
  1665. {
  1666. if ($oSyncAtt->Get('update_policy') == 'write_if_empty')
  1667. {
  1668. $oAttDef = MetaModel::GetAttributeDef(get_class($oDestObj), $sAttCode);
  1669. if ($oAttDef->IsNull($oDestObj->Get($sAttCode)))
  1670. {
  1671. // The value is still "empty" in the target object, we are allowed to write the new value
  1672. $oDestObj->Set($sAttCode, $value);
  1673. $aValueTrace[] = "$sAttCode: $value";
  1674. }
  1675. }
  1676. else
  1677. {
  1678. $oDestObj->Set($sAttCode, $value);
  1679. $aValueTrace[] = "$sAttCode: $value";
  1680. }
  1681. }
  1682. }
  1683. // Really modified ?
  1684. if ($oDestObj->IsModified())
  1685. {
  1686. $oDestObj->DBUpdateTracked($oChange);
  1687. $bModified = true;
  1688. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1689. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_updated')))
  1690. {
  1691. $oStatLog->Inc($sStatsCode.'_updated');
  1692. }
  1693. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1694. }
  1695. else
  1696. {
  1697. $oStatLog->AddTrace('Unchanged object', $this);
  1698. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_unchanged')))
  1699. {
  1700. $oStatLog->Inc($sStatsCode.'_unchanged');
  1701. }
  1702. }
  1703. $this->Set('status_last_error', '');
  1704. $this->Set('status', 'synchronized');
  1705. }
  1706. catch(Exception $e)
  1707. {
  1708. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1709. $this->SetLastError('Unable to update destination object: ', $e);
  1710. $oStatLog->Inc($sStatsCodeError);
  1711. }
  1712. return $bModified;
  1713. }
  1714. /**
  1715. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1716. * @return bool Whether or not the object was created
  1717. */
  1718. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1719. {
  1720. $bCreated = false;
  1721. $oDestObj = MetaModel::NewObject($sClass);
  1722. try
  1723. {
  1724. $aValueTrace = array();
  1725. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1726. {
  1727. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1728. if (!is_null($value))
  1729. {
  1730. $oDestObj->Set($sAttCode, $value);
  1731. $aValueTrace[] = "$sAttCode: $value";
  1732. }
  1733. }
  1734. $iNew = $oDestObj->DBInsertTracked($oChange);
  1735. $this->Set('dest_id', $oDestObj->GetKey());
  1736. $this->Set('dest_class', get_class($oDestObj));
  1737. $this->Set('status_dest_creator', true);
  1738. $this->Set('status_last_error', '');
  1739. $this->Set('status', 'synchronized');
  1740. $this->Set('info_creation_date', date('Y-m-d H:i:s'));
  1741. $bCreated = true;
  1742. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1743. $oStatLog->Inc('stats_nb_obj_created');
  1744. }
  1745. catch(Exception $e)
  1746. {
  1747. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1748. $this->SetLastError('Unable to create destination object: ', $e);
  1749. $oStatLog->Inc('stats_nb_obj_created_errors');
  1750. }
  1751. return $bCreated;
  1752. }
  1753. /**
  1754. * Update the destination object with given values
  1755. */
  1756. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1757. {
  1758. try
  1759. {
  1760. if ($this->Get('dest_class') == '')
  1761. {
  1762. $this->SetLastError('No destination object to update');
  1763. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1764. }
  1765. else
  1766. {
  1767. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1768. foreach($aValues as $sAttCode => $value)
  1769. {
  1770. if (!MetaModel::IsValidAttCode(get_class($oDestObj), $sAttCode))
  1771. {
  1772. throw new Exception("Unknown attribute code '$sAttCode'");
  1773. }
  1774. $oDestObj->Set($sAttCode, $value);
  1775. }
  1776. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1777. $oDestObj->DBUpdateTracked($oChange);
  1778. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1779. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1780. }
  1781. }
  1782. catch(Exception $e)
  1783. {
  1784. $this->SetLastError('Unable to update the destination object: ', $e);
  1785. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1786. }
  1787. }
  1788. /**
  1789. * Delete the destination object
  1790. */
  1791. public function DeleteDestObject($oChange, &$oStatLog)
  1792. {
  1793. if($this->Get('status_dest_creator'))
  1794. {
  1795. try
  1796. {
  1797. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1798. $oCheckDeletionPlan = new DeletionPlan();
  1799. if ($oDestObj->CheckToDelete($oCheckDeletionPlan))
  1800. {
  1801. $oActualDeletionPlan = new DeletionPlan();
  1802. $oDestObj->DBDeleteTracked($oChange, null, $oActualDeletionPlan);
  1803. $this->DBDeleteTracked($oChange);
  1804. $oStatLog->Inc('stats_nb_obj_deleted');
  1805. }
  1806. else
  1807. {
  1808. $sIssues = implode("\n", $oCheckDeletionPlan->GetIssues());
  1809. throw(new Exception($sIssues));
  1810. }
  1811. }
  1812. catch(Exception $e)
  1813. {
  1814. $this->SetLastError('Unable to delete the destination object: ', $e);
  1815. $this->Set('status', 'obsolete');
  1816. $this->DBUpdateTracked($oChange);
  1817. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1818. }
  1819. }
  1820. else
  1821. {
  1822. $this->DBDeleteTracked($oChange);
  1823. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1824. }
  1825. }
  1826. /**
  1827. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1828. * Note: sExtAttCode could be a standard attcode, or 'primary_key'
  1829. */
  1830. protected function GetValueFromExtData($sExtAttCode, $oSyncAtt, &$oStatLog)
  1831. {
  1832. // $aData should contain attributes defined either for reconciliation or create/update
  1833. $aData = $this->GetExtendedData();
  1834. if ($sExtAttCode == 'primary_key')
  1835. {
  1836. return $aData['primary_key'];
  1837. }
  1838. // $sExtAttCode is a valid attribute code
  1839. //
  1840. $sClass = $this->Get('base_class');
  1841. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExtAttCode);
  1842. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1843. {
  1844. $rawValue = $aData[$sExtAttCode];
  1845. if (is_null($rawValue))
  1846. {
  1847. // Null means "ignore" this attribute
  1848. return null;
  1849. }
  1850. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1851. if (!empty($sReconcAttCode))
  1852. {
  1853. $sRemoteClass = $oAttDef->GetTargetClass();
  1854. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1855. if ($oObj)
  1856. {
  1857. $retValue = $oObj->GetKey();
  1858. }
  1859. else
  1860. {
  1861. if ($rawValue != '')
  1862. {
  1863. // Note: differs from null (in which case the value would be left unchanged)
  1864. $oStatLog->AddTrace("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1865. $this->AddWarning("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'");
  1866. }
  1867. $retValue = 0;
  1868. }
  1869. }
  1870. else
  1871. {
  1872. $retValue = $rawValue;
  1873. }
  1874. }
  1875. elseif (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttLinkSet))
  1876. {
  1877. $rawValue = $aData[$sExtAttCode];
  1878. if (is_null($rawValue))
  1879. {
  1880. // Null means "ignore" this attribute
  1881. return null;
  1882. }
  1883. // MakeValueFromString() throws an exception in case of failure
  1884. $bLocalizedValue = false;
  1885. $retValue = $oAttDef->MakeValueFromString($rawValue, $bLocalizedValue, $oSyncAtt->Get('row_separator'), $oSyncAtt->Get('attribute_separator'), $oSyncAtt->Get('value_separator'), $oSyncAtt->Get('attribute_qualifier'));
  1886. }
  1887. else
  1888. {
  1889. $aColumns = $oAttDef->GetImportColumns();
  1890. foreach($aColumns as $sColumn => $sFormat)
  1891. {
  1892. // In any case, a null column means "ignore this attribute"
  1893. //
  1894. if (is_null($aData[$sColumn]))
  1895. {
  1896. return null;
  1897. }
  1898. }
  1899. $retValue = $oAttDef->FromImportToValue($aData, $sExtAttCode);
  1900. }
  1901. return $retValue;
  1902. }
  1903. /**
  1904. * Maps the given context parameter name to the appropriate filter/search code for this class
  1905. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1906. * @return string Filter code, i.e. 'customer_id'
  1907. */
  1908. public static function MapContextParam($sContextParam)
  1909. {
  1910. if ($sContextParam == 'menu')
  1911. {
  1912. return null;
  1913. }
  1914. else
  1915. {
  1916. return $sContextParam;
  1917. }
  1918. }
  1919. /**
  1920. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1921. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1922. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1923. * To Be overridden by derived classes
  1924. * @param void
  1925. * @return String The desired higlight class for the object/row
  1926. */
  1927. public function GetHilightClass()
  1928. {
  1929. // Possible return values are:
  1930. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1931. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1932. }
  1933. public static function GetUIPage()
  1934. {
  1935. return '../synchro/replica.php';
  1936. }
  1937. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1938. {
  1939. // Object's details
  1940. //$this->DisplayBareHeader($oPage, $bEditMode);
  1941. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1942. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1943. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1944. $this->DisplayBareProperties($oPage, $bEditMode);
  1945. }
  1946. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  1947. {
  1948. if ($bEditMode) return; // Not editable
  1949. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1950. $aDetails = array();
  1951. $sClass = get_class($this);
  1952. $oPage->add('<fieldset>');
  1953. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1954. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1955. foreach( $aZList as $sAttCode)
  1956. {
  1957. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1958. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1959. }
  1960. $oPage->Details($aDetails);
  1961. $oPage->add('</fieldset>');
  1962. if (strlen($this->Get('dest_class')) > 0)
  1963. {
  1964. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'), false);
  1965. if (is_object($oDestObj))
  1966. {
  1967. $oPage->add('<fieldset>');
  1968. $oPage->add('<legend>'.Dict::Format('Core:SynchroReplica:TargetObject', $oDestObj->GetHyperlink()).'</legend>');
  1969. $oDestObj->DisplayBareProperties($oPage, false, $sPrefix, $aExtraParams);
  1970. $oPage->add('<fieldset>');
  1971. }
  1972. }
  1973. $oPage->add('</td><td>');
  1974. $oPage->add('<fieldset>');
  1975. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  1976. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1977. $sSQLTable = $oSource->GetDataTable();
  1978. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  1979. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  1980. 'data' => array('label' => 'Value', 'description' => ''));
  1981. $aRows = array();
  1982. foreach($aData as $sKey => $value)
  1983. {
  1984. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  1985. }
  1986. $oPage->Table($aHeaders, $aRows);
  1987. $oPage->add('</fieldset>');
  1988. $oPage->add('</td></tr></table>');
  1989. }
  1990. public function LoadExtendedDataFromTable($sSQLTable)
  1991. {
  1992. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  1993. $rQuery = CMDBSource::Query($sSQL);
  1994. return CMDBSource::FetchArray($rQuery);
  1995. }
  1996. }
  1997. /**
  1998. * Context of an ongoing synchronization
  1999. * Two usages:
  2000. * 1) Public usage: execute the synchronization
  2001. * $oSynchroExec = new SynchroExecution($oDataSource[, $iLastFullLoad]);
  2002. * $oSynchroExec->Process($iMaxChunkSize);
  2003. *
  2004. * 2) Internal usage: continue the synchronization (split into chunks, each performed in a separate process)
  2005. * This is implemented in the page priv_sync_chunk.php
  2006. * $oSynchroExec = SynchroExecution::Resume($oDataSource, $iLastFullLoad, $iSynchroLog, $iChange, $iMaxToProcess, $iJob, $iNextInJob);
  2007. * $oSynchroExec->Process()
  2008. */
  2009. class SynchroExecution
  2010. {
  2011. protected $m_oDataSource = null;
  2012. protected $m_oLastFullLoadStartDate = null;
  2013. protected $m_oChange = null;
  2014. protected $m_oStatLog = null;
  2015. // Context computed one for optimization and report inconsistencies ASAP
  2016. protected $m_aExtDataSpec = array();
  2017. protected $m_aReconciliationKeys = array();
  2018. protected $m_aAttributes = array();
  2019. protected $m_iCountAllReplicas = 0;
  2020. /**
  2021. * Constructor
  2022. * @param SynchroDataSource $oDataSource Synchronization task
  2023. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  2024. * @return void
  2025. */
  2026. public function __construct($oDataSource, $oLastFullLoadStartDate = null)
  2027. {
  2028. $this->m_oDataSource = $oDataSource;
  2029. $this->m_oLastFullLoadStartDate = $oLastFullLoadStartDate;
  2030. }
  2031. /**
  2032. * Create the persistant information records, for the current synchronization
  2033. * In fact, those records ARE defining what is the "current" synchronization
  2034. */
  2035. protected function PrepareLogs()
  2036. {
  2037. if (!is_null($this->m_oChange))
  2038. {
  2039. return;
  2040. }
  2041. // Create a change used for logging all the modifications/creations happening during the synchro
  2042. $this->m_oChange = MetaModel::NewObject("CMDBChange");
  2043. $this->m_oChange->Set("date", time());
  2044. $sUserString = CMDBChange::GetCurrentUserName();
  2045. $this->m_oChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  2046. $this->m_oChange->Set("origin", 'synchro-data-source');
  2047. $iChangeId = $this->m_oChange->DBInsert();
  2048. // Start logging this execution (stats + protection against reentrance)
  2049. //
  2050. $this->m_oStatLog = new SynchroLog();
  2051. $this->m_oStatLog->Set('sync_source_id', $this->m_oDataSource->GetKey());
  2052. $this->m_oStatLog->Set('start_date', time());
  2053. $this->m_oStatLog->Set('status', 'running');
  2054. $this->m_oStatLog->Set('stats_nb_replica_seen', 0);
  2055. $this->m_oStatLog->Set('stats_nb_replica_total', 0);
  2056. $this->m_oStatLog->Set('stats_nb_obj_deleted', 0);
  2057. $this->m_oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  2058. $this->m_oStatLog->Set('stats_nb_obj_obsoleted', 0);
  2059. $this->m_oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  2060. $this->m_oStatLog->Set('stats_nb_obj_created', 0);
  2061. $this->m_oStatLog->Set('stats_nb_obj_created_errors', 0);
  2062. $this->m_oStatLog->Set('stats_nb_obj_created_warnings', 0);
  2063. $this->m_oStatLog->Set('stats_nb_obj_updated', 0);
  2064. $this->m_oStatLog->Set('stats_nb_obj_updated_warnings', 0);
  2065. $this->m_oStatLog->Set('stats_nb_obj_updated_errors', 0);
  2066. $this->m_oStatLog->Set('stats_nb_obj_unchanged_warnings', 0);
  2067. // $this->m_oStatLog->Set('stats_nb_replica_reconciled', 0);
  2068. $this->m_oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  2069. $this->m_oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  2070. $this->m_oStatLog->Set('stats_nb_obj_new_updated', 0);
  2071. $this->m_oStatLog->Set('stats_nb_obj_new_updated_warnings', 0);
  2072. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged',0);
  2073. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged_warnings',0);
  2074. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  2075. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()));
  2076. $this->m_iCountAllReplicas = $oSetTotal->Count();
  2077. $this->m_oStatLog->Set('stats_nb_replica_total', $this->m_iCountAllReplicas);
  2078. $this->m_oStatLog->DBInsertTracked($this->m_oChange);
  2079. }
  2080. /**
  2081. * Prevent against the reentrance... or allow the current task to do things forbidden by the others !
  2082. */
  2083. public static $m_oCurrentTask = null;
  2084. public static function GetCurrentTaskId()
  2085. {
  2086. if (is_object(self::$m_oCurrentTask))
  2087. {
  2088. return self::$m_oCurrentTask->GetKey();
  2089. }
  2090. else
  2091. {
  2092. return null;
  2093. }
  2094. }
  2095. /**
  2096. * Prepare structures in memory, to speedup the processing of a given replica
  2097. */
  2098. public function PrepareProcessing($bFirstPass = true)
  2099. {
  2100. if ($this->m_oDataSource->Get('status') == 'obsolete')
  2101. {
  2102. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  2103. }
  2104. if (!UserRights::IsAdministrator() && $this->m_oDataSource->Get('user_id') != UserRights::GetUserId())
  2105. {
  2106. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  2107. }
  2108. // Get the list of SQL columns
  2109. $sClass = $this->m_oDataSource->GetTargetClass();
  2110. $aAttCodesExpected = array();
  2111. $aAttCodesToReconcile = array();
  2112. $aAttCodesToUpdate = array();
  2113. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  2114. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()) /* aArgs */);
  2115. while ($oSyncAtt = $oSetAtt->Fetch())
  2116. {
  2117. if ($oSyncAtt->Get('update'))
  2118. {
  2119. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2120. }
  2121. if ($oSyncAtt->Get('reconcile'))
  2122. {
  2123. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2124. }
  2125. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2126. }
  2127. $aColumns = $this->m_oDataSource->GetSQLColumns(array_keys($aAttCodesExpected));
  2128. $aExtDataFields = array_keys($aColumns);
  2129. $aExtDataFields[] = 'primary_key';
  2130. $this->m_aExtDataSpec = array(
  2131. 'table' => $this->m_oDataSource->GetDataTable(),
  2132. 'join_key' => 'id',
  2133. 'fields' => $aExtDataFields
  2134. );
  2135. // Get the list of attributes, determine reconciliation keys and update targets
  2136. //
  2137. if ($this->m_oDataSource->Get('reconciliation_policy') == 'use_attributes')
  2138. {
  2139. $this->m_aReconciliationKeys = $aAttCodesToReconcile;
  2140. }
  2141. elseif ($this->m_oDataSource->Get('reconciliation_policy') == 'use_primary_key')
  2142. {
  2143. // Override the settings made at the attribute level !
  2144. $this->m_aReconciliationKeys = array("primary_key" => null);
  2145. }
  2146. if ($bFirstPass)
  2147. {
  2148. $this->m_oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  2149. $this->m_oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($this->m_aReconciliationKeys))."}");
  2150. }
  2151. if (count($aAttCodesToUpdate) == 0)
  2152. {
  2153. $this->m_oStatLog->AddTrace("No attribute to update");
  2154. throw new SynchroExceptionNotStarted('There is no attribute to update');
  2155. }
  2156. if (count($this->m_aReconciliationKeys) == 0)
  2157. {
  2158. $this->m_oStatLog->AddTrace("No attribute for reconciliation");
  2159. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  2160. }
  2161. $this->m_aAttributes = array();
  2162. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  2163. {
  2164. $oAttDef = MetaModel::GetAttributeDef($this->m_oDataSource->GetTargetClass(), $sAttCode);
  2165. if ($oAttDef->IsWritable())
  2166. {
  2167. $this->m_aAttributes[$sAttCode] = $oSyncAtt;
  2168. }
  2169. }
  2170. // Compute and keep track of the limit date taken into account for obsoleting replicas
  2171. //
  2172. if ($this->m_oLastFullLoadStartDate == null)
  2173. {
  2174. // No previous import known, use the full_load_periodicity value... and the current date
  2175. $this->m_oLastFullLoadStartDate = new DateTime(); // Now
  2176. $iLoadPeriodicity = $this->m_oDataSource->Get('full_load_periodicity'); // Duration in seconds
  2177. if ($iLoadPeriodicity > 0)
  2178. {
  2179. $sInterval = "-$iLoadPeriodicity seconds";
  2180. $this->m_oLastFullLoadStartDate->Modify($sInterval);
  2181. }
  2182. else
  2183. {
  2184. $this->m_oLastFullLoadStartDate = new DateTime('1970-01-01');
  2185. }
  2186. }
  2187. if ($bFirstPass)
  2188. {
  2189. $this->m_oStatLog->AddTrace("Limit Date: ".$this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'));
  2190. }
  2191. }
  2192. /**
  2193. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  2194. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  2195. * is used to determine which records are obsolete.
  2196. * @return void
  2197. */
  2198. public function Process()
  2199. {
  2200. $this->PrepareLogs();
  2201. self::$m_oCurrentTask = $this->m_oDataSource;
  2202. try
  2203. {
  2204. $this->DoSynchronize();
  2205. $this->m_oStatLog->Set('end_date', time());
  2206. $this->m_oStatLog->Set('status', 'completed');
  2207. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2208. $iErrors = $this->m_oStatLog->GetErrorCount();
  2209. if ($iErrors > 0)
  2210. {
  2211. $sIssuesOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->m_oDataSource->GetKey()." AND status_last_error!=''";
  2212. $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
  2213. $sIssuesURL = "{$sAbsoluteUrl}synchro/replica.php?operation=oql&datasource=".$this->m_oDataSource->GetKey()."&oql=".urlencode($sIssuesOQL);
  2214. $sSeeIssues = "<p></p>";
  2215. $sStatistics = "<h1>Statistics</h1>\n";
  2216. $sStatistics .= "<ul>\n";
  2217. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('start_date').": ".$this->m_oStatLog->Get('start_date')."</li>\n";
  2218. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('end_date').": ".$this->m_oStatLog->Get('end_date')."</li>\n";
  2219. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_seen').": ".$this->m_oStatLog->Get('stats_nb_replica_seen')."</li>\n";
  2220. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_total').": ".$this->m_oStatLog->Get('stats_nb_replica_total')."</li>\n";
  2221. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted')."</li>\n";
  2222. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted_errors')."</li>\n";
  2223. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted')."</li>\n";
  2224. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted_errors')."</li>\n";
  2225. $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";
  2226. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_created_errors')."</li>\n";
  2227. $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";
  2228. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_updated_errors')."</li>\n";
  2229. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_reconciled_errors').": ".$this->m_oStatLog->Get('stats_nb_replica_reconciled_errors')."</li>\n";
  2230. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_disappeared_no_action').": ".$this->m_oStatLog->Get('stats_nb_replica_disappeared_no_action')."</li>\n";
  2231. $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";
  2232. $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";
  2233. $sStatistics .= "</ul>\n";
  2234. $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);
  2235. }
  2236. else
  2237. {
  2238. //$this->m_oDataSource->SendNotification('success', '<p>The synchronization has been successfully executed.</p>');
  2239. }
  2240. }
  2241. catch (SynchroExceptionNotStarted $e)
  2242. {
  2243. // Set information for reporting... but delete the object in DB
  2244. $this->m_oStatLog->Set('end_date', time());
  2245. $this->m_oStatLog->Set('status', 'error');
  2246. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2247. $this->m_oStatLog->DBDeleteTracked($this->m_oChange);
  2248. $this->m_oDataSource->SendNotification('fatal error', '<p>The synchronization could not start: \''.$e->getMessage().'\'</p><p>Please check its configuration</p>');
  2249. }
  2250. catch (Exception $e)
  2251. {
  2252. $this->m_oStatLog->Set('end_date', time());
  2253. $this->m_oStatLog->Set('status', 'error');
  2254. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2255. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2256. $this->m_oDataSource->SendNotification('exception', '<p>The synchronization has been interrupted: \''.$e->getMessage().'\'</p><p>Please contact the application support team</p>');
  2257. }
  2258. self::$m_oCurrentTask = null;
  2259. return $this->m_oStatLog;
  2260. }
  2261. /**
  2262. * Do the entire synchronization job
  2263. */
  2264. protected function DoSynchronize()
  2265. {
  2266. $this->m_oStatLog->Set('status_curr_job', 1);
  2267. $this->m_oStatLog->Set('status_curr_pos', -1);
  2268. $iMaxChunkSize = utils::ReadParam('max_chunk_size', 0, true /* allow CLI */);
  2269. if ($iMaxChunkSize > 0)
  2270. {
  2271. // Split the execution into several processes
  2272. // Each process will call DoSynchronizeChunk()
  2273. // The loop will end when a process does not reply "continue" on the last line of its output
  2274. if (!utils::IsModeCLI())
  2275. {
  2276. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncSplitModeCLIOnly'));
  2277. }
  2278. $aArguments = array();
  2279. $aArguments['source'] = $this->m_oDataSource->GetKey();
  2280. $aArguments['log'] = $this->m_oStatLog->GetKey();
  2281. $aArguments['change'] = $this->m_oChange->GetKey();
  2282. $aArguments['chunk'] = $iMaxChunkSize;
  2283. if ($this->m_oLastFullLoadStartDate)
  2284. {
  2285. $aArguments['last_full_load'] = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2286. }
  2287. else
  2288. {
  2289. $aArguments['last_full_load'] = '';
  2290. }
  2291. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2292. $iStepCount = 0;
  2293. do
  2294. {
  2295. $aArguments['step_count'] = $iStepCount;
  2296. $iStepCount++;
  2297. list ($iRes, $aOut) = utils::ExecITopScript('synchro/priv_sync_chunk.php', $aArguments);
  2298. // Reload the log that has been modified by the processes
  2299. $this->m_oStatLog->Reload();
  2300. $sLastRes = strtolower(trim(end($aOut)));
  2301. switch($sLastRes)
  2302. {
  2303. case 'continue':
  2304. $bContinue = true;
  2305. break;
  2306. case 'finished':
  2307. $bContinue = false;
  2308. break;
  2309. default:
  2310. $this->m_oStatLog->AddTrace("The script did not reply with the expected keywords:");
  2311. $aIndentedOut = array();
  2312. foreach ($aOut as $sOut)
  2313. {
  2314. $aIndentedOut[] = "-> $sOut";
  2315. $this->m_oStatLog->AddTrace(">>> $sOut");
  2316. }
  2317. throw new Exception("Encountered an error in an underspinned process:\n".implode("\n", $aIndentedOut));
  2318. }
  2319. }
  2320. while ($bContinue);
  2321. }
  2322. else
  2323. {
  2324. $this->PrepareProcessing(/* first pass */);
  2325. $this->DoJob1();
  2326. $this->DoJob2();
  2327. $this->DoJob3();
  2328. }
  2329. }
  2330. /**
  2331. * Do the synchronization job, limited to some amount of work
  2332. * This verb has been designed to be called from within a separate process
  2333. * @return true if the process has to be continued
  2334. */
  2335. public function DoSynchronizeChunk($oLog, $oChange, $iMaxChunkSize)
  2336. {
  2337. // Initialize the structures...
  2338. self::$m_oCurrentTask = $this->m_oDataSource;
  2339. $this->m_oStatLog = $oLog;
  2340. $this->m_oChange = $oChange;
  2341. // Prepare internal structures (not the first pass)
  2342. $this->PrepareProcessing(false);
  2343. $iCurrJob = $this->m_oStatLog->Get('status_curr_job');
  2344. $iCurrPos = $this->m_oStatLog->Get('status_curr_pos');
  2345. $this->m_oStatLog->AddTrace("Synchronizing chunk - curr_job:$iCurrJob, curr_pos:$iCurrPos, max_chunk_size:$iMaxChunkSize");
  2346. $bContinue = false;
  2347. switch ($iCurrJob)
  2348. {
  2349. case 1:
  2350. default:
  2351. $this->DoJob1($iMaxChunkSize, $iCurrPos);
  2352. $bContinue = true;
  2353. break;
  2354. case 2:
  2355. $this->DoJob2($iMaxChunkSize, $iCurrPos);
  2356. $bContinue = true;
  2357. break;
  2358. case 3:
  2359. $bContinue = $this->DoJob3($iMaxChunkSize, $iCurrPos);
  2360. break;
  2361. }
  2362. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2363. self::$m_oCurrentTask = null;
  2364. return $bContinue;
  2365. }
  2366. /**
  2367. * Do the synchronization job #1: Obsolete replica "untouched" for some time
  2368. * @param integer $iMaxReplica Limit the number of replicas to process
  2369. * @param integer $iCurrPos Current position where to resume the processing
  2370. * @return true if the process must be continued
  2371. */
  2372. protected function DoJob1($iMaxReplica = null, $iCurrPos = -1)
  2373. {
  2374. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2375. // Get all the replicas that were not seen in the last import and mark them as obsolete
  2376. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2377. if ($sDeletePolicy != 'ignore')
  2378. {
  2379. $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";
  2380. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2381. $iCountScope = $oSetScope->Count();
  2382. if (($this->m_iCountAllReplicas > 10) && ($this->m_iCountAllReplicas == $iCountScope) && MetaModel::GetConfig()->Get('synchro_prevent_delete_all'))
  2383. {
  2384. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  2385. }
  2386. if ($iMaxReplica)
  2387. {
  2388. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2389. // The replica have to be ordered by id
  2390. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2391. $oSetToProcess->SetLimit($iMaxReplica);
  2392. }
  2393. else
  2394. {
  2395. $oSetToProcess = $oSetScope;
  2396. }
  2397. $iLastReplicaProcessed = -1;
  2398. while($oReplica = $oSetToProcess->Fetch())
  2399. {
  2400. $iLastReplicaProcessed = $oReplica->GetKey();
  2401. switch ($sDeletePolicy)
  2402. {
  2403. case 'update':
  2404. case 'update_then_delete':
  2405. $this->m_oStatLog->AddTrace("Destination object to be updated", $oReplica);
  2406. $aToUpdate = array();
  2407. $aToUpdateSpec = explode(';', $this->m_oDataSource->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  2408. foreach($aToUpdateSpec as $sUpdateSpec)
  2409. {
  2410. $aUpdateSpec = explode(':', $sUpdateSpec);
  2411. if (count($aUpdateSpec) == 2)
  2412. {
  2413. $sAttCode = $aUpdateSpec[0];
  2414. $sValue = $aUpdateSpec[1];
  2415. $aToUpdate[$sAttCode] = $sValue;
  2416. }
  2417. }
  2418. $oReplica->Set('status_last_error', '');
  2419. if ($oReplica->Get('dest_id') == '')
  2420. {
  2421. $oReplica->Set('status', 'obsolete');
  2422. $this->m_oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  2423. }
  2424. else
  2425. {
  2426. $oReplica->UpdateDestObject($aToUpdate, $this->m_oChange, $this->m_oStatLog);
  2427. if ($oReplica->Get('status_last_error') == '')
  2428. {
  2429. // Change the status of the replica IIF
  2430. $oReplica->Set('status', 'obsolete');
  2431. }
  2432. }
  2433. $oReplica->DBUpdateTracked($this->m_oChange);
  2434. break;
  2435. case 'delete':
  2436. default:
  2437. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2438. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2439. }
  2440. }
  2441. if ($iMaxReplica)
  2442. {
  2443. if ($iMaxReplica < $iCountScope)
  2444. {
  2445. // Continue with this job!
  2446. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2447. return true;
  2448. }
  2449. }
  2450. } // if ($sDeletePolicy != 'ignore'
  2451. //Count "seen" objects
  2452. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  2453. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate));
  2454. $this->m_oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  2455. // Job complete!
  2456. $this->m_oStatLog->Set('status_curr_job', 2);
  2457. $this->m_oStatLog->Set('status_curr_pos', -1);
  2458. return false;
  2459. }
  2460. /**
  2461. * Do the synchronization job #2: Create and modify object for new/modified replicas
  2462. * @param integer $iMaxReplica Limit the number of replicas to process
  2463. * @param integer $iCurrPos Current position where to resume the processing
  2464. * @return true if the process must be continued
  2465. */
  2466. protected function DoJob2($iMaxReplica = null, $iCurrPos = -1)
  2467. {
  2468. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2469. // Get all the replicas that are 'new' or modified or synchronized with a warning
  2470. //
  2471. $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";
  2472. $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);
  2473. $iCountScope = $oSetScope->Count();
  2474. if ($iMaxReplica)
  2475. {
  2476. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2477. // The replica have to be ordered by id
  2478. $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);
  2479. $oSetToProcess->SetLimit($iMaxReplica);
  2480. }
  2481. else
  2482. {
  2483. $oSetToProcess = $oSetScope;
  2484. }
  2485. $iLastReplicaProcessed = -1;
  2486. while($oReplica = $oSetToProcess->Fetch())
  2487. {
  2488. $iLastReplicaProcessed = $oReplica->GetKey();
  2489. $oReplica->Synchro($this->m_oDataSource, $this->m_aReconciliationKeys, $this->m_aAttributes, $this->m_oChange, $this->m_oStatLog);
  2490. $oReplica->DBUpdateTracked($this->m_oChange);
  2491. }
  2492. if ($iMaxReplica)
  2493. {
  2494. if ($iMaxReplica < $iCountScope)
  2495. {
  2496. // Continue with this job!
  2497. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2498. return true;
  2499. }
  2500. }
  2501. // Job complete!
  2502. $this->m_oStatLog->Set('status_curr_job', 3);
  2503. $this->m_oStatLog->Set('status_curr_pos', -1);
  2504. return false;
  2505. }
  2506. /**
  2507. * Do the synchronization job #3: Delete replica depending on the obsolescence scheme
  2508. * @param integer $iMaxReplica Limit the number of replicas to process
  2509. * @param integer $iCurrPos Current position where to resume the processing
  2510. * @return true if the process must be continued
  2511. */
  2512. protected function DoJob3($iMaxReplica = null, $iCurrPos = -1)
  2513. {
  2514. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2515. if ($sDeletePolicy != 'update_then_delete')
  2516. {
  2517. // Job complete!
  2518. $this->m_oStatLog->Set('status_curr_job', 0);
  2519. $this->m_oStatLog->Set('status_curr_pos', -1);
  2520. return false;
  2521. }
  2522. $bFirstPass = ($iCurrPos == -1);
  2523. // Get all the replicas that are to be deleted
  2524. //
  2525. $oDeletionDate = $this->m_oLastFullLoadStartDate;
  2526. $iDeleteRetention = $this->m_oDataSource->Get('delete_policy_retention'); // Duration in seconds
  2527. if ($iDeleteRetention > 0)
  2528. {
  2529. $sInterval = "-$iDeleteRetention seconds";
  2530. $oDeletionDate->Modify($sInterval);
  2531. }
  2532. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  2533. if ($bFirstPass)
  2534. {
  2535. $this->m_oStatLog->AddTrace("Deletion date: $sDeletionDate");
  2536. }
  2537. $sSelectToDelete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  2538. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2539. $iCountScope = $oSetScope->Count();
  2540. if ($iMaxReplica)
  2541. {
  2542. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2543. // The replica have to be ordered by id
  2544. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2545. $oSetToProcess->SetLimit($iMaxReplica);
  2546. }
  2547. else
  2548. {
  2549. $oSetToProcess = $oSetScope;
  2550. }
  2551. $iLastReplicaProcessed = -1;
  2552. while($oReplica = $oSetToProcess->Fetch())
  2553. {
  2554. $iLastReplicaProcessed = $oReplica->GetKey();
  2555. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2556. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2557. }
  2558. if ($iMaxReplica)
  2559. {
  2560. if ($iMaxReplica < $iCountScope)
  2561. {
  2562. // Continue with this job!
  2563. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2564. return true;
  2565. }
  2566. }
  2567. // Job complete!
  2568. $this->m_oStatLog->Set('status_curr_job', 0);
  2569. $this->m_oStatLog->Set('status_curr_pos', -1);
  2570. return false;
  2571. }
  2572. }
  2573. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2574. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2575. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2576. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  2577. ?>