synchrodatasource.class.inc.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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 AttributeClass("scope_class", array("class_category"=>"bizmodel", "more_values"=>"", "sql"=>"scope_class", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  51. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  52. //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())));
  53. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  54. MetaModel::Init_AddAttribute(new AttributeString("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  55. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  56. 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())));
  57. 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())));
  58. 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())));
  59. 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())));
  60. 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())));
  61. 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())));
  62. // Format: '1 hour', '2 weeks', '3 hoursABCDEF'... Cf DateTime->Modify()
  63. MetaModel::Init_AddAttribute(new AttributeString("delete_policy_retention", array("allowed_values"=>null, "sql"=>"delete_policy_retention", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  64. 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())));
  65. MetaModel::Init_AddAttribute(new AttributeLinkedSet("status_list", array("linked_class"=>"SynchroLog", "ext_key_to_me"=>"sync_source_id", "allowed_values"=>null, "count_min"=>0, "count_max"=>0, "depends_on"=>array())));
  66. // Display lists
  67. MetaModel::Init_SetZListItems('details', array('name', 'description', 'scope_class', 'scope_restriction', 'status', 'user_id', 'full_load_periodicity', 'reconciliation_policy', 'action_on_zero', 'action_on_one', 'action_on_multiple', 'delete_policy', 'delete_policy_update', 'delete_policy_retention' /*'attribute_list'*/, 'status_list')); // Attributes to be displayed for the complete details
  68. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  69. // Search criteria
  70. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  71. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  72. }
  73. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  74. {
  75. if (!$this->IsNew())
  76. {
  77. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  78. $oAttributeSet = $this->Get('attribute_list');
  79. $aAttributes = array();
  80. while($oAttribute = $oAttributeSet->Fetch())
  81. {
  82. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  83. }
  84. $aAttribs = array(
  85. 'attcode' => array('label'=>'Attribute', 'description' => 'Field of the object'),
  86. 'reconciliation' => array('label'=>'Reconciliation ?', 'description' => 'Used for searching'),
  87. 'update' => array('label'=>'Update ?', 'description' => 'Used to update the object'),
  88. 'update_policy' => array('label'=>'Update Policy', 'description' => 'Behavior of the updated field'),
  89. );
  90. $aValues = array();
  91. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  92. {
  93. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  94. {
  95. if (isset($aAttributes[$sAttCode]))
  96. {
  97. $oAttribute = $aAttributes[$sAttCode];
  98. }
  99. else
  100. {
  101. $oAttribute = new SynchroAttribute();
  102. $oAttribute->Set('sync_source_id', $this->GetKey());
  103. $oAttribute->Set('attcode', $sAttCode);
  104. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  105. $oAttribute->Set('update', 1);
  106. $oAttribute->Set('update_policy', 'master_locked');
  107. }
  108. if (!$bEditMode)
  109. {
  110. // Read-only mode
  111. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  112. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  113. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  114. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  115. }
  116. else
  117. {
  118. // Read-only mode
  119. $sAttCode = $oAttribute->Get('attcode');
  120. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  121. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  122. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  123. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  124. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode'));
  125. $oAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  126. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  127. }
  128. $aValues[] = $aRow;
  129. }
  130. }
  131. $oPage->Table($aAttribs, $aValues);
  132. $this->DisplayStatusTab($oPage);
  133. }
  134. parent::DisplayBareRelations($oPage, $bEditMode);
  135. }
  136. /**
  137. * Displays the status (SynchroLog) of the datasource in a graphical manner
  138. * @param $oPage WebPage
  139. * @return void
  140. */
  141. protected function DisplayStatusTab(WebPage $oPage)
  142. {
  143. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  144. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  145. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  146. if ($oSetSynchroLog->Count() > 0)
  147. {
  148. $oLastLog = $oSetSynchroLog->Fetch();
  149. $sStartDate = $oLastLog->Get('start_date');
  150. $oLastLog->Get('stats_nb_replica_seen');
  151. if ($oLastLog->Get('status') == 'running')
  152. {
  153. // Still running !
  154. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  155. }
  156. else
  157. {
  158. $sEndDate = $oLastLog->Get('end_date');
  159. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  160. }
  161. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  162. // List all the log entries for the user to select
  163. $oPage->add('<h2>'.Dict::S('Core:Synchro:History').'</h2>');
  164. $oSetSynchroLog->Rewind();
  165. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  166. $sSelected = ' selected'; // First log is selected by default
  167. $sScript = "var aSynchroLog = {\n";
  168. while($oLog = $oSetSynchroLog->Fetch())
  169. {
  170. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->Get('start_date'));
  171. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  172. $sSelected = ''; // only the first log is selected by default
  173. $aData = $this->ProcessLog($oLog);
  174. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  175. }
  176. $sScript .= "end: 'Done'";
  177. $sScript .= "};\n";
  178. $sScript .= <<<EOF
  179. function UpdateSynoptics(id)
  180. {
  181. var aValues = aSynchroLog[id];
  182. for (var sKey in aValues)
  183. {
  184. $('#c_'+sKey).html(aValues[sKey]);
  185. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  186. $('#'+sKey).fadeTo("slow", fOpacity);
  187. }
  188. }
  189. EOF
  190. ;
  191. $oPage->add_script($sScript);
  192. $oPage->add('</select>');
  193. $oPage->add('</td><td style="vertical-align:top;">');
  194. // Now build the big "synoptics" view
  195. $aData = $this->ProcessLog($oLastLog);
  196. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  197. $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>");
  198. $oPage->add(
  199. <<<EOF
  200. <table class="synoptics">
  201. <tr class="synoptics_header">
  202. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  203. </tr>
  204. <tr>
  205. EOF
  206. );
  207. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  208. $oPage->add("</tr>\n<tr>");
  209. $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'));
  210. $oPage->add("</tr>\n<tr>");
  211. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  212. $oPage->add("</tr>\n<tr>");
  213. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  214. $oPage->add("</tr>\n<tr>");
  215. $oPage->add($this->HtmlBox('obj_disappeared_errors', $aData, '#C00'));
  216. $oPage->add("</tr>\n<tr>");
  217. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  218. $oPage->add("</tr>\n<tr>");
  219. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  220. $oPage->add("</tr>\n<tr>");
  221. $oPage->add($this->HtmlBox('obj_updated_errors', $aData, '#C00'));
  222. $oPage->add("</tr>\n<tr>");
  223. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  224. $oPage->add("</tr>\n<tr>");
  225. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  226. $oPage->add("</tr>\n<tr>");
  227. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  228. $oPage->add("</tr>\n<tr>");
  229. $oPage->add($this->HtmlBox('obj_new_errors', $aData, '#C00'));
  230. $oPage->add("</tr>\n</table>\n");
  231. $oPage->add('</td></tr></table>');
  232. }
  233. else
  234. {
  235. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  236. }
  237. }
  238. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '')
  239. {
  240. $iCount = $aData[$sId];
  241. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  242. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  243. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  244. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>$sLabel</td>";
  245. }
  246. protected function ProcessLog($oLastLog)
  247. {
  248. $aData = array(
  249. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  250. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  251. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  252. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  253. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  254. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  255. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  256. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  257. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  258. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  259. );
  260. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  261. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  262. $aData['repl_disappeared'] = $iDisappeared;
  263. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  264. $aData['obj_new_errors'] = $iNewErrors;
  265. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  266. $aData['repl_new'] = $iNew;
  267. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  268. $aData['repl_existing'] = $iExisting;
  269. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  270. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  271. $aData['repl_ignored'] = $iIgnored;
  272. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  273. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  274. return $aData;
  275. }
  276. public function GetAttributeFlags($sAttCode)
  277. {
  278. if (($sAttCode == 'scope_class') && (!$this->IsNew()))
  279. {
  280. return OPT_ATT_READONLY;
  281. }
  282. return parent::GetAttributeFlags($sAttCode);
  283. }
  284. public function UpdateObject($sFormPrefix = '')
  285. {
  286. parent::UpdateObject($sFormPrefix);
  287. // And now read the other post parameters...
  288. $oAttributeSet = $this->Get('attribute_list');
  289. $aAttributes = array();
  290. while($oAttribute = $oAttributeSet->Fetch())
  291. {
  292. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  293. }
  294. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  295. $aUpdate = utils::ReadPostedParam('update', array());
  296. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  297. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  298. // through all the writable attributes
  299. foreach($aUpdatePolicy as $sAttCode => $sValue)
  300. {
  301. if(!isset($aAttributes[$sAttCode]))
  302. {
  303. $oAttribute = new SynchroAttribute();
  304. $oAttribute->Set('sync_source_id', $this->GetKey());
  305. $oAttribute->Set('attcode', $sAttCode);
  306. }
  307. else
  308. {
  309. $oAttribute = $aAttributes[$sAttCode];
  310. }
  311. $bReconcile = 0;
  312. if (isset($aReconcile[$sAttCode]))
  313. {
  314. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  315. }
  316. $bUpdate = 0 ; // Default / initial value
  317. if (isset($aUpdate[$sAttCode]))
  318. {
  319. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  320. }
  321. $oAttribute->Set('reconcile', $bReconcile);
  322. $oAttribute->Set('update', $bUpdate);
  323. $oAttribute->Set('update_policy', $sValue);
  324. $oAttributeSet->AddObject($oAttribute);
  325. }
  326. $this->Set('attribute_list', $oAttributeSet);
  327. }
  328. public function GetTargetClass()
  329. {
  330. return $this->Get('scope_class');
  331. }
  332. public function GetDataTable()
  333. {
  334. $sName = strtolower($this->GetTargetClass());
  335. $sName = str_replace('\'"&@|\\/ ', '_', $sName); // Remove forbidden characters from the table name
  336. $sName .= '_'.$this->GetKey(); // Add a suffix for unicity
  337. $sTable = MetaModel::GetConfig()->GetDBSubName()."synchro_data_$sName"; // Add the prefix if any
  338. return $sTable;
  339. }
  340. /**
  341. * When inserting a new datasource object, also create the SynchroAttribute objects
  342. * for each field of the target class
  343. */
  344. protected function OnInsert()
  345. {
  346. // Create all the SynchroAttribute records
  347. $oAttributeSet = $this->Get('attribute_list');
  348. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  349. {
  350. if ($oAttDef->IsScalar() && $oAttDef->IsWritable())
  351. {
  352. $oAttribute = new SynchroAttribute();
  353. $oAttribute->Set('sync_source_id', $this->GetKey());
  354. $oAttribute->Set('attcode', $sAttCode);
  355. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  356. $oAttribute->Set('update', 1);
  357. $oAttribute->Set('update_policy', 'master_locked');
  358. $oAttributeSet->AddObject($oAttribute);
  359. }
  360. }
  361. $this->Set('attribute_list', $oAttributeSet);
  362. }
  363. /**
  364. * When the new datasource has been created, let's create the synchro_data table
  365. * that will hold the data records and the correspoding triggers which will maintain
  366. * both tables in sync
  367. */
  368. protected function AfterInsert()
  369. {
  370. parent::AfterInsert();
  371. $sTable = $this->GetDataTable();
  372. $aColumns = $this->GetSQLColumns();
  373. $aFieldDefs = array();
  374. // Allow '0', otherwise mysql will render an error when the id is not given
  375. // (the trigger is expected to set the value, but it is not executed soon enough)
  376. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  377. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  378. foreach($aColumns as $sColumn => $ColSpec)
  379. {
  380. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  381. }
  382. $aFieldDefs[] = "INDEX (id)";
  383. $aFieldDefs[] = "INDEX (primary_key)";
  384. $sFieldDefs = implode(', ', $aFieldDefs);
  385. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = innodb;";
  386. CMDBSource::Query($sCreateTable);
  387. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON $sTable";
  388. $sTriggerInsert .= " FOR EACH ROW";
  389. $sTriggerInsert .= " BEGIN";
  390. $sTriggerInsert .= " INSERT INTO priv_sync_replica (sync_source_id, status_last_seen, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  391. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  392. $sTriggerInsert .= " END;";
  393. CMDBSource::Query($sTriggerInsert);
  394. $aModified = array();
  395. foreach($aColumns as $sColumn => $ColSpec)
  396. {
  397. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  398. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  399. }
  400. $sIsModified = '('.implode(') OR (', $aModified).')';
  401. // Update the replica
  402. //
  403. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  404. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  405. // otherwise, the status is left as is
  406. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON $sTable";
  407. $sTriggerUpdate .= " FOR EACH ROW";
  408. $sTriggerUpdate .= " BEGIN";
  409. $sTriggerUpdate .= " IF @itopuser is null THEN";
  410. $sTriggerUpdate .= " UPDATE priv_sync_replica 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;";
  411. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  412. $sTriggerUpdate .= " END IF;";
  413. $sTriggerUpdate .= " END;";
  414. CMDBSource::Query($sTriggerUpdate);
  415. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON $sTable";
  416. $sTriggerInsert .= " FOR EACH ROW";
  417. $sTriggerInsert .= " BEGIN";
  418. $sTriggerInsert .= " DELETE FROM priv_sync_replica WHERE id = OLD.id;";
  419. $sTriggerInsert .= " END;";
  420. CMDBSource::Query($sTriggerInsert);
  421. }
  422. protected function AfterDelete()
  423. {
  424. parent::AfterDelete();
  425. $sTable = $this->GetDataTable();
  426. $sDropTable = "DROP TABLE `$sTable`";
  427. CMDBSource::Query($sDropTable);
  428. // TO DO - check that triggers get dropped with the table
  429. }
  430. /**
  431. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  432. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  433. * is used to determine which records are obsolete.
  434. * @param Hash $aTraces Debugs/Trace information, one or more entries per replica
  435. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  436. * @return void
  437. */
  438. public function Synchronize(&$aTraces, $oLastFullLoadStartDate = null)
  439. {
  440. // Create a change used for logging all the modifications/creations happening during the synchro
  441. $oMyChange = MetaModel::NewObject("CMDBChange");
  442. $oMyChange->Set("date", time());
  443. $sUserString = CMDBChange::GetCurrentUserName();
  444. $oMyChange->Set("userinfo", $sUserString);
  445. $iChangeId = $oMyChange->DBInsert();
  446. // Start logging this execution (stats + protection against reentrance)
  447. //
  448. $oStatLog = new SynchroLog();
  449. $oStatLog->Set('sync_source_id', $this->GetKey());
  450. $oStatLog->Set('start_date', time());
  451. $oStatLog->Set('status', 'running');
  452. $oStatLog->Set('stats_nb_replica_seen', 0);
  453. $oStatLog->Set('stats_nb_replica_total', 0);
  454. $oStatLog->Set('stats_nb_obj_deleted', 0);
  455. $oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  456. $oStatLog->Set('stats_nb_obj_obsoleted', 0);
  457. $oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  458. $oStatLog->Set('stats_nb_obj_created', 0);
  459. $oStatLog->Set('stats_nb_obj_created_errors', 0);
  460. $oStatLog->Set('stats_nb_obj_updated', 0);
  461. $oStatLog->Set('stats_nb_obj_updated_errors', 0);
  462. // $oStatLog->Set('stats_nb_replica_reconciled', 0);
  463. $oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  464. $oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  465. $oStatLog->Set('stats_nb_obj_new_updated', 0);
  466. $oStatLog->Set('stats_nb_obj_new_unchanged',0);
  467. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  468. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->GetKey()));
  469. $oStatLog->Set('stats_nb_replica_total', $oSetTotal->Count());
  470. $oStatLog->DBInsertTracked($oMyChange);
  471. try
  472. {
  473. $this->DoSynchronize($oLastFullLoadStartDate, $oMyChange, $oStatLog, $aTraces);
  474. $oStatLog->Set('end_date', time());
  475. $oStatLog->Set('status', 'completed');
  476. $oStatLog->DBUpdateTracked($oMyChange);
  477. }
  478. catch (SynchroExceptionNotStarted $e)
  479. {
  480. // Set information for reporting... but delete the object in DB
  481. $oStatLog->Set('end_date', time());
  482. $oStatLog->Set('status', 'error');
  483. $oStatLog->Set('last_error', $e->getMessage());
  484. $oStatLog->DBDeleteTracked($oMyChange);
  485. }
  486. catch (Exception $e)
  487. {
  488. $oStatLog->Set('end_date', time());
  489. $oStatLog->Set('status', 'error');
  490. $oStatLog->Set('last_error', $e->getMessage());
  491. $oStatLog->DBUpdateTracked($oMyChange);
  492. }
  493. return $oStatLog;
  494. }
  495. protected function DoSynchronize($oLastFullLoadStartDate, $oMyChange, &$oStatLog, &$aTraces)
  496. {
  497. if ($this->Get('status') == 'obsolete')
  498. {
  499. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  500. }
  501. if (!UserRights::IsAdministrator() && $this->Get('user_id') != UserRights::GetUserId())
  502. {
  503. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  504. }
  505. $sDeletePolicy = $this->Get('delete_policy');
  506. // Count the replicas
  507. $sSelectAll = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  508. $oSetAll = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAll), array() /* order by*/, array('source_id' => $this->GetKey()));
  509. $iCountAllReplicas = $oSetAll->Count();
  510. $oStatLog->Set('stats_nb_replica_total', $iCountAllReplicas);
  511. // Get all the replicas that were not seen in the last import and mark them as obsolete
  512. if ($oLastFullLoadStartDate == null)
  513. {
  514. // No previous import known, use the full_load_periodicity value... and the current date
  515. $oLastFullLoadStartDate = new DateTime(); // Now
  516. // TO DO: how do we support localization here ??
  517. $sLoadPeriodicity = trim($this->Get('full_load_periodicity'));
  518. if (strlen($sLoadPeriodicity) > 0)
  519. {
  520. $sInterval = '-'.$sLoadPeriodicity;
  521. // Note: the PHP doc states that Modify return FALSE in case of error
  522. // but, this is actually NOT the case
  523. // Therefore, I do compare before and after, considering that the
  524. // format is incorrect when the datetime remains unchanged
  525. $sBefore = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  526. $oLastFullLoadStartDate->Modify($sInterval);
  527. $sAfter = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  528. if ($sBefore == $sAfter)
  529. {
  530. throw new SynchroExceptionNotStarted("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  531. }
  532. }
  533. }
  534. $sLimitDate = $oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  535. $aTraces[] = "Limit Date: $sLimitDate";
  536. $sSelectToObsolete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  537. $oSetToObsolete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  538. if (($iCountAllReplicas > 10) && ($iCountAllReplicas == $oSetToObsolete->Count()))
  539. {
  540. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  541. }
  542. while($oReplica = $oSetToObsolete->Fetch())
  543. {
  544. switch ($sDeletePolicy)
  545. {
  546. case 'update':
  547. case 'update_then_delete':
  548. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be updated";
  549. $aToUpdate = array();
  550. $aToUpdate = explode(';', $this->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  551. foreach($aToUpdate as $sUpdateSpec)
  552. {
  553. $aUpdateSpec = explode(':', $sUpdateSpec);
  554. if (count($aUpdateSpec) == 2)
  555. {
  556. $sAttCode = $aUpdateSpec[0];
  557. $sValue = $aUpdateSpec[1];
  558. $aToUpdate[$sAttCode] = $sValue;
  559. }
  560. }
  561. $oReplica->UpdateDestObject($aToUpdate, $oMyChange, $oStatLog, $aTraces);
  562. $oReplica->Set('status', 'obsolete');
  563. $oReplica->DBUpdateTracked($oMyChange);
  564. break;
  565. case 'delete':
  566. default:
  567. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be DELETED";
  568. $oReplica->DeleteDestObject($oMyChange, $oStatLog, $aTraces);
  569. }
  570. }
  571. //Count "seen" objects
  572. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  573. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sLimitDate));
  574. $oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  575. // Get all the replicas that are 'new' or modified
  576. //
  577. // Get the list of SQL columns
  578. $sClass = $this->GetTargetClass();
  579. $aAttCodesExpected = array();
  580. $aAttCodesToReconcile = array();
  581. $aAttCodesToUpdate = array();
  582. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  583. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */);
  584. while ($oSyncAtt = $oSetAtt->Fetch())
  585. {
  586. if ($oSyncAtt->Get('update'))
  587. {
  588. $aAttCodesToUpdate[] = $oSyncAtt->Get('attcode');
  589. }
  590. if ($oSyncAtt->Get('reconcile'))
  591. {
  592. $aAttCodesToReconcile[] = $oSyncAtt->Get('attcode');
  593. }
  594. $aAttCodesExpected[] = $oSyncAtt->Get('attcode');
  595. }
  596. $aColumns = $this->GetSQLColumns($aAttCodesExpected);
  597. $aExtDataFields = array_keys($aColumns);
  598. $aExtDataFields[] = 'primary_key';
  599. $aExtDataSpec = array(
  600. 'table' => $this->GetDataTable(),
  601. 'join_key' => 'id',
  602. 'fields' => $aExtDataFields
  603. );
  604. // Get the list of reconciliation keys
  605. if ($this->Get('reconciliation_policy') == 'use_attributes')
  606. {
  607. $aReconciliationKeys = $aAttCodesToReconcile;
  608. }
  609. elseif ($this->Get('reconciliation_policy') == 'use_primary_key')
  610. {
  611. // Override the setings made at the attribute level !
  612. $aReconciliationKeys = array("primary_key");
  613. }
  614. $aTraces[] = "Reconciliation on: {".implode(', ', $aReconciliationKeys)."}";
  615. $aAttributes = array();
  616. foreach($aAttCodesToUpdate as $sAttCode)
  617. {
  618. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  619. if ($oAttDef->IsWritable() && $oAttDef->IsScalar())
  620. {
  621. $aAttributes[] = $sAttCode;
  622. }
  623. }
  624. $sSelectToSync = "SELECT SynchroReplica WHERE (status = 'new' OR status = 'modified') AND sync_source_id = :source_id";
  625. $oSetToSync = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, $aExtDataSpec, 0 /* limitCount */, 0 /* limitStart */);
  626. while($oReplica = $oSetToSync->Fetch())
  627. {
  628. $oReplica->Synchro($this, $aReconciliationKeys, $aAttributes, $oMyChange, $oStatLog, $aTraces);
  629. }
  630. // Get all the replicas that are to be deleted
  631. //
  632. if ($sDeletePolicy == 'update_then_delete')
  633. {
  634. $oDeletionDate = $oLastFullLoadStartDate;
  635. $sDeleteRetention = trim($this->Get('delete_policy_retention')); // MUST NOT BE NULL
  636. if (strlen($sDeleteRetention) > 0)
  637. {
  638. $sInterval = '-'.$sDeleteRetention;
  639. // Note: the PHP doc states that Modify return FALSE in case of error
  640. // but, this is actually NOT the case
  641. // Therefore, I do compare before and after, considering that the
  642. // format is incorrect when the datetime remains unchanged
  643. $sBefore = $oDeletionDate->Format('Y-m-d H:i:s');
  644. $oDeletionDate->Modify($sInterval);
  645. $sAfter = $oDeletionDate->Format('Y-m-d H:i:s');
  646. if ($sBefore == $sAfter)
  647. {
  648. throw new SynchroExceptionNotStarted("Data exchange: Wrong interval specification", array('interval' => $sInterval, 'source_id' => $this->GetKey()));
  649. }
  650. }
  651. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  652. $aTraces[] = "Deletion date: $sDeletionDate";
  653. $sSelectToDelete = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  654. $oSetToDelete = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->GetKey(), 'last_import' => $sDeletionDate));
  655. while($oReplica = $oSetToDelete->Fetch())
  656. {
  657. $aTraces[] = "Destination object: (dest_id:".$oReplica->Get('dest_id').") to be DELETED";
  658. $oReplica->DeleteDestObject($oMyChange, $oStatLog, $aTraces);
  659. }
  660. }
  661. }
  662. /**
  663. * Get the list of SQL columns corresponding to a particular list of attribute codes
  664. * Defaults to the whole list of columns for the current class
  665. */
  666. public function GetSQLColumns($aAttributeCodes = null)
  667. {
  668. $aColumns = array();
  669. $sClass = $this->GetTargetClass();
  670. if (is_null($aAttributeCodes))
  671. {
  672. $aAttributeCodes = array();
  673. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  674. {
  675. if ($sAttCode == 'finalclass') continue;
  676. $aAttributeCodes[] = $sAttCode;
  677. }
  678. }
  679. foreach($aAttributeCodes as $sAttCode)
  680. {
  681. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  682. foreach($oAttDef->GetSQLColumns() as $sField => $sDBFieldType)
  683. {
  684. $aColumns[$sField] = $sDBFieldType;
  685. }
  686. }
  687. return $aColumns;
  688. }
  689. public function IsRunning()
  690. {
  691. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  692. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  693. if ($oSet->Count() < 1)
  694. {
  695. $bRet = false;
  696. }
  697. else
  698. {
  699. $bRet = true;
  700. }
  701. return $bRet;
  702. }
  703. public function GetLatestLog()
  704. {
  705. $oLog = null;
  706. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  707. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  708. if ($oSet->Count() >= 1)
  709. {
  710. $oLog = $oSet->Fetch();
  711. }
  712. return $oLog;
  713. }
  714. // TO DO: remove if still unused
  715. /**
  716. * Retrieve from the log, the date of the last completed import
  717. * @return DateTime
  718. */
  719. public function GetLastCompletedImportDate()
  720. {
  721. $date = null;
  722. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  723. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  724. if ($oSet->Count() >= 1)
  725. {
  726. $oLog = $oSet->Fetch();
  727. $date = $oLog->Get('end_date');
  728. }
  729. else
  730. {
  731. // TO DO: remove trace
  732. echo "<p>No completed log found</p>\n";
  733. }
  734. return $date;
  735. }
  736. }
  737. class SynchroAttribute extends cmdbAbstractObject
  738. {
  739. public static function Init()
  740. {
  741. $aParams = array
  742. (
  743. "category" => "core/cmdb,view_in_gui",
  744. "key_type" => "autoincrement",
  745. "name_attcode" => "",
  746. "state_attcode" => "",
  747. "reconc_keys" => array(),
  748. "db_table" => "priv_sync_att",
  749. "db_key_field" => "id",
  750. "db_finalclass_field" => "",
  751. "display_template" => "",
  752. );
  753. MetaModel::Init_Params($aParams);
  754. MetaModel::Init_InheritAttributes();
  755. 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_AUTO, "depends_on"=>array())));
  756. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  757. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  758. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  759. 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())));
  760. // Display lists
  761. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  762. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  763. // Search criteria
  764. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  765. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  766. }
  767. }
  768. class SynchroAttExtKey extends SynchroAttribute
  769. {
  770. public static function Init()
  771. {
  772. $aParams = array
  773. (
  774. "category" => "core/cmdb,view_in_gui",
  775. "key_type" => "autoincrement",
  776. "name_attcode" => "",
  777. "state_attcode" => "",
  778. "reconc_keys" => array(),
  779. "db_table" => "priv_sync_att_extkey",
  780. "db_key_field" => "id",
  781. "db_finalclass_field" => "",
  782. "display_template" => "",
  783. );
  784. MetaModel::Init_Params($aParams);
  785. MetaModel::Init_InheritAttributes();
  786. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  787. // Display lists
  788. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  789. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  790. // Search criteria
  791. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  792. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  793. }
  794. }
  795. class SynchroAttLinkSet extends SynchroAttribute
  796. {
  797. public static function Init()
  798. {
  799. $aParams = array
  800. (
  801. "category" => "core/cmdb,view_in_gui",
  802. "key_type" => "autoincrement",
  803. "name_attcode" => "",
  804. "state_attcode" => "",
  805. "reconc_keys" => array(),
  806. "db_table" => "priv_sync_att_linkset",
  807. "db_key_field" => "id",
  808. "db_finalclass_field" => "",
  809. "display_template" => "",
  810. );
  811. MetaModel::Init_Params($aParams);
  812. MetaModel::Init_InheritAttributes();
  813. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  814. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  815. // Display lists
  816. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'row_separator', 'attribute_separator')); // Attributes to be displayed for the complete details
  817. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  818. // Search criteria
  819. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  820. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  821. }
  822. }
  823. //class SynchroLog extends Event
  824. class SynchroLog extends cmdbAbstractObject
  825. {
  826. public static function Init()
  827. {
  828. $aParams = array
  829. (
  830. "category" => "core/cmdb,view_in_gui",
  831. "key_type" => "autoincrement",
  832. "name_attcode" => "",
  833. "state_attcode" => "",
  834. "reconc_keys" => array(),
  835. "db_table" => "priv_sync_log",
  836. "db_key_field" => "id",
  837. "db_finalclass_field" => "",
  838. "display_template" => "",
  839. );
  840. MetaModel::Init_Params($aParams);
  841. MetaModel::Init_InheritAttributes();
  842. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  843. 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_AUTO, "depends_on"=>array())));
  844. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  845. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  846. 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())));
  847. 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())));
  848. 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())));
  849. 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())));
  850. 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())));
  851. 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())));
  852. 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())));
  853. 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())));
  854. 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())));
  855. 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())));
  856. 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())));
  857. // 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())));
  858. 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())));
  859. 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())));
  860. 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())));
  861. 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())));
  862. MetaModel::Init_AddAttribute(new AttributeString("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  863. // Display lists
  864. 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',
  865. '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')); // Attributes to be displayed for the complete details
  866. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  867. // Search criteria
  868. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  869. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  870. }
  871. /**
  872. * Increments a statistics counter
  873. */
  874. function Inc($sCode)
  875. {
  876. $this->Set($sCode, 1+$this->Get($sCode));
  877. }
  878. }
  879. class SynchroReplica extends DBObject
  880. {
  881. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  882. public static function Init()
  883. {
  884. $aParams = array
  885. (
  886. "category" => "core/cmdb,view_in_gui",
  887. "key_type" => "autoincrement",
  888. "name_attcode" => "",
  889. "state_attcode" => "",
  890. "reconc_keys" => array(),
  891. "db_table" => "priv_sync_replica",
  892. "db_key_field" => "id",
  893. "db_finalclass_field" => "",
  894. "display_template" => "",
  895. );
  896. MetaModel::Init_Params($aParams);
  897. MetaModel::Init_InheritAttributes();
  898. 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_AUTO, "depends_on"=>array())));
  899. MetaModel::Init_AddAttribute(new AttributeInteger("dest_id", array("allowed_values"=>null, "sql"=>"dest_id", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  900. MetaModel::Init_AddAttribute(new AttributeClass("dest_class", array("class_category"=>"bizmodel", "more_values"=>"", "sql"=>"dest_class", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  901. 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())));
  902. 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())));
  903. 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())));
  904. 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())));
  905. 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())));
  906. 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())));
  907. MetaModel::Init_AddAttribute(new AttributeDateTime("info_last_synchro", array("allowed_values"=>null, "sql"=>"info_last_synchro", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  908. // Display lists
  909. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'info_creation_date', 'info_last_modified', 'info_last_synchro')); // Attributes to be displayed for the complete details
  910. 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
  911. // Search criteria
  912. 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
  913. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  914. }
  915. public function DBInsert()
  916. {
  917. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  918. }
  919. // Overload the deletion -> the replica has been created by the mean of a trigger,
  920. // it will be deleted by the mean of a trigger too
  921. public function DBDelete()
  922. {
  923. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  924. $sTable = $oDataSource->GetDataTable();
  925. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  926. CMDBSource::Query($sSQL);
  927. $this->m_bIsInDB = false;
  928. $this->m_iKey = null;
  929. }
  930. public function SetLastError($sMessage, $oException = null)
  931. {
  932. if ($oException)
  933. {
  934. $sText = $sMessage.$oException->getMessage();
  935. }
  936. else
  937. {
  938. $sText = $sMessage;
  939. }
  940. if (strlen($sText) > 255)
  941. {
  942. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  943. }
  944. $this->Set('status_last_error', $sText);
  945. }
  946. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  947. {
  948. switch($this->Get('status'))
  949. {
  950. case 'new':
  951. $this->Set('status_dest_creator', false);
  952. // If needed, construct the query used for the reconciliation
  953. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  954. {
  955. foreach($aReconciliationKeys as $sFilterCode)
  956. {
  957. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  958. }
  959. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  960. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  961. }
  962. // Get the criterias for the search
  963. $aFilterValues = array();
  964. foreach($aReconciliationKeys as $sFilterCode)
  965. {
  966. $value = $this->GetValueFromExtData($sFilterCode);
  967. if (!is_null($value))
  968. {
  969. $aFilterValues[$sFilterCode] = $value;
  970. }
  971. else
  972. {
  973. // Reconciliation could not be performed - log and EXIT
  974. $aTraces[] = "Could not reconcile on null value: ".$sFilterCode;
  975. $this->SetLastError('Could not reconcile on null value: '.$sFilterCode);
  976. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  977. return;
  978. }
  979. }
  980. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  981. $iCount = $oDestSet->Count();
  982. $aConditions = array();
  983. foreach($aFilterValues as $sCode => $sValue)
  984. {
  985. $aConditions[] = $sCode.'='.$sValue;
  986. }
  987. $sConditionDesc = implode(' AND ', $aConditions);
  988. // How many objects match the reconciliation criterias
  989. switch($iCount)
  990. {
  991. case 0:
  992. $aTraces[] = "Nothing found on: $sConditionDesc";
  993. if ($oDataSource->Get('action_on_zero') == 'create')
  994. {
  995. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  996. }
  997. else // assumed to be 'error'
  998. {
  999. $aTraces[] = "Failed to reconcile (no match)";
  1000. $this->SetLastError('Could not find a match for reconciliation');
  1001. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1002. }
  1003. break;
  1004. case 1:
  1005. $aTraces[] = "Found 1 object on: $sConditionDesc";
  1006. if ($oDataSource->Get('action_on_one') == 'update')
  1007. {
  1008. $oDestObj = $oDestSet->Fetch();
  1009. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1010. $this->Set('dest_id', $oDestObj->GetKey());
  1011. $this->Set('dest_class', get_class($oDestObj));
  1012. }
  1013. else
  1014. {
  1015. // assumed to be 'error'
  1016. $aTraces[] = "Failed to reconcile (1 match)";
  1017. $this->SetLastError('Found a match while expecting several');
  1018. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1019. }
  1020. break;
  1021. default:
  1022. $aTraces[] = "Found $iCount objects on: $sConditionDesc";
  1023. if ($oDataSource->Get('action_on_multiple') == 'error')
  1024. {
  1025. $aTraces[] = "Failed to reconcile (N>1 matches)";
  1026. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1027. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1028. }
  1029. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1030. {
  1031. $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog, $aTraces);
  1032. }
  1033. else
  1034. {
  1035. // assumed to be 'take_first'
  1036. $oDestObj = $oDestSet->Fetch();
  1037. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1038. $this->Set('dest_id', $oDestObj->GetKey());
  1039. $this->Set('dest_class', get_class($oDestObj));
  1040. }
  1041. }
  1042. break;
  1043. case 'modified':
  1044. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1045. if ($oDestObj == null)
  1046. {
  1047. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1048. $this->SetLastError('Destination object deleted unexpectedly');
  1049. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1050. }
  1051. else
  1052. {
  1053. $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, $aTraces, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1054. }
  1055. break;
  1056. default: // Do nothing in all other cases
  1057. }
  1058. $this->DBUpdateTracked($oChange);
  1059. }
  1060. /**
  1061. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1062. */
  1063. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, &$aTraces, $sStatsCode, $sStatsCodeError)
  1064. {
  1065. $aValueTrace = array();
  1066. foreach($aAttributes as $sAttCode)
  1067. {
  1068. $value = $this->GetValueFromExtData($sAttCode);
  1069. if (!is_null($value))
  1070. {
  1071. $oDestObj->Set($sAttCode, $value);
  1072. $aValueTrace[] = "$sAttCode: $value";
  1073. }
  1074. }
  1075. try
  1076. {
  1077. // Really modified ?
  1078. if ($oDestObj->IsModified())
  1079. {
  1080. $oDestObj->DBUpdateTracked($oChange);
  1081. $aTraces[] = "Updated object ".$oDestObj->GetHyperLink()." (".implode(', ', $aValueTrace).")";
  1082. $oStatLog->Inc($sStatsCode.'_updated');
  1083. }
  1084. else
  1085. {
  1086. $aTraces[] = "Unchanged object ".$oDestObj->GetHyperLink()." (".implode(', ', $aValueTrace).")";
  1087. $oStatLog->Inc($sStatsCode.'_unchanged');
  1088. }
  1089. $this->Set('status_last_error', '');
  1090. $this->Set('status', 'synchronized');
  1091. }
  1092. catch(Exception $e)
  1093. {
  1094. $aTraces[] = "Failed to update destination object: {$e->getMessage()}";
  1095. $this->SetLastError('Unable to update destination object: ', $e);
  1096. $oStatLog->Inc($sStatsCodeError);
  1097. }
  1098. }
  1099. /**
  1100. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1101. */
  1102. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog, &$aTraces)
  1103. {
  1104. $oDestObj = MetaModel::NewObject($sClass);
  1105. try
  1106. {
  1107. $aValueTrace = array();
  1108. foreach($aAttributes as $sAttCode)
  1109. {
  1110. $value = $this->GetValueFromExtData($sAttCode);
  1111. if (!is_null($value))
  1112. {
  1113. $oDestObj->Set($sAttCode, $value);
  1114. $aValueTrace[] = "$sAttCode: $value";
  1115. }
  1116. }
  1117. $iNew = $oDestObj->DBInsertTracked($oChange);
  1118. $aTraces[] = "Created $sClass::$iNew (".implode(', ', $aValueTrace).")";
  1119. $this->Set('dest_id', $oDestObj->GetKey());
  1120. $this->Set('dest_class', get_class($oDestObj));
  1121. $this->Set('status_dest_creator', true);
  1122. $this->Set('status_last_error', '');
  1123. $this->Set('status', 'synchronized');
  1124. $oStatLog->Inc('stats_nb_obj_created');
  1125. }
  1126. catch(Exception $e)
  1127. {
  1128. $aTraces[] = "Failed to create $sClass ({$e->getMessage()})";
  1129. $this->SetLastError('Unable to create destination object: ', $e);
  1130. $oStatLog->Inc('stats_nb_obj_created_errors');
  1131. }
  1132. }
  1133. /**
  1134. * Update the destination object with given values
  1135. */
  1136. public function UpdateDestObject($aValues, $oChange, &$oStatLog, &$aTraces)
  1137. {
  1138. try
  1139. {
  1140. if ($this->Get('dest_class') == '')
  1141. {
  1142. $this->SetLastError('No destination object to update');
  1143. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1144. }
  1145. else
  1146. {
  1147. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1148. foreach($aValues as $sAttCode => $value)
  1149. {
  1150. $oDestObj->Set($sAttCode, $value);
  1151. }
  1152. $oDestObj->DBUpdateTracked($oChange);
  1153. $aTraces[] = "Replica id:".$this->GetKey()." (dest_id:".$this->Get('dest_id').") marked as obsolete";
  1154. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1155. }
  1156. }
  1157. catch(Exception $e)
  1158. {
  1159. $this->SetLastError('Unable to update the destination object: ', $e);
  1160. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1161. }
  1162. }
  1163. /**
  1164. * Delete the destination object
  1165. */
  1166. public function DeleteDestObject($oChange, &$oStatLog, &$aTraces)
  1167. {
  1168. if($this->Get('status_dest_creator'))
  1169. {
  1170. try
  1171. {
  1172. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1173. $oDestObj->DBDeleteTracked($oChange);
  1174. $this->DBDeleteTracked($oChange);
  1175. $oStatLog->Inc('stats_nb_obj_deleted');
  1176. }
  1177. catch(Exception $e)
  1178. {
  1179. $this->SetLastError('Unable to delete the destination object: ', $e);
  1180. $this->Set('status', 'obsolete');
  1181. $this->DBUpdateTracked($oChange);
  1182. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1183. }
  1184. }
  1185. else
  1186. {
  1187. $this->DBDeleteTracked($oChange);
  1188. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1189. }
  1190. }
  1191. /**
  1192. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1193. */
  1194. protected function GetValueFromExtData($sColumnName)
  1195. {
  1196. // $aData should contain attributes defined either for reconciliation or update
  1197. $aData = $this->GetExtendedData();
  1198. return $aData[$sColumnName];
  1199. }
  1200. }
  1201. // TO DO: finalize.... admins only ? which options ? troubleshoot WebPageMenuNode::__construct(.... sEnableClass...) ?
  1202. //if (UserRights::IsAdministrator())
  1203. {
  1204. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */);
  1205. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  1206. new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  1207. }
  1208. ?>