synchrodatasource.class.inc.php 113 KB

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