synchrodatasource.class.inc.php 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  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 static $m_oCurrentTask = null;
  87. public static function GetCurrentTaskId()
  88. {
  89. if (is_object(self::$m_oCurrentTask))
  90. {
  91. return self::$m_oCurrentTask->GetKey();
  92. }
  93. else
  94. {
  95. return null;
  96. }
  97. }
  98. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  99. {
  100. if (!$this->IsNew())
  101. {
  102. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  103. $oAttributeSet = $this->Get('attribute_list');
  104. $aAttributes = array();
  105. while($oAttribute = $oAttributeSet->Fetch())
  106. {
  107. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  108. }
  109. // Columns of the form
  110. $aAttribs = array();
  111. foreach(array('attcode', 'reconciliation', 'update', 'update_policy', 'reconciliation_attcode') as $s )
  112. {
  113. $aAttribs[$s] = array( 'label' => Dict::S("Core:SynchroAtt:$s"), "description" => Dict::S("Core:SynchroAtt:$s+"));
  114. }
  115. // Rows of the form
  116. $aValues = array();
  117. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  118. {
  119. if ($oAttDef->IsWritable())
  120. {
  121. if (isset($aAttributes[$sAttCode]))
  122. {
  123. $oAttribute = $aAttributes[$sAttCode];
  124. }
  125. else
  126. {
  127. if ($oAttDef->IsExternalKey())
  128. {
  129. $oAttribute = new SynchroAttExtKey();
  130. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  131. }
  132. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  133. {
  134. $oAttribute = new SynchroAttLinkSet();
  135. // Todo - add these settings into the form
  136. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  137. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  138. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  139. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  140. }
  141. elseif ($oAttDef->IsScalar())
  142. {
  143. $oAttribute = new SynchroAttribute();
  144. }
  145. else
  146. {
  147. $oAttribute = null;
  148. }
  149. if (!is_null($oAttribute))
  150. {
  151. $oAttribute->Set('sync_source_id', $this->GetKey());
  152. $oAttribute->Set('attcode', $sAttCode);
  153. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  154. $oAttribute->Set('update', 1);
  155. $oAttribute->Set('update_policy', 'master_locked');
  156. }
  157. }
  158. if (!is_null($oAttribute))
  159. {
  160. if (!$bEditMode)
  161. {
  162. // Read-only mode
  163. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  164. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  165. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  166. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  167. if ($oAttDef->IsExternalKey())
  168. {
  169. $aRow['reconciliation_attcode'] = $oAttribute->GetAsHTML('reconciliation_attcode');
  170. }
  171. else
  172. {
  173. $aRow['reconciliation_attcode'] = '&nbsp;';
  174. }
  175. }
  176. else
  177. {
  178. // Edit mode
  179. $sAttCode = $oAttribute->Get('attcode');
  180. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  181. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  182. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  183. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  184. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  185. $oUpdateAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  186. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oUpdateAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  187. if ($oAttDef->IsExternalKey())
  188. {
  189. $aRow['reconciliation_attcode'] = $oAttribute->GetReconciliationFormElement($oAttDef->GetTargetClass(), "attr_reconciliation_attcode[$sAttCode]");
  190. }
  191. else
  192. {
  193. $aRow['reconciliation_attcode'] = '&nbsp;';
  194. }
  195. }
  196. $aValues[] = $aRow;
  197. }
  198. }
  199. }
  200. $oPage->p(Dict::Format('Class:SynchroDataSource:DataTable', $this->GetDataTable()));
  201. $oPage->Table($aAttribs, $aValues);
  202. $this->DisplayStatusTab($oPage);
  203. }
  204. parent::DisplayBareRelations($oPage, $bEditMode);
  205. }
  206. /**
  207. * Displays the status (SynchroLog) of the datasource in a graphical manner
  208. * @param $oPage WebPage
  209. * @return void
  210. */
  211. protected function DisplayStatusTab(WebPage $oPage)
  212. {
  213. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  214. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  215. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  216. if ($oSetSynchroLog->Count() > 0)
  217. {
  218. $oLastLog = $oSetSynchroLog->Fetch();
  219. $sStartDate = $oLastLog->Get('start_date');
  220. $oLastLog->Get('stats_nb_replica_seen');
  221. $iLastLog = 0;
  222. $iDSid = $this->GetKey();
  223. if ($oLastLog->Get('status') == 'running')
  224. {
  225. // Still running !
  226. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  227. }
  228. else
  229. {
  230. $sEndDate = $oLastLog->Get('end_date');
  231. $iLastLog = $oLastLog->GetKey();
  232. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  233. }
  234. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  235. // List all the log entries for the user to select
  236. $oPage->add('<h2 style="line-height:55px;">'.Dict::S('Core:Synchro:History').'</h2>');
  237. $oSetSynchroLog->Rewind();
  238. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  239. $sSelected = ' selected'; // First log is selected by default
  240. $sScript = "var aSynchroLog = {\n";
  241. while($oLog = $oSetSynchroLog->Fetch())
  242. {
  243. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  244. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  245. $sSelected = ''; // only the first log is selected by default
  246. $aData = $this->ProcessLog($oLog);
  247. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  248. }
  249. $sScript .= "end: 'Done'";
  250. $sScript .= "};\n";
  251. $sScript .= <<<EOF
  252. var sLastLog = '$iLastLog';
  253. function UpdateSynoptics(id)
  254. {
  255. var aValues = aSynchroLog[id];
  256. for (var sKey in aValues)
  257. {
  258. $('#c_'+sKey).html(aValues[sKey]);
  259. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  260. $('#'+sKey).fadeTo("slow", fOpacity);
  261. }
  262. //alert('id = '+id+', lastLog='+sLastLog+', id==sLastLog: '+(id==sLastLog)+' obj_updated_errors: '+aValues['obj_updated_errors']);
  263. if ( (id == sLastLog) && (aValues['obj_new_errors'] > 0) )
  264. {
  265. $('#new_errors_link').show();
  266. }
  267. else
  268. {
  269. $('#new_errors_link').hide();
  270. }
  271. if ( (id == sLastLog) && (aValues['obj_updated_errors'] > 0) )
  272. {
  273. $('#updated_errors_link').show();
  274. }
  275. else
  276. {
  277. $('#updated_errors_link').hide();
  278. }
  279. if ( (id == sLastLog) && (aValues['obj_disappeared_errors'] > 0) )
  280. {
  281. $('#disappeared_errors_link').show();
  282. }
  283. else
  284. {
  285. $('#disappeared_errors_link').hide();
  286. }
  287. }
  288. EOF
  289. ;
  290. $oPage->add_script($sScript);
  291. $oPage->add('</select>');
  292. $oPage->add('</td><td style="vertical-align:top;">');
  293. // Now build the big "synoptics" view
  294. $aData = $this->ProcessLog($oLastLog);
  295. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  296. $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>");
  297. $oPage->add(
  298. <<<EOF
  299. <table class="synoptics">
  300. <tr class="synoptics_header">
  301. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  302. </tr>
  303. <tr>
  304. EOF
  305. );
  306. $sBaseOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  307. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  308. $oPage->add("</tr>\n<tr>");
  309. $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'));
  310. $oPage->add("</tr>\n<tr>");
  311. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  312. $oPage->add("</tr>\n<tr>");
  313. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  314. $oPage->add("</tr>\n<tr>");
  315. $sOQL = urlencode($sBaseOQL." AND status='obsolete'");
  316. $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>"));
  317. $oPage->add("</tr>\n<tr>");
  318. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  319. $oPage->add("</tr>\n<tr>");
  320. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  321. $oPage->add("</tr>\n<tr>");
  322. $sOQL = urlencode($sBaseOQL." AND status='modified'");
  323. $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>"));
  324. $oPage->add("</tr>\n<tr>");
  325. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  326. $oPage->add("</tr>\n<tr>");
  327. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  328. $oPage->add("</tr>\n<tr>");
  329. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  330. $oPage->add("</tr>\n<tr>");
  331. $sOQL = urlencode($sBaseOQL." AND status='new'");
  332. $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>"));
  333. $oPage->add("</tr>\n</table>\n");
  334. $oPage->add('</td></tr></table>');
  335. $oPage->add_ready_script("UpdateSynoptics('$iLastLog')");
  336. }
  337. else
  338. {
  339. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  340. }
  341. }
  342. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '', $sErrorLink = '')
  343. {
  344. $iCount = $aData[$sId];
  345. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  346. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  347. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  348. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>{$sLabel}{$sErrorLink}</td>";
  349. }
  350. protected function ProcessLog($oLastLog)
  351. {
  352. $aData = array(
  353. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  354. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  355. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  356. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  357. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  358. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  359. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  360. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  361. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  362. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  363. );
  364. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  365. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  366. $aData['repl_disappeared'] = $iDisappeared;
  367. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  368. $aData['obj_new_errors'] = $iNewErrors;
  369. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  370. $aData['repl_new'] = $iNew;
  371. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  372. $aData['repl_existing'] = $iExisting;
  373. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  374. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  375. $aData['repl_ignored'] = $iIgnored;
  376. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  377. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  378. return $aData;
  379. }
  380. public function GetIcon($bImgTag = true, $sMoreStyles = '')
  381. {
  382. if ($this->Get('url_icon') == '') return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  383. if ($bImgTag)
  384. {
  385. return "<img src=\"".$this->Get('url_icon')."\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  386. }
  387. return $this->Get('url_icon');
  388. }
  389. /**
  390. * Get the actual hyperlink to the remote application for the given replica and dest object
  391. */
  392. public function GetApplicationUrl(DBObject $oDestObj, SynchroReplica $oReplica)
  393. {
  394. if ($this->Get('url_application') == '') return '';
  395. $aSearches = array();
  396. $aReplacements = array();
  397. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  398. {
  399. if ($oAttDef->IsScalar())
  400. {
  401. $aSearches[] = '$this->'.$sAttCode.'$';
  402. $aReplacements[] = $oDestObj->Get($sAttCode);
  403. }
  404. }
  405. $aData = $oReplica->LoadExtendedDataFromTable($this->GetDataTable());
  406. foreach($aData as $sColumn => $value)
  407. {
  408. $aSearches[] = '$replica->'.$sColumn.'$';
  409. $aReplacements[] = $value;
  410. }
  411. return str_replace($aSearches, $aReplacements, $this->Get('url_application'));
  412. }
  413. public function GetAttributeFlags($sAttCode, &$aReasons = array())
  414. {
  415. if (($sAttCode == 'scope_class') && (!$this->IsNew()))
  416. {
  417. return OPT_ATT_READONLY;
  418. }
  419. return parent::GetAttributeFlags($sAttCode, $aReasons);
  420. }
  421. public function UpdateObjectFromPostedForm($sFormPrefix = '', $sAttList = null)
  422. {
  423. parent::UpdateObjectFromPostedForm($sFormPrefix, $sAttList);
  424. // And now read the other post parameters...
  425. $oAttributeSet = $this->Get('attribute_list');
  426. $aAttributes = array();
  427. while($oAttribute = $oAttributeSet->Fetch())
  428. {
  429. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  430. }
  431. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  432. $aUpdate = utils::ReadPostedParam('update', array());
  433. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  434. $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array());
  435. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  436. // through all the writable attributes
  437. foreach($aUpdatePolicy as $sAttCode => $sValue)
  438. {
  439. if(!isset($aAttributes[$sAttCode]))
  440. {
  441. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  442. if ($oAttDef->IsExternalKey())
  443. {
  444. $oAttribute = new SynchroAttExtKey();
  445. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  446. }
  447. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  448. {
  449. $oAttribute = new SynchroAttLinkSet();
  450. // Todo - set those value from the form
  451. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  452. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  453. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  454. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  455. }
  456. else
  457. {
  458. $oAttribute = new SynchroAttribute();
  459. }
  460. $oAttribute->Set('sync_source_id', $this->GetKey());
  461. $oAttribute->Set('attcode', $sAttCode);
  462. }
  463. else
  464. {
  465. $oAttribute = $aAttributes[$sAttCode];
  466. }
  467. $bReconcile = 0;
  468. if (isset($aReconcile[$sAttCode]))
  469. {
  470. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  471. }
  472. $bUpdate = 0 ; // Default / initial value
  473. if (isset($aUpdate[$sAttCode]))
  474. {
  475. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  476. }
  477. $oAttribute->Set('reconcile', $bReconcile);
  478. $oAttribute->Set('update', $bUpdate);
  479. $oAttribute->Set('update_policy', $sValue);
  480. if ($oAttribute instanceof SynchroAttExtKey)
  481. {
  482. $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]);
  483. }
  484. elseif ($oAttribute instanceof SynchroAttLinkSet)
  485. {
  486. }
  487. $oAttributeSet->AddObject($oAttribute);
  488. }
  489. $this->Set('attribute_list', $oAttributeSet);
  490. }
  491. /*
  492. * Overload the standard behavior
  493. */
  494. public function ComputeValues()
  495. {
  496. parent::ComputeValues();
  497. if ($this->IsNew())
  498. {
  499. // When inserting a new datasource object, also create the SynchroAttribute objects
  500. // for each field of the target class
  501. // Create all the SynchroAttribute records
  502. $oAttributeSet = $this->Get('attribute_list');
  503. if ($oAttributeSet->Count() == 0)
  504. {
  505. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  506. {
  507. if ($oAttDef->IsWritable())
  508. {
  509. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  510. if ($oAttDef->IsExternalKey())
  511. {
  512. $oAttribute = new SynchroAttExtKey();
  513. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  514. }
  515. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  516. {
  517. $oAttribute = new SynchroAttLinkSet();
  518. // Todo - set those value from the form
  519. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  520. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  521. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  522. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  523. }
  524. elseif ($oAttDef->IsScalar())
  525. {
  526. $oAttribute = new SynchroAttribute();
  527. }
  528. else
  529. {
  530. $oAttribute = null;
  531. }
  532. if (!is_null($oAttribute))
  533. {
  534. $oAttribute->Set('sync_source_id', $this->GetKey());
  535. $oAttribute->Set('attcode', $sAttCode);
  536. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  537. $oAttribute->Set('update', 1);
  538. $oAttribute->Set('update_policy', 'master_locked');
  539. $oAttributeSet->AddObject($oAttribute);
  540. }
  541. }
  542. }
  543. $this->Set('attribute_list', $oAttributeSet);
  544. }
  545. }
  546. }
  547. public function DoCheckToWrite()
  548. {
  549. parent::DoCheckToWrite();
  550. // Check that there is at least one reconciliation key defined
  551. if ($this->Get('reconciliation_policy') == 'use_attributes')
  552. {
  553. $oSet = $this->Get('attribute_list');
  554. $oSynchroAttributeList = $oSet->ToArray();
  555. $bReconciliationKey = false;
  556. foreach($oSynchroAttributeList as $oSynchroAttribute)
  557. {
  558. if ($oSynchroAttribute->Get('reconcile') == 1)
  559. {
  560. $bReconciliationKey = true; // At least one key is defined
  561. break;
  562. }
  563. }
  564. if (!$bReconciliationKey)
  565. {
  566. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  567. }
  568. }
  569. // If 'update_then_delete' is specified there must be a delete_retention_period
  570. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  571. {
  572. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  573. }
  574. // If update is specified, then something to update must be defined
  575. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  576. && ($this->Get('delete_policy_update') == ''))
  577. {
  578. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  579. }
  580. }
  581. public function GetTargetClass()
  582. {
  583. return $this->Get('scope_class');
  584. }
  585. public function GetDataTable()
  586. {
  587. $sName = strtolower($this->GetTargetClass());
  588. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  589. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  590. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  591. return $sTable;
  592. }
  593. /**
  594. * When the new datasource has been created, let's create the synchro_data table
  595. * that will hold the data records and the correspoding triggers which will maintain
  596. * both tables in sync
  597. */
  598. protected function AfterInsert()
  599. {
  600. parent::AfterInsert();
  601. $sTable = $this->GetDataTable();
  602. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  603. $aColumns = $this->GetSQLColumns();
  604. $aFieldDefs = array();
  605. // Allow '0', otherwise mysql will render an error when the id is not given
  606. // (the trigger is expected to set the value, but it is not executed soon enough)
  607. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  608. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  609. foreach($aColumns as $sColumn => $ColSpec)
  610. {
  611. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  612. }
  613. $aFieldDefs[] = "INDEX (id)";
  614. $aFieldDefs[] = "INDEX (primary_key)";
  615. $sFieldDefs = implode(', ', $aFieldDefs);
  616. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  617. CMDBSource::Query($sCreateTable);
  618. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  619. $sTriggerInsert .= " FOR EACH ROW";
  620. $sTriggerInsert .= " BEGIN";
  621. $sTriggerInsert .= " INSERT INTO {$sReplicaTable} (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  622. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  623. $sTriggerInsert .= " END;";
  624. CMDBSource::Query($sTriggerInsert);
  625. $aModified = array();
  626. foreach($aColumns as $sColumn => $ColSpec)
  627. {
  628. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  629. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  630. }
  631. $sIsModified = '('.implode(') OR (', $aModified).')';
  632. // Update the replica
  633. //
  634. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  635. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  636. // otherwise, the status is left as is
  637. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  638. $sTriggerUpdate .= " FOR EACH ROW";
  639. $sTriggerUpdate .= " BEGIN";
  640. $sTriggerUpdate .= " IF @itopuser is null THEN";
  641. $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;";
  642. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  643. $sTriggerUpdate .= " END IF;";
  644. $sTriggerUpdate .= " END;";
  645. CMDBSource::Query($sTriggerUpdate);
  646. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  647. $sTriggerInsert .= " FOR EACH ROW";
  648. $sTriggerInsert .= " BEGIN";
  649. $sTriggerInsert .= " DELETE FROM {$sReplicaTable} WHERE id = OLD.id;";
  650. $sTriggerInsert .= " END;";
  651. CMDBSource::Query($sTriggerInsert);
  652. }
  653. protected function AfterDelete()
  654. {
  655. parent::AfterDelete();
  656. $sTable = $this->GetDataTable();
  657. $sDropTable = "DROP TABLE `$sTable`";
  658. CMDBSource::Query($sDropTable);
  659. // TO DO - check that triggers get dropped with the table
  660. }
  661. protected function SendNotification($sSubject, $sBody)
  662. {
  663. $iContact = $this->Get('notify_contact_id');
  664. if ($iContact == 0)
  665. {
  666. // Leave silently...
  667. return;
  668. }
  669. $oContact = MetaModel::GetObject('Contact', $iContact);
  670. // Determine the email attribute (the first one will be our choice)
  671. $sEmailAttCode = null;
  672. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  673. {
  674. if ($oAttDef instanceof AttributeEmailAddress)
  675. {
  676. $sEmailAttCode = $sAttCode;
  677. // we've got one, exit the loop
  678. break;
  679. }
  680. }
  681. if (is_null($sEmailAttCode))
  682. {
  683. // Leave silently...
  684. return;
  685. }
  686. $sTo = $oContact->Get($sEmailAttCode);
  687. $sFrom = $sTo;
  688. $sBody = '<p>Data synchronization: '.$this->GetHyperlink().'</p>'.$sBody;
  689. $sSubject = 'iTop Data Sync - '.$this->GetName().' - '.$sSubject;
  690. $oEmail = new Email();
  691. $oEmail->SetRecipientTO($sTo);
  692. $oEmail->SetRecipientFrom($sFrom);
  693. $oEmail->SetSubject($sSubject);
  694. $oEmail->SetBody($sBody);
  695. if ($oEmail->Send($aIssues) == EMAIL_SEND_ERROR)
  696. {
  697. // mmmm, what can I do?
  698. }
  699. }
  700. /**
  701. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  702. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  703. * is used to determine which records are obsolete.
  704. * @param Hash $aTraces Debugs/Trace information, one or more entries per replica
  705. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  706. * @return void
  707. */
  708. public function Synchronize($oLastFullLoadStartDate = null)
  709. {
  710. // Create a change used for logging all the modifications/creations happening during the synchro
  711. $oMyChange = MetaModel::NewObject("CMDBChange");
  712. $oMyChange->Set("date", time());
  713. $sUserString = CMDBChange::GetCurrentUserName();
  714. $oMyChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  715. $iChangeId = $oMyChange->DBInsert();
  716. // Start logging this execution (stats + protection against reentrance)
  717. //
  718. $oStatLog = new SynchroLog();
  719. $oStatLog->Set('sync_source_id', $this->GetKey());
  720. $oStatLog->Set('start_date', time());
  721. $oStatLog->Set('status', 'running');
  722. $oStatLog->Set('stats_nb_replica_seen', 0);
  723. $oStatLog->Set('stats_nb_replica_total', 0);
  724. $oStatLog->Set('stats_nb_obj_deleted', 0);
  725. $oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  726. $oStatLog->Set('stats_nb_obj_obsoleted', 0);
  727. $oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  728. $oStatLog->Set('stats_nb_obj_created', 0);
  729. $oStatLog->Set('stats_nb_obj_created_errors', 0);
  730. $oStatLog->Set('stats_nb_obj_updated', 0);
  731. $oStatLog->Set('stats_nb_obj_updated_errors', 0);
  732. // $oStatLog->Set('stats_nb_replica_reconciled', 0);
  733. $oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  734. $oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  735. $oStatLog->Set('stats_nb_obj_new_updated', 0);
  736. $oStatLog->Set('stats_nb_obj_new_unchanged',0);
  737. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  738. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->GetKey()));
  739. $oStatLog->Set('stats_nb_replica_total', $oSetTotal->Count());
  740. $oStatLog->DBInsertTracked($oMyChange);
  741. self::$m_oCurrentTask = $this;
  742. try
  743. {
  744. $this->DoSynchronize($oLastFullLoadStartDate, $oMyChange, $oStatLog);
  745. $oStatLog->Set('end_date', time());
  746. $oStatLog->Set('status', 'completed');
  747. $oStatLog->DBUpdateTracked($oMyChange);
  748. $iErrors = $oStatLog->GetErrorCount();
  749. if ($iErrors > 0)
  750. {
  751. $sIssuesOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  752. $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
  753. $sIssuesURL = "{$sAbsoluteUrl}synchro/replica.php?operation=oql&datasource=".$this->GetKey()."&oql=".urlencode($sIssuesOQL);
  754. $sSeeIssues = "<p></p>";
  755. $sStatistics = "<h1>Statistics</h1>\n";
  756. $sStatistics .= "<ul>\n";
  757. $sStatistics .= "<li>".$oStatLog->GetLabel('start_date').": ".$oStatLog->Get('start_date')."</li>\n";
  758. $sStatistics .= "<li>".$oStatLog->GetLabel('end_date').": ".$oStatLog->Get('end_date')."</li>\n";
  759. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_replica_seen').": ".$oStatLog->Get('stats_nb_replica_seen')."</li>\n";
  760. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_replica_total').": ".$oStatLog->Get('stats_nb_replica_total')."</li>\n";
  761. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_deleted').": ".$oStatLog->Get('stats_nb_obj_deleted')."</li>\n";
  762. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_deleted_errors').": ".$oStatLog->Get('stats_nb_obj_deleted_errors')."</li>\n";
  763. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_obsoleted').": ".$oStatLog->Get('stats_nb_obj_obsoleted')."</li>\n";
  764. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_obsoleted_errors').": ".$oStatLog->Get('stats_nb_obj_obsoleted_errors')."</li>\n";
  765. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_created').": ".$oStatLog->Get('stats_nb_obj_created')."</li>\n";
  766. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_created_errors').": ".$oStatLog->Get('stats_nb_obj_created_errors')."</li>\n";
  767. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_updated').": ".$oStatLog->Get('stats_nb_obj_updated')."</li>\n";
  768. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_updated_errors').": ".$oStatLog->Get('stats_nb_obj_updated_errors')."</li>\n";
  769. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_replica_reconciled_errors').": ".$oStatLog->Get('stats_nb_replica_reconciled_errors')."</li>\n";
  770. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_replica_disappeared_no_action').": ".$oStatLog->Get('stats_nb_replica_disappeared_no_action')."</li>\n";
  771. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_new_updated').": ".$oStatLog->Get('stats_nb_obj_new_updated')."</li>\n";
  772. $sStatistics .= "<li>".$oStatLog->GetLabel('stats_nb_obj_new_unchanged').": ".$oStatLog->Get('stats_nb_obj_new_unchanged')."</li>\n";
  773. $sStatistics .= "</ul>\n";
  774. $this->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);
  775. }
  776. else
  777. {
  778. //$this->SendNotification('success', '<p>The synchronization has been successfully executed.</p>');
  779. }
  780. }
  781. catch (SynchroExceptionNotStarted $e)
  782. {
  783. // Set information for reporting... but delete the object in DB
  784. $oStatLog->Set('end_date', time());
  785. $oStatLog->Set('status', 'error');
  786. $oStatLog->Set('last_error', $e->getMessage());
  787. $oStatLog->DBDeleteTracked($oMyChange);
  788. $this->SendNotification('fatal error', '<p>The synchronization could not start: \''.$e->getMessage().'\'</p><p>Please check its configuration</p>');
  789. }
  790. catch (Exception $e)
  791. {
  792. $oStatLog->Set('end_date', time());
  793. $oStatLog->Set('status', 'error');
  794. $oStatLog->Set('last_error', $e->getMessage());
  795. $oStatLog->DBUpdateTracked($oMyChange);
  796. $this->SendNotification('exception', '<p>The synchronization has been interrupted: \''.$e->getMessage().'\'</p><p>Please contact the application support team</p>');
  797. }
  798. self::$m_oCurrentTask = null;
  799. return $oStatLog;
  800. }
  801. protected function DoSynchronize($oLastFullLoadStartDate, $oMyChange, &$oStatLog)
  802. {
  803. if ($this->Get('status') == 'obsolete')
  804. {
  805. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  806. }
  807. if (!UserRights::IsAdministrator() && $this->Get('user_id') != UserRights::GetUserId())
  808. {
  809. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  810. }
  811. // Get the list of SQL columns
  812. $sClass = $this->GetTargetClass();
  813. $aAttCodesExpected = array();
  814. $aAttCodesToReconcile = array();
  815. $aAttCodesToUpdate = array();
  816. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  817. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  818. while ($oSyncAtt = $oSetAtt->Fetch())
  819. {
  820. if ($oSyncAtt->Get('update'))
  821. {
  822. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  823. }
  824. if ($oSyncAtt->Get('reconcile'))
  825. {
  826. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  827. }
  828. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  829. }
  830. $aColumns = $this->GetSQLColumns(array_keys($aAttCodesExpected));
  831. $aExtDataFields = array_keys($aColumns);
  832. $aExtDataFields[] = 'primary_key';
  833. $aExtDataSpec = array(
  834. 'table' => $this->GetDataTable(),
  835. 'join_key' => 'id',
  836. 'fields' => $aExtDataFields
  837. );
  838. // Get the list of attributes, determine reconciliation keys and update targets
  839. //
  840. if ($this->Get('reconciliation_policy') == 'use_attributes')
  841. {
  842. $aReconciliationKeys = $aAttCodesToReconcile;
  843. }
  844. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  845. {
  846. // Override the settings made at the attribute level !
  847. $aReconciliationKeys = array("primary_key" => null);
  848. }
  849. $oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  850. $oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($aReconciliationKeys))."}");
  851. if (count($aAttCodesToUpdate) == 0)
  852. {
  853. $oStatLog->AddTrace("No attribute to update");
  854. throw new SynchroExceptionNotStarted('There is no attribute to update');
  855. }
  856. if (count($aReconciliationKeys) == 0)
  857. {
  858. $oStatLog->AddTrace("No attribute for reconciliation");
  859. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  860. }
  861. $aAttributes = array();
  862. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  863. {
  864. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  865. if ($oAttDef->IsWritable())
  866. {
  867. $aAttributes[$sAttCode] = $oSyncAtt;
  868. }
  869. }
  870. // Count the replicas
  871. $sSelectAll = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  872. $oSetAll = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAll), array() /* order by*/, array('source_id' => $this->GetKey()));
  873. $iCountAllReplicas = $oSetAll->Count();
  874. $oStatLog->Set('stats_nb_replica_total', $iCountAllReplicas);
  875. // Get all the replicas that were not seen in the last import and mark them as obsolete
  876. if ($oLastFullLoadStartDate == null)
  877. {
  878. // No previous import known, use the full_load_periodicity value... and the current date
  879. $oLastFullLoadStartDate = new DateTime(); // Now
  880. $iLoadPeriodicity = $this->Get('full_load_periodicity'); // Duration in seconds
  881. if ($iLoadPeriodicity > 0)
  882. {
  883. $sInterval = "-$iLoadPeriodicity seconds";
  884. $oLastFullLoadStartDate->Modify($sInterval);
  885. }
  886. else
  887. {
  888. $oLastFullLoadStartDate = new DateTime('1970-01-01');
  889. }
  890. }
  891. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  892. $oStatLog->AddTrace("Limit Date: $sLimitDate");
  893. $sDeletePolicy = $this->Get('delete_policy');
  894. if ($sDeletePolicy != 'ignore')
  895. {
  896. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  897. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  898. if (($iCountAllReplicas > 10) && ($iCountAllReplicas == $oSetToObsolete->Count()))
  899. {
  900. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  901. }
  902. while($oReplica = $oSetToObsolete->Fetch())
  903. {
  904. switch ($sDeletePolicy)
  905. {
  906. case 'update':
  907. case 'update_then_delete':
  908. $oStatLog->AddTrace("Destination object to be updated", $oReplica);
  909. $aToUpdate = array();
  910. $aToUpdateSpec = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  911. foreach($aToUpdateSpec as $sUpdateSpec)
  912. {
  913. $aUpdateSpec = explode(':', $sUpdateSpec);
  914. if (count($aUpdateSpec) == 2)
  915. {
  916. $sAttCode = $aUpdateSpec[0];
  917. $sValue = $aUpdateSpec[1];
  918. $aToUpdate[$sAttCode] = $sValue;
  919. }
  920. }
  921. $oReplica->Set('status_last_error', '');
  922. $oReplica->UpdateDestObject($aToUpdate, $oMyChange, $oStatLog);
  923. if ($oReplica->Get('status_last_error') == '')
  924. {
  925. // Change the status of the replica IIF
  926. $oReplica->Set('status', 'obsolete');
  927. }
  928. $oReplica->DBUpdateTracked($oMyChange);
  929. break;
  930. case 'delete':
  931. default:
  932. $oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  933. $oReplica->DeleteDestObject($oMyChange, $oStatLog);
  934. }
  935. }
  936. } // if ($sDeletePolicy != 'ignore'
  937. //Count "seen" objects
  938. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  939. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  940. $oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  941. // Get all the replicas that are 'new' or modified
  942. //
  943. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  944. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  945. while($oReplica = $oSetToSync->Fetch())
  946. {
  947. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange, $oStatLog);
  948. $oReplica->DBUpdateTracked($oMyChange);
  949. }
  950. // Get all the replicas that are to be deleted
  951. //
  952. if ($sDeletePolicy == 'update_then_delete')
  953. {
  954. $oDeletionDate = $oLastFullLoadStartDate;
  955. $iDeleteRetention = $this->Get('delete_policy_retention'); // Duration in seconds
  956. if ($iDeleteRetention > 0)
  957. {
  958. $sInterval = "-$iDeleteRetention seconds";
  959. $oDeletionDate->Modify($sInterval);
  960. }
  961. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  962. $oStatLog->AddTrace("Deletion date: $sDeletionDate");
  963. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  964. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  965. while($oReplica = $oSetToDelete->Fetch())
  966. {
  967. $oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  968. $oReplica->DeleteDestObject($oMyChange, $oStatLog);
  969. }
  970. }
  971. }
  972. /**
  973. * Get the list of SQL columns corresponding to a particular list of attribute codes
  974. * Defaults to the whole list of columns for the current class
  975. */
  976. public function GetSQLColumns($aAttributeCodes = null)
  977. {
  978. $aColumns = array();
  979. $sClass = $this->GetTargetClass();
  980. if (is_null($aAttributeCodes))
  981. {
  982. $aAttributeCodes = array();
  983. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  984. {
  985. if ($sAttCode == 'finalclass') continue;
  986. $aAttributeCodes[] = $sAttCode;
  987. }
  988. }
  989. foreach($aAttributeCodes as $sAttCode)
  990. {
  991. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  992. if ($oAttDef->IsExternalKey())
  993. {
  994. // The pkey might be used as well as any other key column
  995. $aColumns[$sAttCode] = 'VARCHAR (255)';
  996. }
  997. else
  998. {
  999. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  1000. {
  1001. $aColumns[$sField] = $sDBFieldType;
  1002. }
  1003. }
  1004. }
  1005. return $aColumns;
  1006. }
  1007. /**
  1008. * Get the list of Date and Datetime SQL columns
  1009. */
  1010. public function GetDateSQLColumns()
  1011. {
  1012. $aDateAttributes = array();
  1013. $sClass = $this->GetTargetClass();
  1014. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1015. {
  1016. if ($oAttDef instanceof AttributeDateTime)
  1017. {
  1018. $aDateAttributes[] = $sAttCode;
  1019. }
  1020. }
  1021. return $this->GetSQLColumns($aDateAttributes);
  1022. }
  1023. public function IsRunning()
  1024. {
  1025. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  1026. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1027. if ($oSet->Count() < 1)
  1028. {
  1029. $bRet = false;
  1030. }
  1031. else
  1032. {
  1033. $bRet = true;
  1034. }
  1035. return $bRet;
  1036. }
  1037. public function GetLatestLog()
  1038. {
  1039. $oLog = null;
  1040. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  1041. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1042. if ($oSet->Count() >= 1)
  1043. {
  1044. $oLog = $oSet->Fetch();
  1045. }
  1046. return $oLog;
  1047. }
  1048. // TO DO: remove if still unused
  1049. /**
  1050. * Retrieve from the log, the date of the last completed import
  1051. * @return DateTime
  1052. */
  1053. public function GetLastCompletedImportDate()
  1054. {
  1055. $date = null;
  1056. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  1057. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  1058. if ($oSet->Count() >= 1)
  1059. {
  1060. $oLog = $oSet->Fetch();
  1061. $date = $oLog->Get('end_date');
  1062. }
  1063. return $date;
  1064. }
  1065. }
  1066. class SynchroAttribute extends cmdbAbstractObject
  1067. {
  1068. public static function Init()
  1069. {
  1070. $aParams = array
  1071. (
  1072. "category" => "core/cmdb,view_in_gui",
  1073. "key_type" => "autoincrement",
  1074. "name_attcode" => "",
  1075. "state_attcode" => "",
  1076. "reconc_keys" => array(),
  1077. "db_table" => "priv_sync_att",
  1078. "db_key_field" => "id",
  1079. "db_finalclass_field" => "",
  1080. "display_template" => "",
  1081. );
  1082. MetaModel::Init_Params($aParams);
  1083. MetaModel::Init_InheritAttributes();
  1084. 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())));
  1085. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  1086. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  1087. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  1088. 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())));
  1089. // Display lists
  1090. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  1091. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1092. // Search criteria
  1093. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1094. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1095. }
  1096. }
  1097. class SynchroAttExtKey extends SynchroAttribute
  1098. {
  1099. public static function Init()
  1100. {
  1101. $aParams = array
  1102. (
  1103. "category" => "core/cmdb,view_in_gui",
  1104. "key_type" => "autoincrement",
  1105. "name_attcode" => "",
  1106. "state_attcode" => "",
  1107. "reconc_keys" => array(),
  1108. "db_table" => "priv_sync_att_extkey",
  1109. "db_key_field" => "id",
  1110. "db_finalclass_field" => "",
  1111. "display_template" => "",
  1112. );
  1113. MetaModel::Init_Params($aParams);
  1114. MetaModel::Init_InheritAttributes();
  1115. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1116. // Display lists
  1117. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  1118. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1119. // Search criteria
  1120. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1121. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1122. }
  1123. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  1124. {
  1125. $sHtml = "<select name=\"$sFieldName\">\n";
  1126. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1127. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  1128. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1129. {
  1130. if ($oAttDef->IsScalar())
  1131. {
  1132. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1133. $sHtml .= "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  1134. }
  1135. }
  1136. $sHtml .= "</select>\n";
  1137. return $sHtml;
  1138. }
  1139. }
  1140. class SynchroAttLinkSet extends SynchroAttribute
  1141. {
  1142. public static function Init()
  1143. {
  1144. $aParams = array
  1145. (
  1146. "category" => "core/cmdb,view_in_gui",
  1147. "key_type" => "autoincrement",
  1148. "name_attcode" => "",
  1149. "state_attcode" => "",
  1150. "reconc_keys" => array(),
  1151. "db_table" => "priv_sync_att_linkset",
  1152. "db_key_field" => "id",
  1153. "db_finalclass_field" => "",
  1154. "display_template" => "",
  1155. );
  1156. MetaModel::Init_Params($aParams);
  1157. MetaModel::Init_InheritAttributes();
  1158. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1159. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1160. MetaModel::Init_AddAttribute(new AttributeString("value_separator", array("allowed_values"=>null, "sql"=>"value_separator", "default_value"=>':', "is_null_allowed"=>true, "depends_on"=>array())));
  1161. MetaModel::Init_AddAttribute(new AttributeString("attribute_qualifier", array("allowed_values"=>null, "sql"=>"attribute_qualifier", "default_value"=>'\'', "is_null_allowed"=>true, "depends_on"=>array())));
  1162. // Display lists
  1163. 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
  1164. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1165. // Search criteria
  1166. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1167. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1168. }
  1169. }
  1170. //class SynchroLog extends Event
  1171. class SynchroLog extends DBObject
  1172. {
  1173. public static function Init()
  1174. {
  1175. $aParams = array
  1176. (
  1177. "category" => "core/cmdb,view_in_gui",
  1178. "key_type" => "autoincrement",
  1179. "name_attcode" => "",
  1180. "state_attcode" => "",
  1181. "reconc_keys" => array(),
  1182. "db_table" => "priv_sync_log",
  1183. "db_key_field" => "id",
  1184. "db_finalclass_field" => "",
  1185. "display_template" => "",
  1186. );
  1187. MetaModel::Init_Params($aParams);
  1188. MetaModel::Init_InheritAttributes();
  1189. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1190. 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())));
  1191. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1192. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1193. 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())));
  1194. 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())));
  1195. 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())));
  1196. 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())));
  1197. 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())));
  1198. 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())));
  1199. 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())));
  1200. 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())));
  1201. 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())));
  1202. 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())));
  1203. 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())));
  1204. // 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())));
  1205. 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())));
  1206. 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())));
  1207. 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())));
  1208. 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())));
  1209. MetaModel::Init_AddAttribute(new AttributeText("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1210. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1211. // Display lists
  1212. 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',
  1213. '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
  1214. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1215. // Search criteria
  1216. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1217. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1218. }
  1219. /**
  1220. * Helper
  1221. */
  1222. function GetErrorCount()
  1223. {
  1224. return $this->Get('stats_nb_obj_deleted_errors')
  1225. + $this->Get('stats_nb_obj_obsoleted_errors')
  1226. + $this->Get('stats_nb_obj_created_errors')
  1227. + $this->Get('stats_nb_obj_updated_errors')
  1228. + $this->Get('stats_nb_replica_reconciled_errors');
  1229. }
  1230. /**
  1231. * Increments a statistics counter
  1232. */
  1233. function Inc($sCode)
  1234. {
  1235. $this->Set($sCode, 1+$this->Get($sCode));
  1236. }
  1237. /**
  1238. * Implement traces management
  1239. */
  1240. protected $m_aTraces = array();
  1241. public function AddTrace($sMsg, $oReplica = null)
  1242. {
  1243. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1244. {
  1245. return;
  1246. }
  1247. if ($oReplica)
  1248. {
  1249. $sDestClass = $oReplica->Get('dest_class');
  1250. if (!empty($sDestClass))
  1251. {
  1252. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1253. }
  1254. else
  1255. {
  1256. $sPrefix = $oReplica->GetKey().',,';
  1257. }
  1258. }
  1259. else
  1260. {
  1261. $sPrefix = ',,';
  1262. }
  1263. $this->m_aTraces[] = $sPrefix.$sMsg;
  1264. }
  1265. public function GetTraces()
  1266. {
  1267. return $this->m_aTraces;
  1268. }
  1269. protected function TraceToText()
  1270. {
  1271. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1272. {
  1273. // none, or display only
  1274. return;
  1275. }
  1276. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1277. $iMaxSize = $oAttDef->GetMaxSize();
  1278. $sTrace = implode("\n", $this->m_aTraces);
  1279. if (strlen($sTrace) >= $iMaxSize)
  1280. {
  1281. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1282. }
  1283. $this->Set('traces', $sTrace);
  1284. }
  1285. protected function OnInsert()
  1286. {
  1287. $this->TraceToText();
  1288. parent::OnInsert();
  1289. }
  1290. protected function OnUpdate()
  1291. {
  1292. $this->TraceToText();
  1293. parent::OnUpdate();
  1294. }
  1295. }
  1296. class SynchroReplica extends DBObject implements iDisplay
  1297. {
  1298. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1299. public static function Init()
  1300. {
  1301. $aParams = array
  1302. (
  1303. "category" => "core/cmdb,view_in_gui",
  1304. "key_type" => "autoincrement",
  1305. "name_attcode" => "",
  1306. "state_attcode" => "",
  1307. "reconc_keys" => array(),
  1308. "db_table" => "priv_sync_replica",
  1309. "db_key_field" => "id",
  1310. "db_finalclass_field" => "",
  1311. "display_template" => "",
  1312. );
  1313. MetaModel::Init_Params($aParams);
  1314. MetaModel::Init_InheritAttributes();
  1315. 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())));
  1316. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1317. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1318. 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())));
  1319. 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())));
  1320. 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())));
  1321. 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())));
  1322. 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())));
  1323. 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())));
  1324. 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())));
  1325. // Display lists
  1326. MetaModel::Init_SetZListItems('details', array('' .
  1327. 'col:0'=> array(
  1328. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1329. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error'),
  1330. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1331. )
  1332. );
  1333. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error')); // Attributes to be displayed for a list
  1334. // Search criteria
  1335. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error')); // Criteria of the std search form
  1336. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1337. }
  1338. public function DBInsert()
  1339. {
  1340. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1341. }
  1342. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1343. // it will be deleted by the mean of a trigger too
  1344. protected function DBDeleteSingleObject()
  1345. {
  1346. $this->OnDelete();
  1347. if (!MetaModel::DBIsReadOnly())
  1348. {
  1349. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1350. $sTable = $oDataSource->GetDataTable();
  1351. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1352. CMDBSource::Query($sSQL);
  1353. }
  1354. $this->AfterDelete();
  1355. $this->m_bIsInDB = false;
  1356. $this->m_iKey = null;
  1357. }
  1358. public function SetLastError($sMessage, $oException = null)
  1359. {
  1360. if ($oException)
  1361. {
  1362. $sText = $sMessage.$oException->getMessage();
  1363. }
  1364. else
  1365. {
  1366. $sText = $sMessage;
  1367. }
  1368. if (strlen($sText) > 255)
  1369. {
  1370. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1371. }
  1372. $this->Set('status_last_error', $sText);
  1373. }
  1374. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1375. {
  1376. switch($this->Get('status'))
  1377. {
  1378. case 'new':
  1379. $this->Set('status_dest_creator', false);
  1380. // If needed, construct the query used for the reconciliation
  1381. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1382. {
  1383. $aCriterias = array();
  1384. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1385. {
  1386. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1387. }
  1388. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1389. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1390. }
  1391. // Get the criterias for the search
  1392. $aFilterValues = array();
  1393. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1394. {
  1395. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1396. if (!is_null($value))
  1397. {
  1398. $aFilterValues[$sFilterCode] = $value;
  1399. }
  1400. else
  1401. {
  1402. // Reconciliation could not be performed - log and EXIT
  1403. $oStatLog->AddTrace("Could not reconcile on null value for attribute '$sFilterCode'", $this);
  1404. $this->SetLastError("Could not reconcile on null value for attribute '$sFilterCode'");
  1405. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1406. return;
  1407. }
  1408. }
  1409. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1410. $iCount = $oDestSet->Count();
  1411. $aConditions = array();
  1412. foreach($aFilterValues as $sCode => $sValue)
  1413. {
  1414. $aConditions[] = $sCode.'='.$sValue;
  1415. }
  1416. $sConditionDesc = implode(' AND ', $aConditions);
  1417. // How many objects match the reconciliation criterias
  1418. switch($iCount)
  1419. {
  1420. case 0:
  1421. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1422. if ($oDataSource->Get('action_on_zero') == 'create')
  1423. {
  1424. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1425. }
  1426. else // assumed to be 'error'
  1427. {
  1428. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1429. $this->SetLastError('Could not find a match for reconciliation');
  1430. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1431. }
  1432. break;
  1433. case 1:
  1434. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1435. if ($oDataSource->Get('action_on_one') == 'update')
  1436. {
  1437. $oDestObj = $oDestSet->Fetch();
  1438. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1439. $this->Set('dest_id', $oDestObj->GetKey());
  1440. $this->Set('dest_class', get_class($oDestObj));
  1441. }
  1442. else
  1443. {
  1444. // assumed to be 'error'
  1445. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1446. $this->SetLastError('Found a match while expecting several');
  1447. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1448. }
  1449. break;
  1450. default:
  1451. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1452. if ($oDataSource->Get('action_on_multiple') == 'error')
  1453. {
  1454. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1455. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1456. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1457. }
  1458. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1459. {
  1460. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1461. }
  1462. else
  1463. {
  1464. // assumed to be 'take_first'
  1465. $oDestObj = $oDestSet->Fetch();
  1466. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1467. $this->Set('dest_id', $oDestObj->GetKey());
  1468. $this->Set('dest_class', get_class($oDestObj));
  1469. }
  1470. }
  1471. break;
  1472. case 'modified':
  1473. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1474. if ($oDestObj == null)
  1475. {
  1476. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1477. $this->SetLastError('Destination object deleted unexpectedly');
  1478. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1479. }
  1480. else
  1481. {
  1482. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, '', 'stats_nb_obj_updated_errors');
  1483. }
  1484. break;
  1485. default: // Do nothing in all other cases
  1486. }
  1487. }
  1488. /**
  1489. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1490. */
  1491. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1492. {
  1493. $aValueTrace = array();
  1494. try
  1495. {
  1496. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1497. {
  1498. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1499. if (!is_null($value))
  1500. {
  1501. $oDestObj->Set($sAttCode, $value);
  1502. $aValueTrace[] = "$sAttCode: $value";
  1503. }
  1504. }
  1505. // Really modified ?
  1506. if ($oDestObj->IsModified())
  1507. {
  1508. $oDestObj->DBUpdateTracked($oChange);
  1509. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1510. if ($sStatsCode != '')
  1511. {
  1512. $oStatLog->Inc($sStatsCode.'_updated');
  1513. }
  1514. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1515. }
  1516. else
  1517. {
  1518. $oStatLog->AddTrace('Unchanged object', $this);
  1519. if ($sStatsCode != '')
  1520. {
  1521. $oStatLog->Inc($sStatsCode.'_unchanged');
  1522. }
  1523. }
  1524. $this->Set('status_last_error', '');
  1525. $this->Set('status', 'synchronized');
  1526. }
  1527. catch(Exception $e)
  1528. {
  1529. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1530. $this->SetLastError('Unable to update destination object: ', $e);
  1531. $oStatLog->Inc($sStatsCodeError);
  1532. }
  1533. }
  1534. /**
  1535. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1536. */
  1537. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1538. {
  1539. $oDestObj = MetaModel::NewObject($sClass);
  1540. try
  1541. {
  1542. $aValueTrace = array();
  1543. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1544. {
  1545. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1546. if (!is_null($value))
  1547. {
  1548. $oDestObj->Set($sAttCode, $value);
  1549. $aValueTrace[] = "$sAttCode: $value";
  1550. }
  1551. }
  1552. $iNew = $oDestObj->DBInsertTracked($oChange);
  1553. $this->Set('dest_id', $oDestObj->GetKey());
  1554. $this->Set('dest_class', get_class($oDestObj));
  1555. $this->Set('status_dest_creator', true);
  1556. $this->Set('status_last_error', '');
  1557. $this->Set('status', 'synchronized');
  1558. $this->Set('info_creation_date', date('Y-m-d H:i:s'));
  1559. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1560. $oStatLog->Inc('stats_nb_obj_created');
  1561. }
  1562. catch(Exception $e)
  1563. {
  1564. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1565. $this->SetLastError('Unable to create destination object: ', $e);
  1566. $oStatLog->Inc('stats_nb_obj_created_errors');
  1567. }
  1568. }
  1569. /**
  1570. * Update the destination object with given values
  1571. */
  1572. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1573. {
  1574. try
  1575. {
  1576. if ($this->Get('dest_class') == '')
  1577. {
  1578. $this->SetLastError('No destination object to update');
  1579. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1580. }
  1581. else
  1582. {
  1583. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1584. foreach($aValues as $sAttCode => $value)
  1585. {
  1586. if (!MetaModel::IsValidAttCode(get_class($oDestObj), $sAttCode))
  1587. {
  1588. throw new Exception("Unknown attribute code '$sAttCode'");
  1589. }
  1590. $oDestObj->Set($sAttCode, $value);
  1591. }
  1592. $this->Set('info_last_modified', date('Y-m-d H:i:s'));
  1593. $oDestObj->DBUpdateTracked($oChange);
  1594. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1595. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1596. }
  1597. }
  1598. catch(Exception $e)
  1599. {
  1600. $this->SetLastError('Unable to update the destination object: ', $e);
  1601. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1602. }
  1603. }
  1604. /**
  1605. * Delete the destination object
  1606. */
  1607. public function DeleteDestObject($oChange, &$oStatLog)
  1608. {
  1609. if($this->Get('status_dest_creator'))
  1610. {
  1611. try
  1612. {
  1613. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1614. $oCheckDeletionPlan = new DeletionPlan();
  1615. if ($oDestObj->CheckToDelete($oCheckDeletionPlan))
  1616. {
  1617. $oActualDeletionPlan = new DeletionPlan();
  1618. $oDestObj->DBDeleteTracked($oChange, null, $oActualDeletionPlan);
  1619. $this->DBDeleteTracked($oChange);
  1620. $oStatLog->Inc('stats_nb_obj_deleted');
  1621. }
  1622. else
  1623. {
  1624. $sIssues = implode("\n", $oCheckDeletionPlan->GetIssues());
  1625. throw(new Exception($sIssues));
  1626. }
  1627. }
  1628. catch(Exception $e)
  1629. {
  1630. $this->SetLastError('Unable to delete the destination object: ', $e);
  1631. $this->Set('status', 'obsolete');
  1632. $this->DBUpdateTracked($oChange);
  1633. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1634. }
  1635. }
  1636. else
  1637. {
  1638. $this->DBDeleteTracked($oChange);
  1639. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1640. }
  1641. }
  1642. /**
  1643. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1644. * Note: sExtAttCode could be a standard attcode, or 'primary_key'
  1645. */
  1646. protected function GetValueFromExtData($sExtAttCode, $oSyncAtt, &$oStatLog)
  1647. {
  1648. // $aData should contain attributes defined either for reconciliation or create/update
  1649. $aData = $this->GetExtendedData();
  1650. if ($sExtAttCode == 'primary_key')
  1651. {
  1652. return $aData['primary_key'];
  1653. }
  1654. // $sExtAttCode is a valid attribute code
  1655. //
  1656. $sClass = $this->Get('base_class');
  1657. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExtAttCode);
  1658. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1659. {
  1660. $rawValue = $aData[$sExtAttCode];
  1661. if (is_null($rawValue))
  1662. {
  1663. // Null means "ignore" this attribute
  1664. return null;
  1665. }
  1666. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1667. if (!empty($sReconcAttCode))
  1668. {
  1669. $sRemoteClass = $oAttDef->GetTargetClass();
  1670. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1671. if ($oObj)
  1672. {
  1673. $retValue = $oObj->GetKey();
  1674. }
  1675. else
  1676. {
  1677. // Note: differs from null (in which case the value would be left unchanged)
  1678. $oStatLog->AddTrace("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1679. $retValue = 0;
  1680. }
  1681. }
  1682. else
  1683. {
  1684. $retValue = $rawValue;
  1685. }
  1686. }
  1687. elseif (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttLinkSet))
  1688. {
  1689. $rawValue = $aData[$sExtAttCode];
  1690. if (is_null($rawValue))
  1691. {
  1692. // Null means "ignore" this attribute
  1693. return null;
  1694. }
  1695. // MakeValueFromString() throws an exception in case of failure
  1696. $retValue = $oAttDef->MakeValueFromString($rawValue, $oSyncAtt->Get('row_separator'), $oSyncAtt->Get('attribute_separator'), $oSyncAtt->Get('value_separator'), $oSyncAtt->Get('attribute_qualifier'));
  1697. }
  1698. else
  1699. {
  1700. $aColumns = $oAttDef->GetImportColumns();
  1701. foreach($aColumns as $sColumn => $sFormat)
  1702. {
  1703. // In any case, a null column means "ignore this attribute"
  1704. //
  1705. if (is_null($aData[$sColumn]))
  1706. {
  1707. return null;
  1708. }
  1709. }
  1710. $retValue = $oAttDef->FromImportToValue($aData, $sExtAttCode);
  1711. }
  1712. return $retValue;
  1713. }
  1714. /**
  1715. * Maps the given context parameter name to the appropriate filter/search code for this class
  1716. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1717. * @return string Filter code, i.e. 'customer_id'
  1718. */
  1719. public static function MapContextParam($sContextParam)
  1720. {
  1721. if ($sContextParam == 'menu')
  1722. {
  1723. return null;
  1724. }
  1725. else
  1726. {
  1727. return $sContextParam;
  1728. }
  1729. }
  1730. /**
  1731. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1732. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1733. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1734. * To Be overridden by derived classes
  1735. * @param void
  1736. * @return String The desired higlight class for the object/row
  1737. */
  1738. public function GetHilightClass()
  1739. {
  1740. // Possible return values are:
  1741. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1742. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1743. }
  1744. public static function GetUIPage()
  1745. {
  1746. return '../synchro/replica.php';
  1747. }
  1748. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1749. {
  1750. // Object's details
  1751. //$this->DisplayBareHeader($oPage, $bEditMode);
  1752. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1753. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1754. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1755. $this->DisplayBareProperties($oPage, $bEditMode);
  1756. }
  1757. function DisplayBareProperties(WebPage $oPage, $bEditMode = false)
  1758. {
  1759. if ($bEditMode) return; // Not editable
  1760. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1761. $aDetails = array();
  1762. $sClass = get_class($this);
  1763. $oPage->add('<fieldset>');
  1764. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1765. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1766. foreach( $aZList as $sAttCode)
  1767. {
  1768. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1769. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1770. }
  1771. $oPage->Details($aDetails);
  1772. $oPage->add('</fieldset>');
  1773. $oPage->add('</td><td>');
  1774. $oPage->add('<fieldset>');
  1775. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  1776. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  1777. $sSQLTable = $oSource->GetDataTable();
  1778. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  1779. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  1780. 'data' => array('label' => 'Value', 'description' => ''));
  1781. $aRows = array();
  1782. foreach($aData as $sKey => $value)
  1783. {
  1784. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  1785. }
  1786. $oPage->Table($aHeaders, $aRows);
  1787. $oPage->add('</fieldset>');
  1788. $oPage->add('</td></tr></table>');
  1789. }
  1790. public function LoadExtendedDataFromTable($sSQLTable)
  1791. {
  1792. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  1793. $rQuery = CMDBSource::Query($sSQL);
  1794. return CMDBSource::FetchArray($rQuery);
  1795. }
  1796. }
  1797. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1798. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1799. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1800. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  1801. ?>