synchrodatasource.class.inc.php 114 KB

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