synchrodatasource.class.inc.php 108 KB

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