synchrodatasource.class.inc.php 108 KB

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