synchrodatasource.class.inc.php 79 KB

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