synchrodatasource.class.inc.php 59 KB

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