synchrodatasource.class.inc.php 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878
  1. <?php
  2. // Copyright (C) 2010-2015 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Data Exchange - synchronization with external applications (incoming data)
  20. *
  21. * @copyright Copyright (C) 2010-2015 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  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. MetaModel::Init_AddAttribute(new AttributeString("database_table_name", array("allowed_values"=>null, "sql"=>"database_table_name", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array(), "validation_pattern" => "^[A-Za-z0-9_]*$")));
  53. // Declared here for a future usage, but ignored so far
  54. MetaModel::Init_AddAttribute(new AttributeString("scope_restriction", array("allowed_values"=>null, "sql"=>"scope_restriction", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  55. //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())));
  56. // Format: seconds (int)
  57. MetaModel::Init_AddAttribute(new AttributeDuration("full_load_periodicity", array("allowed_values"=>null, "sql"=>"full_load_periodicity", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  58. // MetaModel::Init_AddAttribute(new AttributeString("reconciliation_list", array("allowed_values"=>null, "sql"=>"reconciliation_list", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  59. 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())));
  60. 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())));
  61. 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())));
  62. 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())));
  63. 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())));
  64. 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())));
  65. // Format: seconds (unsigned int)
  66. 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())));
  67. 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(), 'tracking_level' => LINKSET_TRACKING_DETAILS)));
  68. // Not used yet !
  69. 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())));
  70. 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())));
  71. // 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
  72. MetaModel::Init_AddAttribute(new AttributeString("url_application", array("allowed_values"=>null, "sql"=>"url_application", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  73. // Display lists
  74. MetaModel::Init_SetZListItems('details', array(
  75. 'col:0'=> array(
  76. 'fieldset:SynchroDataSource:Description' => array('name','description','status','scope_class','user_id','notify_contact_id','url_icon','url_application', 'database_table_name')),
  77. 'col:1'=> array(
  78. 'fieldset:SynchroDataSource:Reconciliation' => array('reconciliation_policy','action_on_zero','action_on_one','action_on_multiple'),
  79. 'fieldset:SynchroDataSource:Deletion' => array('user_delete_policy','full_load_periodicity','delete_policy','delete_policy_update','delete_policy_retention'))
  80. )
  81. );
  82. MetaModel::Init_SetZListItems('list', array('scope_class', 'status', 'user_id', 'full_load_periodicity')); // Attributes to be displayed for a list
  83. // Search criteria
  84. MetaModel::Init_SetZListItems('standard_search', array('name', 'status', 'scope_class', 'user_id')); // Criteria of the std search form
  85. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  86. }
  87. public function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  88. {
  89. if (!$this->IsNew())
  90. {
  91. $this->Set('database_table_name', $this->GetDataTable());
  92. }
  93. return parent::DisplayBareProperties($oPage, $bEditMode, $sPrefix, $aExtraParams);
  94. }
  95. public function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
  96. {
  97. if (!$this->IsNew())
  98. {
  99. $oPage->SetCurrentTab(Dict::S('Core:SynchroAttributes'));
  100. $oAttributeSet = $this->Get('attribute_list');
  101. $aAttributes = array();
  102. while($oAttribute = $oAttributeSet->Fetch())
  103. {
  104. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  105. }
  106. // Columns of the form
  107. $aAttribs = array();
  108. foreach(array('attcode', 'reconciliation', 'update', 'update_policy', 'reconciliation_attcode') as $s )
  109. {
  110. $aAttribs[$s] = array( 'label' => Dict::S("Core:SynchroAtt:$s"), "description" => Dict::S("Core:SynchroAtt:$s+"));
  111. }
  112. // Rows of the form
  113. $aValues = array();
  114. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  115. {
  116. if ($oAttDef->IsWritable())
  117. {
  118. if (isset($aAttributes[$sAttCode]))
  119. {
  120. $oAttribute = $aAttributes[$sAttCode];
  121. }
  122. else
  123. {
  124. if ($oAttDef->IsExternalKey())
  125. {
  126. $oAttribute = new SynchroAttExtKey();
  127. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  128. }
  129. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  130. {
  131. $oAttribute = new SynchroAttLinkSet();
  132. // Todo - add these settings into the form
  133. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  134. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  135. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  136. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  137. }
  138. elseif ($oAttDef->IsScalar())
  139. {
  140. $oAttribute = new SynchroAttribute();
  141. }
  142. else
  143. {
  144. $oAttribute = null;
  145. }
  146. if (!is_null($oAttribute))
  147. {
  148. $oAttribute->Set('sync_source_id', $this->GetKey());
  149. $oAttribute->Set('attcode', $sAttCode);
  150. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  151. $oAttribute->Set('update', 1);
  152. $oAttribute->Set('update_policy', 'master_locked');
  153. }
  154. }
  155. if (!is_null($oAttribute))
  156. {
  157. if (!$bEditMode)
  158. {
  159. // Read-only mode
  160. $aRow['reconciliation'] = $oAttribute->Get('reconcile') == 1 ? Dict::S('Core:SynchroReconcile:Yes') : Dict::S('Core:SynchroReconcile:No');
  161. $aRow['update'] = $oAttribute->Get('update') == 1 ? Dict::S('Core:SynchroUpdate:Yes') : Dict::S('Core:SynchroUpdate:No');
  162. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  163. $aRow['update_policy'] = $oAttribute->GetAsHTML('update_policy');
  164. if ($oAttDef->IsExternalKey())
  165. {
  166. $sReconciliationAttCode = $oAttribute->Get('reconciliation_attcode');
  167. switch($sReconciliationAttCode)
  168. {
  169. case '':
  170. $sDisplayReconciliationAttCode = Dict::S('Core:SynchroAttExtKey:ReconciliationById');
  171. break;
  172. default:
  173. $sDisplayReconciliationAttCode = MetaModel::GetLabel($oAttDef->GetTargetClass(), $sReconciliationAttCode);
  174. }
  175. $aRow['reconciliation_attcode'] = $sDisplayReconciliationAttCode;
  176. }
  177. else
  178. {
  179. $aRow['reconciliation_attcode'] = '&nbsp;';
  180. }
  181. }
  182. else
  183. {
  184. // Edit mode
  185. $sAttCode = $oAttribute->Get('attcode');
  186. $sChecked = $oAttribute->Get('reconcile') == 1 ? 'checked' : '';
  187. $aRow['reconciliation'] = "<input type=\"checkbox\" name=\"reconciliation[$sAttCode]\" $sChecked/>";
  188. $sChecked = $oAttribute->Get('update') == 1 ? 'checked' : '';
  189. $aRow['update'] = "<input type=\"checkbox\" name=\"update[$sAttCode]\" $sChecked/>";
  190. $aRow['attcode'] = MetaModel::GetLabel($this->GetTargetClass(), $oAttribute->Get('attcode')).' ('.$oAttribute->Get('attcode').')';
  191. $oUpdateAttDef = MetaModel::GetAttributeDef(get_class($oAttribute), 'update_policy');
  192. $aRow['update_policy'] = cmdbAbstractObject::GetFormElementForField($oPage, get_class($oAttribute), 'update_policy', $oUpdateAttDef, $oAttribute->Get('update_policy'), '', 'update_policy_'.$sAttCode, "[$sAttCode]");
  193. if ($oAttDef->IsExternalKey())
  194. {
  195. $aRow['reconciliation_attcode'] = $oAttribute->GetReconciliationFormElement($oAttDef->GetTargetClass(), "attr_reconciliation_attcode[$sAttCode]");
  196. }
  197. else
  198. {
  199. $aRow['reconciliation_attcode'] = '&nbsp;';
  200. }
  201. }
  202. $aValues[] = $aRow;
  203. }
  204. }
  205. }
  206. $oPage->p(Dict::Format('Class:SynchroDataSource:DataTable', $this->GetDataTable()));
  207. $oPage->Table($aAttribs, $aValues);
  208. $this->DisplayStatusTab($oPage);
  209. }
  210. parent::DisplayBareRelations($oPage, $bEditMode);
  211. }
  212. /**
  213. * Displays the status (SynchroLog) of the datasource in a graphical manner
  214. * @param $oPage WebPage
  215. * @return void
  216. */
  217. protected function DisplayStatusTab(WebPage $oPage)
  218. {
  219. $oPage->SetCurrentTab(Dict::S('Core:SynchroStatus'));
  220. $sSelectSynchroLog = 'SELECT SynchroLog WHERE sync_source_id = :source_id';
  221. $oSetSynchroLog = new CMDBObjectSet(DBObjectSearch::FromOQL($sSelectSynchroLog), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()));
  222. $oSetSynchroLog->SetLimit(100); // Display only the 100 latest runs
  223. if ($oSetSynchroLog->Count() > 0)
  224. {
  225. $oLastLog = $oSetSynchroLog->Fetch();
  226. $sStartDate = $oLastLog->GetAsHTML('start_date');
  227. $oLastLog->Get('stats_nb_replica_seen');
  228. $iLastLog = 0;
  229. $iDSid = $this->GetKey();
  230. if ($oLastLog->Get('status') == 'running')
  231. {
  232. // Still running !
  233. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroRunningStartedOn_Date', $sStartDate).'</h2>');
  234. }
  235. else
  236. {
  237. $sEndDate = $oLastLog->GetAsHTML('end_date');
  238. $iLastLog = $oLastLog->GetKey();
  239. $oPage->p('<h2>'.Dict::Format('Core:Synchro:SynchroEndedOn_Date', $sEndDate).'</h2>');
  240. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid";
  241. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  242. $iCountAllReplicas = $oSet->Count();
  243. $sAllReplicas = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllReplicas</a>";
  244. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_error !=''";
  245. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  246. $iCountAllErrors = $oSet->Count();
  247. $sAllErrors = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllErrors</a>";
  248. $sOQL = "SELECT SynchroReplica WHERE sync_source_id=$iDSid AND status_last_warning !=''";
  249. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL));
  250. $iCountAllWarnings = $oSet->Count();
  251. $sAllWarnings = "<a href=\"../synchro/replica.php?operation=oql&datasource=$iDSid&oql=$sOQL\">$iCountAllWarnings</a>";
  252. $oPage->p('<h2>'.Dict::Format('Core:Synchro:ListReplicas_AllReplicas_Errors_Warnings', $sAllReplicas, $sAllErrors, $sAllWarnings).'</h2>');
  253. }
  254. $oPage->add('<table class="synoptics"><tr><td style="color:#333;vertical-align:top">');
  255. // List all the log entries for the user to select
  256. $oPage->add('<h2 style="line-height:55px;">'.Dict::S('Core:Synchro:History').'</h2>');
  257. $oSetSynchroLog->Rewind();
  258. $oPage->add('<select size="25" onChange="UpdateSynoptics(this.value);">');
  259. $sSelected = ' selected'; // First log is selected by default
  260. $sScript = "var aSynchroLog = {\n";
  261. while($oLog = $oSetSynchroLog->Fetch())
  262. {
  263. $sLogTitle = Dict::Format('Core:SynchroLogTitle', $oLog->Get('status'), $oLog->GetEditValue('start_date'));
  264. $oPage->add('<option value="'.$oLog->GetKey().'"'.$sSelected.'>'.$sLogTitle.'</option>');
  265. $sSelected = ''; // only the first log is selected by default
  266. $aData = $this->ProcessLog($oLog);
  267. $sScript .= '"'.$oLog->GetKey().'": '.json_encode($aData).",\n";
  268. }
  269. $sScript .= "end: 'Done'";
  270. $sScript .= "};\n";
  271. $sScript .= <<<EOF
  272. var sLastLog = '$iLastLog';
  273. function ToggleSynoptics(sId, bShow)
  274. {
  275. if (bShow)
  276. {
  277. $(sId).show();
  278. }
  279. else
  280. {
  281. $(sId).hide();
  282. }
  283. }
  284. function UpdateSynoptics(id)
  285. {
  286. var aValues = aSynchroLog[id];
  287. if (aValues == undefined) return;
  288. for (var sKey in aValues)
  289. {
  290. $('#c_'+sKey).html(aValues[sKey]);
  291. var fOpacity = (aValues[sKey] == 0) ? 0.3 : 1;
  292. $('#'+sKey).fadeTo("slow", fOpacity);
  293. }
  294. //alert('id = '+id+', lastLog='+sLastLog+', id==sLastLog: '+(id==sLastLog)+' obj_updated_errors: '+aValues['obj_updated_errors']);
  295. if ( (id == sLastLog) && (aValues['obj_new_errors'] > 0) )
  296. {
  297. $('#new_errors_link').show();
  298. }
  299. else
  300. {
  301. $('#new_errors_link').hide();
  302. }
  303. if ( (id == sLastLog) && (aValues['obj_updated_errors'] > 0) )
  304. {
  305. $('#updated_errors_link').show();
  306. }
  307. else
  308. {
  309. $('#updated_errors_link').hide();
  310. }
  311. if ( (id == sLastLog) && (aValues['obj_disappeared_errors'] > 0) )
  312. {
  313. $('#disappeared_errors_link').show();
  314. }
  315. else
  316. {
  317. $('#disappeared_errors_link').hide();
  318. }
  319. ToggleSynoptics('#cw_obj_created_warnings', aValues['obj_created_warnings'] > 0);
  320. ToggleSynoptics('#cw_obj_new_updated_warnings', aValues['obj_new_updated_warnings'] > 0);
  321. ToggleSynoptics('#cw_obj_new_unchanged_warnings', aValues['obj_new_unchanged_warnings'] > 0);
  322. ToggleSynoptics('#cw_obj_updated_warnings', aValues['obj_updated_warnings'] > 0);
  323. ToggleSynoptics('#cw_obj_unchanged_warnings', aValues['obj_unchanged_warnings'] > 0);
  324. }
  325. EOF
  326. ;
  327. $oPage->add_script($sScript);
  328. $oPage->add('</select>');
  329. $oPage->add('</td><td style="vertical-align:top;">');
  330. // Now build the big "synoptics" view
  331. $aData = $this->ProcessLog($oLastLog);
  332. $sNbReplica = $this->GetIcon()."&nbsp;".Dict::Format('Core:Synchro:Nb_Replica', "<span id=\"c_nb_replica_total\">{$aData['nb_replica_total']}</span>");
  333. $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>");
  334. $oPage->add(
  335. <<<EOF
  336. <table class="synoptics">
  337. <tr class="synoptics_header">
  338. <td>$sNbReplica</td><td>&nbsp;</td><td>$sNbObjects</td>
  339. </tr>
  340. <tr>
  341. EOF
  342. );
  343. $sBaseOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->GetKey()." AND status_last_error!=''";
  344. $oPage->add($this->HtmlBox('repl_ignored', $aData, '#999').'<td colspan="2">&nbsp;</td>');
  345. $oPage->add("</tr>\n<tr>");
  346. $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'));
  347. $oPage->add("</tr>\n<tr>");
  348. $oPage->add($this->HtmlBox('obj_deleted', $aData, '#000'));
  349. $oPage->add("</tr>\n<tr>");
  350. $oPage->add($this->HtmlBox('obj_obsoleted', $aData, '#630'));
  351. $oPage->add("</tr>\n<tr>");
  352. $sOQL = urlencode($sBaseOQL." AND status='obsolete'");
  353. $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>"));
  354. $oPage->add("</tr>\n<tr>");
  355. $oPage->add($this->HtmlBox('repl_existing', $aData, '#093', 'rowspan="3"').'<td rowspan="3" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_unchanged', $aData, '#393'));
  356. $oPage->add("</tr>\n<tr>");
  357. $oPage->add($this->HtmlBox('obj_updated', $aData, '#3C3'));
  358. $oPage->add("</tr>\n<tr>");
  359. $sOQL = urlencode($sBaseOQL." AND status='modified'");
  360. $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>"));
  361. $oPage->add("</tr>\n<tr>");
  362. $oPage->add($this->HtmlBox('repl_new', $aData, '#339', 'rowspan="4"').'<td rowspan="4" class="arrow">=&gt;</td>'.$this->HtmlBox('obj_new_unchanged', $aData, '#393'));
  363. $oPage->add("</tr>\n<tr>");
  364. $oPage->add($this->HtmlBox('obj_new_updated', $aData, '#3C3'));
  365. $oPage->add("</tr>\n<tr>");
  366. $oPage->add($this->HtmlBox('obj_created', $aData, '#339'));
  367. $oPage->add("</tr>\n<tr>");
  368. $sOQL = urlencode($sBaseOQL." AND status='new'");
  369. $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>"));
  370. $oPage->add("</tr>\n</table>\n");
  371. $oPage->add('</td></tr></table>');
  372. $oPage->add_ready_script("UpdateSynoptics('$iLastLog')");
  373. }
  374. else
  375. {
  376. $oPage->p('<h2>'.Dict::S('Core:Synchro:NeverRun').'</h2>');
  377. }
  378. }
  379. protected function HtmlBox($sId, $aData, $sColor, $sHTMLAttribs = '', $sErrorLink = '')
  380. {
  381. $iCount = $aData[$sId];
  382. $sCount = "<span id=\"c_{$sId}\">$iCount</span>";
  383. $sLabel = Dict::Format('Core:Synchro:label_'.$sId, $sCount);
  384. $sOpacity = ($iCount==0) ? "opacity:0.3;" : "";
  385. if (isset($aData[$sId.'_warnings']))
  386. {
  387. $sLabel .= " <span id=\"cw_{$sId}_warnings\"><img src=\"../images/error.png\" style=\"vertical-align:middle\"/> (<span id=\"c_{$sId}_warnings\">".$aData[$sId.'_warnings']."</span>)</span>";
  388. }
  389. return "<td id=\"$sId\" style=\"background-color:$sColor;$sOpacity;\" {$sHTMLAttribs}>{$sLabel}{$sErrorLink}</td>";
  390. }
  391. protected function ProcessLog($oLastLog)
  392. {
  393. $aData = array(
  394. 'obj_deleted' => $oLastLog->Get('stats_nb_obj_deleted'),
  395. 'obj_obsoleted' => $oLastLog->Get('stats_nb_obj_obsoleted'),
  396. 'obj_disappeared_errors' => $oLastLog->Get('stats_nb_obj_obsoleted_errors') + $oLastLog->Get('stats_nb_obj_deleted_errors'),
  397. 'obj_disappeared_no_action' => $oLastLog->Get('stats_nb_replica_disappeared_no_action'),
  398. 'obj_updated' => $oLastLog->Get('stats_nb_obj_updated'),
  399. 'obj_updated_warnings' => $oLastLog->Get('stats_nb_obj_updated_warnings'),
  400. 'obj_updated_errors' => $oLastLog->Get('stats_nb_obj_updated_errors'),
  401. 'obj_new_updated' => $oLastLog->Get('stats_nb_obj_new_updated'),
  402. 'obj_new_updated_warnings' => $oLastLog->Get('stats_nb_obj_new_updated_warnings'),
  403. 'obj_new_unchanged' => $oLastLog->Get('stats_nb_obj_new_unchanged'),
  404. 'obj_created' => $oLastLog->Get('stats_nb_obj_created'),
  405. 'obj_created_warnings' => $oLastLog->Get('stats_nb_obj_created_warnings'),
  406. 'obj_created_errors' => $oLastLog->Get('stats_nb_obj_created_errors'),
  407. 'obj_unchanged_warnings' => $oLastLog->Get('stats_nb_obj_unchanged_warnings'),
  408. );
  409. $iReconciledErrors = $oLastLog->Get('stats_nb_replica_reconciled_errors');
  410. $iDisappeared = $aData['obj_disappeared_errors'] + $aData['obj_obsoleted'] + $aData['obj_deleted'] + $aData['obj_disappeared_no_action'];
  411. $aData['repl_disappeared'] = $iDisappeared;
  412. $iNewErrors = $aData['obj_created_errors'] + $oLastLog->Get('stats_nb_replica_reconciled_errors');
  413. $aData['obj_new_errors'] = $iNewErrors;
  414. $iNew = $aData['obj_created'] + $iNewErrors + $aData['obj_new_updated'] + $aData['obj_new_unchanged'];
  415. $aData['repl_new'] = $iNew;
  416. $iExisting = $oLastLog->Get('stats_nb_replica_seen') - $iNew;
  417. $aData['repl_existing'] = $iExisting;
  418. $aData['obj_unchanged'] = $iExisting - $aData['obj_updated'] - $aData['obj_updated_errors'];
  419. $iIgnored = $oLastLog->Get('stats_nb_replica_total') - $iNew - $iExisting - $iDisappeared;
  420. $aData['repl_ignored'] = $iIgnored;
  421. $aData['nb_obj_total'] = $iNew + $iExisting + $iDisappeared;
  422. $aData['nb_replica_total'] = $aData['nb_obj_total'] + $iIgnored;
  423. return $aData;
  424. }
  425. public function GetIcon($bImgTag = true, $sMoreStyles = '')
  426. {
  427. if ($this->Get('url_icon') == '') return MetaModel::GetClassIcon(get_class($this), $bImgTag);
  428. if ($bImgTag)
  429. {
  430. return "<img src=\"".$this->Get('url_icon')."\" style=\"vertical-align:middle;$sMoreStyles\"/>";
  431. }
  432. return $this->Get('url_icon');
  433. }
  434. /**
  435. * Get the actual hyperlink to the remote application for the given replica and dest object
  436. */
  437. public function GetApplicationUrl(DBObject $oDestObj, SynchroReplica $oReplica)
  438. {
  439. if ($this->Get('url_application') == '') return '';
  440. $aSearches = array();
  441. $aReplacements = array();
  442. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  443. {
  444. if ($oAttDef->IsScalar())
  445. {
  446. $aSearches[] = '$this->'.$sAttCode.'$';
  447. $aReplacements[] = $oDestObj->Get($sAttCode);
  448. }
  449. }
  450. $aData = $oReplica->LoadExtendedDataFromTable($this->GetDataTable());
  451. foreach($aData as $sColumn => $value)
  452. {
  453. $aSearches[] = '$replica->'.$sColumn.'$';
  454. $aReplacements[] = $value;
  455. }
  456. return str_replace($aSearches, $aReplacements, $this->Get('url_application'));
  457. }
  458. public function GetAttributeFlags($sAttCode, &$aReasons = array(), $sTargetState = '')
  459. {
  460. if ( (($sAttCode == 'scope_class') || ($sAttCode == 'database_table_name')) && (!$this->IsNew()))
  461. {
  462. return OPT_ATT_READONLY;
  463. }
  464. return parent::GetAttributeFlags($sAttCode, $aReasons, $sTargetState);
  465. }
  466. public function UpdateObjectFromPostedForm($sFormPrefix = '', $sAttList = null, $sTargetState = '')
  467. {
  468. parent::UpdateObjectFromPostedForm($sFormPrefix, $sAttList, $sTargetState);
  469. // And now read the other post parameters...
  470. $oAttributeSet = $this->Get('attribute_list');
  471. $aAttributes = array();
  472. while($oAttribute = $oAttributeSet->Fetch())
  473. {
  474. $aAttributes[$oAttribute->Get('attcode')] = $oAttribute;
  475. }
  476. $aReconcile = utils::ReadPostedParam('reconciliation', array());
  477. $aUpdate = utils::ReadPostedParam('update', array());
  478. $aUpdatePolicy = utils::ReadPostedParam('attr_update_policy', array());
  479. $aReconciliation = utils::ReadPostedParam('attr_reconciliation_attcode', array());
  480. // update_policy cannot be empty, so there is one entry per attribute, use this to iterate
  481. // through all the writable attributes
  482. foreach($aUpdatePolicy as $sAttCode => $sValue)
  483. {
  484. if(!isset($aAttributes[$sAttCode]))
  485. {
  486. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  487. }
  488. else
  489. {
  490. $oAttribute = $aAttributes[$sAttCode];
  491. }
  492. $bReconcile = 0;
  493. if (isset($aReconcile[$sAttCode]))
  494. {
  495. $bReconcile = $aReconcile[$sAttCode] == 'on' ? 1 : 0;
  496. }
  497. $bUpdate = 0 ; // Default / initial value
  498. if (isset($aUpdate[$sAttCode]))
  499. {
  500. $bUpdate = $aUpdate[$sAttCode] == 'on' ? 1 : 0;
  501. }
  502. $oAttribute->Set('reconcile', $bReconcile);
  503. $oAttribute->Set('update', $bUpdate);
  504. $oAttribute->Set('update_policy', $sValue);
  505. if ($oAttribute instanceof SynchroAttExtKey)
  506. {
  507. $oAttribute->Set('reconciliation_attcode', $aReconciliation[$sAttCode]);
  508. }
  509. elseif ($oAttribute instanceof SynchroAttLinkSet)
  510. {
  511. }
  512. $oAttributeSet->AddObject($oAttribute);
  513. }
  514. $this->Set('attribute_list', $oAttributeSet);
  515. }
  516. /**
  517. * Creates a new SynchroAttXXX object in memory with the default values
  518. */
  519. protected function CreateSynchroAtt($sAttCode)
  520. {
  521. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  522. if ($oAttDef->IsExternalKey())
  523. {
  524. $oAttribute = new SynchroAttExtKey();
  525. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  526. }
  527. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  528. {
  529. $oAttribute = new SynchroAttLinkSet();
  530. // Todo - set those value from the form
  531. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  532. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  533. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  534. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  535. }
  536. else
  537. {
  538. $oAttribute = new SynchroAttribute();
  539. }
  540. $oAttribute->Set('sync_source_id', $this->GetKey());
  541. $oAttribute->Set('attcode', $sAttCode);
  542. $oAttribute->Set('reconcile', 0);
  543. $oAttribute->Set('update', 0);
  544. $oAttribute->Set('update_policy', 'master_locked');
  545. return $oAttribute;
  546. }
  547. /**
  548. * Overload the standard behavior
  549. */
  550. public function ComputeValues()
  551. {
  552. parent::ComputeValues();
  553. if ($this->IsNew())
  554. {
  555. // Compute the database_table_name
  556. $sDataTable = $this->Get('database_table_name');
  557. if (!empty($sDataTable))
  558. {
  559. $this->Set('database_table_name', $this->ComputeDataTableName());
  560. }
  561. // When inserting a new datasource object, also create the SynchroAttribute objects
  562. // for each field of the target class
  563. // Create all the SynchroAttribute records
  564. $oAttributeSet = $this->Get('attribute_list');
  565. if ($oAttributeSet->Count() == 0)
  566. {
  567. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode=>$oAttDef)
  568. {
  569. if ($oAttDef->IsWritable())
  570. {
  571. $oAttDef = MetaModel::GetAttributeDef($this->GetTargetClass(), $sAttCode);
  572. if ($oAttDef->IsExternalKey())
  573. {
  574. $oAttribute = new SynchroAttExtKey();
  575. $oAttribute->Set('reconciliation_attcode', ''); // Blank means by pkey
  576. }
  577. elseif ($oAttDef->IsLinkSet() && $oAttDef->IsIndirect())
  578. {
  579. $oAttribute = new SynchroAttLinkSet();
  580. // Todo - set those value from the form
  581. $oAttribute->Set('row_separator', MetaModel::GetConfig()->Get('link_set_item_separator'));
  582. $oAttribute->Set('attribute_separator', MetaModel::GetConfig()->Get('link_set_attribute_separator'));
  583. $oAttribute->Set('value_separator', MetaModel::GetConfig()->Get('link_set_value_separator'));
  584. $oAttribute->Set('attribute_qualifier', MetaModel::GetConfig()->Get('link_set_attribute_qualifier'));
  585. }
  586. elseif ($oAttDef->IsScalar())
  587. {
  588. $oAttribute = new SynchroAttribute();
  589. }
  590. else
  591. {
  592. $oAttribute = null;
  593. }
  594. if (!is_null($oAttribute))
  595. {
  596. $oAttribute->Set('sync_source_id', $this->GetKey());
  597. $oAttribute->Set('attcode', $sAttCode);
  598. $oAttribute->Set('reconcile', MetaModel::IsReconcKey($this->GetTargetClass(), $sAttCode) ? 1 : 0);
  599. $oAttribute->Set('update', 1);
  600. $oAttribute->Set('update_policy', 'master_locked');
  601. $oAttributeSet->AddObject($oAttribute);
  602. }
  603. }
  604. }
  605. $this->Set('attribute_list', $oAttributeSet);
  606. }
  607. }
  608. else
  609. {
  610. $sDataTable = $this->Get('database_table_name');
  611. if (empty($sDataTable))
  612. {
  613. $this->Set('database_table_name', $this->ComputeDataTableName());
  614. }
  615. }
  616. }
  617. public function DoCheckToWrite()
  618. {
  619. parent::DoCheckToWrite();
  620. // Check that there is at least one reconciliation key defined
  621. if ($this->Get('reconciliation_policy') == 'use_attributes')
  622. {
  623. $oSet = $this->Get('attribute_list');
  624. $oSynchroAttributeList = $oSet->ToArray();
  625. $bReconciliationKey = false;
  626. foreach($oSynchroAttributeList as $oSynchroAttribute)
  627. {
  628. if ($oSynchroAttribute->Get('reconcile') == 1)
  629. {
  630. $bReconciliationKey = true; // At least one key is defined
  631. break;
  632. }
  633. }
  634. if (!$bReconciliationKey)
  635. {
  636. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:AtLeastOneReconciliationKeyMustBeSpecified');
  637. }
  638. }
  639. // If 'update_then_delete' is specified there must be a delete_retention_period
  640. if (($this->Get('delete_policy') == 'update_then_delete') && ($this->Get('delete_policy_retention') == 0))
  641. {
  642. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeleteRetentionDurationMustBeSpecified');
  643. }
  644. // If update is specified, then something to update must be defined
  645. if ((($this->Get('delete_policy') == 'update_then_delete') || ($this->Get('delete_policy') == 'update'))
  646. && ($this->Get('delete_policy_update') == ''))
  647. {
  648. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DeletePolicyUpdateMustBeSpecified');
  649. }
  650. // When creating the data source with a specified database_table_name, this table must NOT exist
  651. if ($this->IsNew())
  652. {
  653. $sDataTable = $this->GetDataTable();
  654. if (!empty($sDataTable) && CMDBSource::IsTable($this->GetDataTable()))
  655. {
  656. // Hmm, the synchro_data_xxx table already exists !!
  657. $this->m_aCheckIssues[] = Dict::Format('Class:SynchroDataSource/Error:DataTableAlreadyExists', $this->GetDataTable());
  658. }
  659. }
  660. }
  661. public function GetTargetClass()
  662. {
  663. return $this->Get('scope_class');
  664. }
  665. public function GetDataTable()
  666. {
  667. $sTable = $this->Get('database_table_name');
  668. if (empty($sTable))
  669. {
  670. $sTable = $this->ComputeDataTableName();
  671. }
  672. return $sTable;
  673. }
  674. protected function ComputeDataTableName()
  675. {
  676. $sDBTableName = $this->Get('database_table_name');
  677. if (empty($sDBTableName))
  678. {
  679. $sDBTableName = strtolower($this->GetTargetClass());
  680. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  681. $sDBTableName .= '_'.$this->GetKey(); // Add a suffix for unicity
  682. }
  683. else
  684. {
  685. $sDBTableName = preg_replace('/[^A-za-z0-9_]/', '_', $sDBTableName); // Remove forbidden characters from the table name
  686. }
  687. $sPrefix = MetaModel::GetConfig()->GetDBSubName()."synchro_data_";
  688. if (strpos($sDBTableName, $sPrefix) !== 0)
  689. {
  690. $sDBTableName = $sPrefix.$sDBTableName;
  691. }
  692. return $sDBTableName;
  693. }
  694. /**
  695. * When the new datasource has been created, let's create the synchro_data table
  696. * that will hold the data records and the correspoding triggers which will maintain
  697. * both tables in sync
  698. */
  699. protected function AfterInsert()
  700. {
  701. parent::AfterInsert();
  702. $sTable = $this->GetDataTable();
  703. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  704. $aColumns = $this->GetSQLColumns();
  705. $aFieldDefs = array();
  706. // Allow '0', otherwise mysql will render an error when the id is not given
  707. // (the trigger is expected to set the value, but it is not executed soon enough)
  708. $aFieldDefs[] = "id INTEGER(11) NOT NULL DEFAULT 0 ";
  709. $aFieldDefs[] = "`primary_key` VARCHAR(255) NULL DEFAULT NULL";
  710. foreach($aColumns as $sColumn => $ColSpec)
  711. {
  712. $aFieldDefs[] = "`$sColumn` $ColSpec NULL DEFAULT NULL";
  713. }
  714. $aFieldDefs[] = "INDEX (id)";
  715. $aFieldDefs[] = "INDEX (primary_key)";
  716. $sFieldDefs = implode(', ', $aFieldDefs);
  717. $sCreateTable = "CREATE TABLE `$sTable` ($sFieldDefs) ENGINE = ".MYSQL_ENGINE." CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
  718. CMDBSource::Query($sCreateTable);
  719. $aTriggers = $this->GetTriggersDefinition();
  720. foreach($aTriggers as $key => $sTriggerSQL)
  721. {
  722. CMDBSource::Query($sTriggerSQL);
  723. }
  724. $sDataTable = $this->Get('database_table_name');
  725. if (empty($sDataTable))
  726. {
  727. $this->Set('database_table_name', $this->ComputeDataTableName());
  728. $this->DBUpdate();
  729. }
  730. }
  731. /**
  732. * Gets the definitions of the 3 triggers: before insert, before update and after delete
  733. * @return array An array with 3 entries, one for each of the SQL queries
  734. */
  735. protected function GetTriggersDefinition()
  736. {
  737. $sTable = $this->GetDataTable();
  738. $sReplicaTable = MetaModel::DBGetTable('SynchroReplica');
  739. $aColumns = $this->GetSQLColumns();
  740. $aResult = array();
  741. $sTriggerInsert = "CREATE TRIGGER `{$sTable}_bi` BEFORE INSERT ON `$sTable`";
  742. $sTriggerInsert .= " FOR EACH ROW";
  743. $sTriggerInsert .= " BEGIN";
  744. $sTriggerInsert .= " INSERT INTO `{$sReplicaTable}` (`sync_source_id`, `status_last_seen`, `status`) VALUES ({$this->GetKey()}, NOW(), 'new');";
  745. $sTriggerInsert .= " SET NEW.id = LAST_INSERT_ID();";
  746. $sTriggerInsert .= " END;";
  747. $aResult['bi'] = $sTriggerInsert;
  748. $aModified = array();
  749. foreach($aColumns as $sColumn => $ColSpec)
  750. {
  751. // <=> is a null-safe 'EQUALS' operator (there is no equivalent for "DIFFERS FROM")
  752. $aModified[] = "NOT(NEW.`$sColumn` <=> OLD.`$sColumn`)";
  753. }
  754. $sIsModified = '('.implode(') OR (', $aModified).')';
  755. // Update the replica
  756. //
  757. // status is forced to "new" if the replica was obsoleted directly from the state "new" (dest_id = null)
  758. // otherwise, if status was either 'obsolete' or 'synchronized' it is turned into 'modified' or 'synchronized' depending on the changes
  759. // otherwise, the status is left as is
  760. $sTriggerUpdate = "CREATE TRIGGER `{$sTable}_bu` BEFORE UPDATE ON `$sTable`";
  761. $sTriggerUpdate .= " FOR EACH ROW";
  762. $sTriggerUpdate .= " BEGIN";
  763. $sTriggerUpdate .= " IF @itopuser is null THEN";
  764. $sTriggerUpdate .= " UPDATE `{$sReplicaTable}` SET status_last_seen = NOW(), `status` = IF(`status` = 'obsolete', IF(`dest_id` IS NULL, 'new', 'modified'), IF(`status` IN ('synchronized') AND ($sIsModified), 'modified', `status`)) WHERE sync_source_id = {$this->GetKey()} AND id = OLD.id;";
  765. $sTriggerUpdate .= " SET NEW.id = OLD.id;"; // make sure this id won't change
  766. $sTriggerUpdate .= " END IF;";
  767. $sTriggerUpdate .= " END;";
  768. $aResult['bu'] = $sTriggerUpdate;
  769. $sTriggerDelete = "CREATE TRIGGER `{$sTable}_ad` AFTER DELETE ON `$sTable`";
  770. $sTriggerDelete .= " FOR EACH ROW";
  771. $sTriggerDelete .= " BEGIN";
  772. $sTriggerDelete .= " DELETE FROM `{$sReplicaTable}` WHERE id = OLD.id;";
  773. $sTriggerDelete .= " END;";
  774. $aResult['ad'] = $sTriggerDelete;
  775. return $aResult;
  776. }
  777. protected function AfterDelete()
  778. {
  779. parent::AfterDelete();
  780. $sTable = $this->GetDataTable();
  781. $sDropTable = "DROP TABLE `$sTable`";
  782. CMDBSource::Query($sDropTable);
  783. // TO DO - check that triggers get dropped with the table
  784. }
  785. /**
  786. * Checks if the data source definition is consistent with the schema of the target class
  787. * @param $bDiagnostics boolean True to only diagnose the consistency, false to actually apply some changes
  788. * @param $bVerbose boolean True to get some information in the std output (echo)
  789. * @return bool Whether or not the database needs fixing for this data source
  790. */
  791. public function CheckDBConsistency($bDiagnostics, $bVerbose, $oChange = null)
  792. {
  793. $bFixNeeded = false;
  794. $bTriggerRebuildNeeded = false;
  795. $aMissingFields = array();
  796. $oAttributeSet = $this->Get('attribute_list');
  797. $aAttributes = array();
  798. while($oAttribute = $oAttributeSet->Fetch())
  799. {
  800. $sAttCode = $oAttribute->Get('attcode');
  801. if (MetaModel::IsValidAttCode($this->GetTargetClass(), $sAttCode))
  802. {
  803. $aAttributes[$sAttCode] = $oAttribute;
  804. }
  805. else
  806. {
  807. // Old field remaining
  808. $bTriggerRebuildNeeded = true;
  809. if ($bVerbose)
  810. {
  811. echo "Irrelevant field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be removed.\n";
  812. }
  813. $bFixNeeded = true;
  814. if (!$bDiagnostics)
  815. {
  816. // Fix the issue
  817. $oAttribute->DBDelete();
  818. }
  819. }
  820. }
  821. $sTable = $this->GetDataTable();
  822. foreach($this->ListTargetAttributes() as $sAttCode=>$oAttDef)
  823. {
  824. if (!isset($aAttributes[$sAttCode]))
  825. {
  826. $bFixNeeded = true;
  827. $aMissingFields[] = $sAttCode;
  828. $bTriggerRebuildNeeded = true;
  829. // New field missing...
  830. if ($bVerbose)
  831. {
  832. echo "Missing field description for the field '$sAttCode', for the data synchro task ".$this->GetName()." (".$this->GetKey()."), will be created with default values.\n";
  833. }
  834. if (!$bDiagnostics)
  835. {
  836. // Fix the issue
  837. $oAttribute = $this->CreateSynchroAtt($sAttCode);
  838. $oAttribute->DBInsert();
  839. }
  840. }
  841. else
  842. {
  843. $aColumns = $this->GetSQLColumns(array($sAttCode));
  844. foreach($aColumns as $sColName => $sColumnDef)
  845. {
  846. $bOneColIsMissing = false;
  847. if (!CMDBSource::IsField($sTable, $sColName))
  848. {
  849. $bFixNeeded = true;
  850. $bOneColIsMissing = true;
  851. if ($bVerbose)
  852. {
  853. if (count($aColumns) > 1)
  854. {
  855. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  856. }
  857. else
  858. {
  859. echo "Missing column '$sColName', in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  860. }
  861. }
  862. }
  863. else if (strcasecmp(CMDBSource::GetFieldType($sTable, $sColName), $sColumnDef) != 0)
  864. {
  865. $bFixNeeded = true;
  866. $bOneColIsMissing = true;
  867. if (count($aColumns) > 1)
  868. {
  869. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The columns '".implode("', '", $aColumns )." will be re-created.'.\n";
  870. }
  871. else
  872. {
  873. echo "Incorrect column '$sColName' (".CMDBSource::GetFieldType($sTable, $sColName)." instead of ".$sColumnDef."), in the table '$sTable' for the data synchro task ".$this->GetName()." (".$this->GetKey()."). The column '$sColName' will be added.\n";
  874. }
  875. }
  876. if ($bOneColIsMissing)
  877. {
  878. $bTriggerRebuildNeeded = true;
  879. $aMissingFields[] = $sAttCode;
  880. }
  881. }
  882. }
  883. }
  884. $sDBName = MetaModel::GetConfig()->GetDBName();
  885. try
  886. {
  887. // Note: as per the MySQL documentation, using information_schema behaves exactly like SHOW TRIGGERS (user privileges)
  888. // and this is in fact the recommended way for better portability
  889. $iTriggerCount = CMDBSource::QueryToScalar("select count(*) from information_schema.triggers where EVENT_OBJECT_SCHEMA='$sDBName' and EVENT_OBJECT_TABLE='$sTable'");
  890. }
  891. catch (Exception $e)
  892. {
  893. if ($bVerbose)
  894. {
  895. echo "Failed to investigate on the synchro triggers (skipping the check): ".$e->getMessage().".\n";
  896. }
  897. // Ignore this error: consider that the trigger are there
  898. $iTriggerCount = 3;
  899. }
  900. if ($iTriggerCount < 3)
  901. {
  902. $bFixNeeded = true;
  903. $bTriggerRebuildNeeded = true;
  904. if ($bVerbose)
  905. {
  906. echo "Missing trigger(s) for the data synchro task ".$this->GetName()." (table {$sTable}).\n";
  907. }
  908. }
  909. $aRepairQueries = array();
  910. if (count($aMissingFields) > 0)
  911. {
  912. // The structure of the table needs adjusting
  913. $aColumns = $this->GetSQLColumns($aMissingFields);
  914. $aFieldDefs = array();
  915. foreach($aColumns as $sAttCode => $sColumnDef)
  916. {
  917. if (CMDBSource::IsField($sTable, $sAttCode))
  918. {
  919. $aRepairQueries[] = "ALTER TABLE `$sTable` CHANGE `$sAttCode` `$sAttCode` $sColumnDef";
  920. }
  921. else
  922. {
  923. $aFieldDefs[] = "`$sAttCode` $sColumnDef";
  924. }
  925. }
  926. if (count($aFieldDefs) > 0)
  927. {
  928. $aRepairQueries[] = "ALTER TABLE `$sTable` ADD (".implode(',', $aFieldDefs).");";
  929. }
  930. if ($bDiagnostics)
  931. {
  932. if ($bVerbose)
  933. {
  934. echo "The structure of the table $sTable for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be altered (missing or incorrect fields: ".implode(',', $aMissingFields).").\n";
  935. }
  936. }
  937. }
  938. // Repair the triggers
  939. // Must be done after updating the columns because MySQL does check the validity of the query found into the procedure!
  940. if ($bTriggerRebuildNeeded)
  941. {
  942. // The triggers as well must be adjusted
  943. $aTriggersDefs = $this->GetTriggersDefinition();
  944. $aTriggerRepair = array();
  945. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bi`;";
  946. $aTriggerRepair[] = $aTriggersDefs['bi'];
  947. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_bu`;";
  948. $aTriggerRepair[] = $aTriggersDefs['bu'];
  949. $aTriggerRepair[] = "DROP TRIGGER IF EXISTS `{$sTable}_ad`;";
  950. $aTriggerRepair[] = $aTriggersDefs['ad'];
  951. if ($bDiagnostics)
  952. {
  953. if ($bVerbose)
  954. {
  955. echo "The triggers {$sTable}_bi, {$sTable}_bu, {$sTable}_ad for the data synchro task ".$this->GetName()." (".$this->GetKey().") must be re-created.\n";
  956. echo implode("\n", $aTriggerRepair)."\n";
  957. }
  958. }
  959. $aRepairQueries = array_merge($aRepairQueries, $aTriggerRepair); // The order matters!
  960. }
  961. // Execute the repair statements
  962. //
  963. if (!$bDiagnostics && (count($aRepairQueries) > 0))
  964. {
  965. // Fix the issue
  966. foreach($aRepairQueries as $sSQL)
  967. {
  968. CMDBSource::Query($sSQL);
  969. if ($bVerbose)
  970. {
  971. echo "$sSQL\n";
  972. }
  973. }
  974. }
  975. return $bFixNeeded;
  976. }
  977. public function SendNotification($sSubject, $sBody)
  978. {
  979. $iContact = $this->Get('notify_contact_id');
  980. if ($iContact == 0)
  981. {
  982. // Leave silently...
  983. return;
  984. }
  985. $oContact = MetaModel::GetObject('Contact', $iContact);
  986. // Determine the email attribute (the first one will be our choice)
  987. $sEmailAttCode = null;
  988. foreach (MetaModel::ListAttributeDefs(get_class($oContact)) as $sAttCode => $oAttDef)
  989. {
  990. if ($oAttDef instanceof AttributeEmailAddress)
  991. {
  992. $sEmailAttCode = $sAttCode;
  993. // we've got one, exit the loop
  994. break;
  995. }
  996. }
  997. if (is_null($sEmailAttCode))
  998. {
  999. // Leave silently...
  1000. return;
  1001. }
  1002. $sTo = $oContact->Get($sEmailAttCode);
  1003. $sFrom = $sTo;
  1004. $sBody = '<p>Data synchronization: '.$this->GetHyperlink().'</p>'.$sBody;
  1005. $sSubject = 'iTop Data Sync - '.$this->GetName().' - '.$sSubject;
  1006. $oEmail = new Email();
  1007. $oEmail->SetRecipientTO($sTo);
  1008. $oEmail->SetRecipientFrom($sFrom);
  1009. $oEmail->SetSubject($sSubject);
  1010. $oEmail->SetBody($sBody);
  1011. if ($oEmail->Send($aIssues) == EMAIL_SEND_ERROR)
  1012. {
  1013. // mmmm, what can I do?
  1014. }
  1015. }
  1016. /**
  1017. * Get the list of attributes eligible to the synchronization
  1018. */
  1019. public function ListTargetAttributes()
  1020. {
  1021. $aRet = array();
  1022. foreach(MetaModel::ListAttributeDefs($this->GetTargetClass()) as $sAttCode => $oAttDef)
  1023. {
  1024. if ($sAttCode == 'finalclass') continue;
  1025. if (!$oAttDef->IsWritable()) continue;
  1026. if ($oAttDef->IsLinkSet() && !$oAttDef->IsIndirect()) continue;
  1027. $aRet[$sAttCode] = $oAttDef;
  1028. }
  1029. return $aRet;
  1030. }
  1031. /**
  1032. * Get the list of SQL columns corresponding to a particular list of attribute codes
  1033. * Defaults to the whole list of columns for the current class
  1034. */
  1035. public function GetSQLColumns($aAttributeCodes = null)
  1036. {
  1037. $aColumns = array();
  1038. $sClass = $this->GetTargetClass();
  1039. if (is_null($aAttributeCodes))
  1040. {
  1041. $aAttributeCodes = array();
  1042. foreach($this->ListTargetAttributes() as $sAttCode => $oAttDef)
  1043. {
  1044. $aAttributeCodes[] = $sAttCode;
  1045. }
  1046. }
  1047. foreach($aAttributeCodes as $sAttCode)
  1048. {
  1049. $oAttDef = MetaModel::GetAttributeDef($sClass, $sAttCode);
  1050. if ($oAttDef->IsExternalKey())
  1051. {
  1052. // The pkey might be used as well as any other key column
  1053. $aColumns[$sAttCode] = 'VARCHAR(255)';
  1054. }
  1055. else
  1056. {
  1057. foreach($oAttDef->GetImportColumns() as $sField => $sDBFieldType)
  1058. {
  1059. $aColumns[$sField] = $sDBFieldType;
  1060. }
  1061. }
  1062. }
  1063. return $aColumns;
  1064. }
  1065. /**
  1066. * Get the list of Date and Datetime SQL columns
  1067. */
  1068. public function GetDateSQLColumns()
  1069. {
  1070. $aDateAttributes = array();
  1071. $sClass = $this->GetTargetClass();
  1072. foreach(MetaModel::ListAttributeDefs($sClass) as $sAttCode => $oAttDef)
  1073. {
  1074. if ($oAttDef instanceof AttributeDateTime)
  1075. {
  1076. $aDateAttributes[] = $sAttCode;
  1077. }
  1078. }
  1079. return $this->GetSQLColumns($aDateAttributes);
  1080. }
  1081. public function IsRunning()
  1082. {
  1083. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='running'";
  1084. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1085. if ($oSet->Count() < 1)
  1086. {
  1087. $bRet = false;
  1088. }
  1089. else
  1090. {
  1091. $bRet = true;
  1092. }
  1093. return $bRet;
  1094. }
  1095. public function GetLatestLog()
  1096. {
  1097. $oLog = null;
  1098. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id";
  1099. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('start_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 1 /* limitCount */, 0 /* limitStart */);
  1100. if ($oSet->Count() >= 1)
  1101. {
  1102. $oLog = $oSet->Fetch();
  1103. }
  1104. return $oLog;
  1105. }
  1106. // TO DO: remove if still unused
  1107. /**
  1108. * Retrieve from the log, the date of the last completed import
  1109. * @return DateTime
  1110. */
  1111. public function GetLastCompletedImportDate()
  1112. {
  1113. $date = null;
  1114. $sOQL = "SELECT SynchroLog WHERE sync_source_id = :source_id AND status='completed'";
  1115. $oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array('end_date' => false) /* order by*/, array('source_id' => $this->GetKey()) /* aArgs */, array(), 0 /* limitCount */, 0 /* limitStart */);
  1116. if ($oSet->Count() >= 1)
  1117. {
  1118. $oLog = $oSet->Fetch();
  1119. $date = $oLog->Get('end_date');
  1120. }
  1121. return $date;
  1122. }
  1123. }
  1124. class SynchroAttribute extends cmdbAbstractObject
  1125. {
  1126. public static function Init()
  1127. {
  1128. $aParams = array
  1129. (
  1130. "category" => "core/cmdb,view_in_gui",
  1131. "key_type" => "autoincrement",
  1132. "name_attcode" => "attcode",
  1133. "state_attcode" => "",
  1134. "reconc_keys" => array(),
  1135. "db_table" => "priv_sync_att",
  1136. "db_key_field" => "id",
  1137. "db_finalclass_field" => "",
  1138. "display_template" => "",
  1139. );
  1140. MetaModel::Init_Params($aParams);
  1141. MetaModel::Init_InheritAttributes();
  1142. 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())));
  1143. MetaModel::Init_AddAttribute(new AttributeExternalField("sync_source_name", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"name")));
  1144. MetaModel::Init_AddAttribute(new AttributeString("attcode", array("allowed_values"=>null, "sql"=>"attcode", "default_value"=>null, "is_null_allowed"=>false, "depends_on"=>array())));
  1145. MetaModel::Init_AddAttribute(new AttributeBoolean("update", array("allowed_values"=>null, "sql"=>"update", "default_value"=>true, "is_null_allowed"=>false, "depends_on"=>array())));
  1146. MetaModel::Init_AddAttribute(new AttributeBoolean("reconcile", array("allowed_values"=>null, "sql"=>"reconcile", "default_value"=>false, "is_null_allowed"=>false, "depends_on"=>array())));
  1147. 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())));
  1148. // Display lists
  1149. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for the complete details
  1150. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1151. // Search criteria
  1152. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1153. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1154. }
  1155. }
  1156. class SynchroAttExtKey extends SynchroAttribute
  1157. {
  1158. public static function Init()
  1159. {
  1160. $aParams = array
  1161. (
  1162. "category" => "core/cmdb,view_in_gui",
  1163. "key_type" => "autoincrement",
  1164. "name_attcode" => "attcode",
  1165. "state_attcode" => "",
  1166. "reconc_keys" => array(),
  1167. "db_table" => "priv_sync_att_extkey",
  1168. "db_key_field" => "id",
  1169. "db_finalclass_field" => "",
  1170. "display_template" => "",
  1171. );
  1172. MetaModel::Init_Params($aParams);
  1173. MetaModel::Init_InheritAttributes();
  1174. MetaModel::Init_AddAttribute(new AttributeString("reconciliation_attcode", array("allowed_values"=>null, "sql"=>"reconciliation_attcode", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1175. // Display lists
  1176. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'reconciliation_attcode')); // Attributes to be displayed for the complete details
  1177. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1178. // Search criteria
  1179. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1180. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1181. }
  1182. public function GetReconciliationFormElement($sTargetClass, $sFieldName)
  1183. {
  1184. $sHtml = "<select name=\"$sFieldName\">\n";
  1185. // Id
  1186. $sSelected = (''== $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1187. $sHtml .= "<option value=\"\" $sSelected>".Dict::S('Core:SynchroAttExtKey:ReconciliationById')."</option>\n";
  1188. // Friendly name
  1189. $sSelected = ('friendlyname' == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1190. $sHtml .= "<option value=\"friendlyname\" $sSelected>".MetaModel::GetLabel($sTargetClass, 'friendlyname')."</option>\n";
  1191. // Separator
  1192. $sHtml .= '<option value="" disabled=disabled">———————————</option>'; // Note: using the em-dash character which has no space between 2 characters
  1193. // Then add all remaining scalar attributes, sorted alphabetically
  1194. $aMoreOptions = array();
  1195. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  1196. {
  1197. if ($oAttDef->IsScalar() && ($sAttCode != 'friendlyname'))
  1198. {
  1199. $sSelected = ($sAttCode == $this->Get('reconciliation_attcode')) ? ' selected' : '';
  1200. $aMoreOptions[MetaModel::GetLabel($sTargetClass, $sAttCode)] = "<option value=\"$sAttCode\" $sSelected>".MetaModel::GetLabel($sTargetClass, $sAttCode)."</option>\n";
  1201. }
  1202. }
  1203. ksort($aMoreOptions);
  1204. foreach($aMoreOptions as $sOption)
  1205. {
  1206. $sHtml .= $sOption;
  1207. }
  1208. $sHtml .= "</select>\n";
  1209. return $sHtml;
  1210. }
  1211. }
  1212. class SynchroAttLinkSet extends SynchroAttribute
  1213. {
  1214. public static function Init()
  1215. {
  1216. $aParams = array
  1217. (
  1218. "category" => "core/cmdb,view_in_gui",
  1219. "key_type" => "autoincrement",
  1220. "name_attcode" => "attcode",
  1221. "state_attcode" => "",
  1222. "reconc_keys" => array(),
  1223. "db_table" => "priv_sync_att_linkset",
  1224. "db_key_field" => "id",
  1225. "db_finalclass_field" => "",
  1226. "display_template" => "",
  1227. );
  1228. MetaModel::Init_Params($aParams);
  1229. MetaModel::Init_InheritAttributes();
  1230. MetaModel::Init_AddAttribute(new AttributeString("row_separator", array("allowed_values"=>null, "sql"=>"row_separator", "default_value"=>'|', "is_null_allowed"=>true, "depends_on"=>array())));
  1231. MetaModel::Init_AddAttribute(new AttributeString("attribute_separator", array("allowed_values"=>null, "sql"=>"attribute_separator", "default_value"=>';', "is_null_allowed"=>true, "depends_on"=>array())));
  1232. MetaModel::Init_AddAttribute(new AttributeString("value_separator", array("allowed_values"=>null, "sql"=>"value_separator", "default_value"=>':', "is_null_allowed"=>true, "depends_on"=>array())));
  1233. MetaModel::Init_AddAttribute(new AttributeString("attribute_qualifier", array("allowed_values"=>null, "sql"=>"attribute_qualifier", "default_value"=>'\'', "is_null_allowed"=>true, "depends_on"=>array())));
  1234. // Display lists
  1235. MetaModel::Init_SetZListItems('details', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy', 'row_separator', 'attribute_separator', 'value_separator', 'attribute_qualifier')); // Attributes to be displayed for the complete details
  1236. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'attcode', 'update', 'reconcile', 'update_policy')); // Attributes to be displayed for a list
  1237. // Search criteria
  1238. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1239. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1240. }
  1241. }
  1242. //class SynchroLog extends Event
  1243. class SynchroLog extends DBObject
  1244. {
  1245. public static function Init()
  1246. {
  1247. $aParams = array
  1248. (
  1249. "category" => "core/cmdb,view_in_gui",
  1250. "key_type" => "autoincrement",
  1251. "name_attcode" => "",
  1252. "state_attcode" => "",
  1253. "reconc_keys" => array(),
  1254. "db_table" => "priv_sync_log",
  1255. "db_key_field" => "id",
  1256. "db_finalclass_field" => "",
  1257. "display_template" => "",
  1258. );
  1259. MetaModel::Init_Params($aParams);
  1260. MetaModel::Init_InheritAttributes();
  1261. // MetaModel::Init_AddAttribute(new AttributeString("userinfo", array("allowed_values"=>null, "sql"=>"userinfo", "default_value"=>null, "is_null_allowed"=>true, "depends_on"=>array())));
  1262. 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())));
  1263. MetaModel::Init_AddAttribute(new AttributeDateTime("start_date", array("allowed_values"=>null, "sql"=>"start_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1264. MetaModel::Init_AddAttribute(new AttributeDateTime("end_date", array("allowed_values"=>null, "sql"=>"end_date", "default_value"=>"", "is_null_allowed"=>true, "depends_on"=>array())));
  1265. 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())));
  1266. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_job", array("allowed_values"=>null, "sql"=>"status_curr_job", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1267. MetaModel::Init_AddAttribute(new AttributeInteger("status_curr_pos", array("allowed_values"=>null, "sql"=>"status_curr_pos", "default_value"=>0, "is_null_allowed"=>true, "depends_on"=>array())));
  1268. 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())));
  1269. 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())));
  1270. 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())));
  1271. 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())));
  1272. 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())));
  1273. 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())));
  1274. 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())));
  1275. 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())));
  1276. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_created_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_created_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1277. 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())));
  1278. 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())));
  1279. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1280. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1281. // 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())));
  1282. 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())));
  1283. 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())));
  1284. 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())));
  1285. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_updated_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_updated_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1286. 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())));
  1287. MetaModel::Init_AddAttribute(new AttributeInteger("stats_nb_obj_new_unchanged_warnings", array("allowed_values"=>null, "sql"=>"stats_nb_obj_new_unchanged_warnings", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1288. MetaModel::Init_AddAttribute(new AttributeText("last_error", array("allowed_values"=>null, "sql"=>"last_error", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1289. MetaModel::Init_AddAttribute(new AttributeLongText("traces", array("allowed_values"=>null, "sql"=>"traces", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1290. MetaModel::Init_AddAttribute(new AttributeInteger("memory_usage_peak", array("allowed_values"=>null, "sql"=>"memory_usage_peak", "default_value"=>0, "is_null_allowed"=>false, "depends_on"=>array())));
  1291. // Display lists
  1292. 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',
  1293. '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
  1294. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'start_date', 'end_date', 'status', 'stats_nb_replica_seen')); // Attributes to be displayed for a list
  1295. // Search criteria
  1296. // MetaModel::Init_SetZListItems('standard_search', array('name')); // Criteria of the std search form
  1297. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1298. }
  1299. /**
  1300. * Helper
  1301. */
  1302. function GetErrorCount()
  1303. {
  1304. return $this->Get('stats_nb_obj_deleted_errors')
  1305. + $this->Get('stats_nb_obj_obsoleted_errors')
  1306. + $this->Get('stats_nb_obj_created_errors')
  1307. + $this->Get('stats_nb_obj_updated_errors')
  1308. + $this->Get('stats_nb_replica_reconciled_errors');
  1309. }
  1310. /**
  1311. * Increments a statistics counter
  1312. */
  1313. function Inc($sCode)
  1314. {
  1315. $this->Set($sCode, 1+$this->Get($sCode));
  1316. }
  1317. /**
  1318. * Implement traces management
  1319. */
  1320. protected $m_aTraces = array();
  1321. public function AddTrace($sMsg, $oReplica = null)
  1322. {
  1323. if (MetaModel::GetConfig()->Get('synchro_trace') == 'none')
  1324. {
  1325. return;
  1326. }
  1327. if ($oReplica)
  1328. {
  1329. $sDestClass = $oReplica->Get('dest_class');
  1330. if (!empty($sDestClass))
  1331. {
  1332. $sPrefix = $oReplica->GetKey().','.$sDestClass.'::'.$oReplica->Get('dest_id').',';
  1333. }
  1334. else
  1335. {
  1336. $sPrefix = $oReplica->GetKey().',,';
  1337. }
  1338. }
  1339. else
  1340. {
  1341. $sPrefix = ',,';
  1342. }
  1343. $this->m_aTraces[] = $sPrefix.$sMsg;
  1344. }
  1345. public function GetTraces()
  1346. {
  1347. return $this->m_aTraces;
  1348. }
  1349. protected function TraceToText()
  1350. {
  1351. if (MetaModel::GetConfig()->Get('synchro_trace') != 'save')
  1352. {
  1353. // none, or display only
  1354. return;
  1355. }
  1356. $sPrevTrace = $this->Get('traces');
  1357. $oAttDef = MetaModel::GetAttributeDef(get_class($this), 'traces');
  1358. $iMaxSize = $oAttDef->GetMaxSize();
  1359. if (strlen($sPrevTrace) > 0)
  1360. {
  1361. $sTrace = $sPrevTrace."\n".implode("\n", $this->m_aTraces);
  1362. }
  1363. else
  1364. {
  1365. $sTrace = implode("\n", $this->m_aTraces);
  1366. }
  1367. if (strlen($sTrace) >= $iMaxSize)
  1368. {
  1369. $sTrace = substr($sTrace, 0, $iMaxSize - 255)."...\nTruncated (size: ".strlen($sTrace).')';
  1370. }
  1371. $this->Set('traces', $sTrace);
  1372. //DBUpdate may be called many times... the operation should not be repeated
  1373. $this->m_aTraces = array();
  1374. }
  1375. protected function OnInsert()
  1376. {
  1377. $this->TraceToText();
  1378. parent::OnInsert();
  1379. }
  1380. protected function OnUpdate()
  1381. {
  1382. $this->TraceToText();
  1383. $sMemPeak = max($this->Get('memory_usage_peak'), ExecutionKPI::memory_get_peak_usage());
  1384. $this->Set('memory_usage_peak', $sMemPeak);
  1385. parent::OnUpdate();
  1386. }
  1387. }
  1388. class SynchroReplica extends DBObject implements iDisplay
  1389. {
  1390. static $aSearches = array(); // Cache of OQL queries used for reconciliation (per data source)
  1391. protected $aWarnings;
  1392. public static function Init()
  1393. {
  1394. $aParams = array
  1395. (
  1396. "category" => "core/cmdb,view_in_gui",
  1397. "key_type" => "autoincrement",
  1398. "name_attcode" => "",
  1399. "state_attcode" => "",
  1400. "reconc_keys" => array(),
  1401. "db_table" => "priv_sync_replica",
  1402. "db_key_field" => "id",
  1403. "db_finalclass_field" => "",
  1404. "display_template" => "",
  1405. "indexes" => array( array ('dest_class', 'dest_id'), ),
  1406. );
  1407. MetaModel::Init_Params($aParams);
  1408. MetaModel::Init_InheritAttributes();
  1409. 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())));
  1410. MetaModel::Init_AddAttribute(new AttributeExternalField("base_class", array("allowed_values"=>null, "extkey_attcode"=> 'sync_source_id', "target_attcode"=>"scope_class")));
  1411. MetaModel::Init_AddAttribute(new AttributeObjectKey("dest_id", array("allowed_values"=>null, "class_attcode"=>"dest_class", "sql"=>"dest_id", "is_null_allowed"=>true, "depends_on"=>array())));
  1412. 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())));
  1413. 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())));
  1414. 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())));
  1415. 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())));
  1416. 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())));
  1417. MetaModel::Init_AddAttribute(new AttributeString("status_last_warning", array("allowed_values"=>null, "sql"=>"status_last_warning", "default_value"=>'', "is_null_allowed"=>true, "depends_on"=>array())));
  1418. 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())));
  1419. 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())));
  1420. // Display lists
  1421. MetaModel::Init_SetZListItems('details', array('' .
  1422. 'col:0'=> array(
  1423. 'fieldset:SynchroDataSource:Definition' => array('sync_source_id','dest_id','dest_class'),
  1424. 'fieldset:SynchroDataSource:Status' => array('status','status_last_seen','status_dest_creator','status_last_error','status_last_warning'),
  1425. 'fieldset:SynchroDataSource:Information' => array('info_creation_date','info_last_modified'))
  1426. )
  1427. );
  1428. MetaModel::Init_SetZListItems('list', array('sync_source_id', 'dest_id', 'dest_class', 'status_last_seen', 'status', 'status_dest_creator', 'status_last_error', 'status_last_warning')); // Attributes to be displayed for a list
  1429. // Search criteria
  1430. MetaModel::Init_SetZListItems('standard_search', array('sync_source_id', 'status_last_seen', 'status', 'status_dest_creator', 'dest_class', 'dest_id', 'status_last_error', 'status_last_warning')); // Criteria of the std search form
  1431. // MetaModel::Init_SetZListItems('advanced_search', array('name')); // Criteria of the advanced search form
  1432. }
  1433. public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
  1434. {
  1435. parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
  1436. $this->aWarnings = array();
  1437. }
  1438. protected function AddWarning($sWarningMessage)
  1439. {
  1440. $this->aWarnings[] = $sWarningMessage;
  1441. }
  1442. protected function ResetWarnings()
  1443. {
  1444. $this->aWarnings = array();
  1445. }
  1446. protected function HasWarnings()
  1447. {
  1448. return (count($this->aWarnings) > 0);
  1449. }
  1450. protected function RecordWarnings()
  1451. {
  1452. $sWarningMessage = '';
  1453. $MAX_WARNING_LENGTH = 255;
  1454. switch(count($this->aWarnings))
  1455. {
  1456. case 0:
  1457. $sWarningMessage = '';
  1458. break;
  1459. case 1:
  1460. $sWarningMessage = $this->aWarnings[0];
  1461. break;
  1462. default:
  1463. $sWarningMessage = count($this->aWarnings)." warnings: ".implode(' ', $this->aWarnings);
  1464. break;
  1465. }
  1466. if (strlen($sWarningMessage) > $MAX_WARNING_LENGTH)
  1467. {
  1468. $sWarningMessage = substr($sWarningMessage, 0, $MAX_WARNING_LENGTH - 3).'...';
  1469. }
  1470. $this->Set('status_last_warning', $sWarningMessage);
  1471. }
  1472. public function DBInsert()
  1473. {
  1474. throw new CoreException('A synchronization replica must be created only by the mean of triggers');
  1475. }
  1476. // Overload the deletion -> the replica has been created by the mean of a trigger,
  1477. // it will be deleted by the mean of a trigger too
  1478. protected function DBDeleteSingleObject()
  1479. {
  1480. $this->OnDelete();
  1481. if (!MetaModel::DBIsReadOnly())
  1482. {
  1483. $oDataSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'), false);
  1484. if ($oDataSource)
  1485. {
  1486. $sTable = $oDataSource->GetDataTable();
  1487. $sSQL = "DELETE FROM `$sTable` WHERE id = '{$this->GetKey()}'";
  1488. CMDBSource::Query($sSQL);
  1489. }
  1490. // else the whole datasource has probably been already deleted
  1491. }
  1492. $this->AfterDelete();
  1493. $this->m_bIsInDB = false;
  1494. $this->m_iKey = null;
  1495. }
  1496. public function SetLastError($sMessage, $oException = null)
  1497. {
  1498. if ($oException)
  1499. {
  1500. $sText = $sMessage.$oException->getMessage();
  1501. }
  1502. else
  1503. {
  1504. $sText = $sMessage;
  1505. }
  1506. if (strlen($sText) > 255)
  1507. {
  1508. $sText = substr($sText, 0, 200).'...('.strlen($sText).' chars)...';
  1509. }
  1510. $this->Set('status_last_error', $sText);
  1511. }
  1512. public function Synchro($oDataSource, $aReconciliationKeys, $aAttributes, $oChange, &$oStatLog)
  1513. {
  1514. $this->ResetWarnings();
  1515. switch($this->Get('status'))
  1516. {
  1517. case 'new':
  1518. $this->Set('status_dest_creator', false);
  1519. // If needed, construct the query used for the reconciliation
  1520. if (!isset(self::$aSearches[$oDataSource->GetKey()]))
  1521. {
  1522. $aCriterias = array();
  1523. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1524. {
  1525. $aCriterias[] = ($sFilterCode == 'primary_key' ? 'id' : $sFilterCode).' = :'.$sFilterCode;
  1526. }
  1527. $sOQL = "SELECT ".$oDataSource->GetTargetClass()." WHERE ".implode(' AND ', $aCriterias);
  1528. self::$aSearches[$oDataSource->GetKey()] = DBObjectSearch::FromOQL($sOQL);
  1529. }
  1530. // Get the criterias for the search
  1531. $aFilterValues = array();
  1532. foreach($aReconciliationKeys as $sFilterCode => $oSyncAtt)
  1533. {
  1534. $value = $this->GetValueFromExtData($sFilterCode, $oSyncAtt, $oStatLog);
  1535. if (!is_null($value))
  1536. {
  1537. $aFilterValues[$sFilterCode] = $value;
  1538. }
  1539. else
  1540. {
  1541. // TO DO: can we retry this ??
  1542. // Reconciliation could not be performed - log and EXIT
  1543. $oStatLog->AddTrace("Could not reconcile on null value for attribute '$sFilterCode'", $this);
  1544. $this->SetLastError("Could not reconcile on null value for attribute '$sFilterCode'");
  1545. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1546. return;
  1547. }
  1548. }
  1549. $oDestSet = new DBObjectSet(self::$aSearches[$oDataSource->GetKey()], array(), $aFilterValues);
  1550. $iCount = $oDestSet->Count();
  1551. $aConditions = array();
  1552. foreach($aFilterValues as $sCode => $sValue)
  1553. {
  1554. $aConditions[] = $sCode.'='.$sValue;
  1555. }
  1556. $sConditionDesc = implode(' AND ', $aConditions);
  1557. // How many objects match the reconciliation criterias
  1558. switch($iCount)
  1559. {
  1560. case 0:
  1561. $oStatLog->AddTrace("Nothing found on: $sConditionDesc", $this);
  1562. if ($oDataSource->Get('action_on_zero') == 'create')
  1563. {
  1564. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1565. if ($bCreated)
  1566. {
  1567. if ($this->HasWarnings())
  1568. {
  1569. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1570. }
  1571. }
  1572. else
  1573. {
  1574. // Creation error has precedence over any warning
  1575. $this->ResetWarnings();
  1576. }
  1577. }
  1578. else // assumed to be 'error'
  1579. {
  1580. $oStatLog->AddTrace("Failed to reconcile (no match)", $this);
  1581. // Recoverable error
  1582. $this->SetLastError('Could not find a match for reconciliation');
  1583. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1584. }
  1585. break;
  1586. case 1:
  1587. $oStatLog->AddTrace("Found 1 object on: $sConditionDesc", $this);
  1588. if ($oDataSource->Get('action_on_one') == 'update')
  1589. {
  1590. $oDestObj = $oDestSet->Fetch();
  1591. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1592. $this->Set('dest_id', $oDestObj->GetKey());
  1593. $this->Set('dest_class', get_class($oDestObj));
  1594. if ($this->HasWarnings())
  1595. {
  1596. if ($bModified)
  1597. {
  1598. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1599. }
  1600. else
  1601. {
  1602. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1603. }
  1604. }
  1605. }
  1606. else
  1607. {
  1608. // assumed to be 'error'
  1609. $oStatLog->AddTrace("Failed to reconcile (1 match)", $this);
  1610. // Recoverable error
  1611. $this->SetLastError('Found a match while expecting several');
  1612. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1613. }
  1614. break;
  1615. default:
  1616. $oStatLog->AddTrace("Found $iCount objects on: $sConditionDesc", $this);
  1617. if ($oDataSource->Get('action_on_multiple') == 'error')
  1618. {
  1619. $oStatLog->AddTrace("Failed to reconcile (N>1 matches)", $this);
  1620. // Recoverable error
  1621. $this->SetLastError($iCount.' destination objects match the reconciliation criterias: '.$sConditionDesc);
  1622. $oStatLog->Inc('stats_nb_replica_reconciled_errors');
  1623. }
  1624. elseif ($oDataSource->Get('action_on_multiple') == 'create')
  1625. {
  1626. $bCreated = $this->CreateObjectFromReplica($oDataSource->GetTargetClass(), $aAttributes, $oChange, $oStatLog);
  1627. if ($bCreated)
  1628. {
  1629. if ($this->HasWarnings())
  1630. {
  1631. $oStatLog->Inc('stats_nb_obj_created_warnings');
  1632. }
  1633. }
  1634. else
  1635. {
  1636. // Creation error has precedence over any warning
  1637. $this->ResetWarnings();
  1638. }
  1639. }
  1640. else
  1641. {
  1642. // assumed to be 'take_first'
  1643. $oDestObj = $oDestSet->Fetch();
  1644. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj_new', 'stats_nb_replica_reconciled_errors');
  1645. $this->Set('dest_id', $oDestObj->GetKey());
  1646. $this->Set('dest_class', get_class($oDestObj));
  1647. if ($this->HasWarnings())
  1648. {
  1649. if ($bModified)
  1650. {
  1651. $oStatLog->Inc('stats_nb_obj_new_updated_warnings');
  1652. }
  1653. else
  1654. {
  1655. $oStatLog->Inc('stats_nb_obj_new_unchanged_warnings');
  1656. }
  1657. }
  1658. }
  1659. }
  1660. $this->RecordWarnings();
  1661. break;
  1662. case 'synchronized': // try to recover synchronized replicas with warnings
  1663. case 'modified':
  1664. $oDestObj = MetaModel::GetObject($oDataSource->GetTargetClass(), $this->Get('dest_id'));
  1665. if ($oDestObj == null)
  1666. {
  1667. $this->Set('status', 'orphan'); // The destination object has been deleted !
  1668. $this->SetLastError('Destination object deleted unexpectedly');
  1669. $oStatLog->Inc('stats_nb_obj_updated_errors');
  1670. }
  1671. else
  1672. {
  1673. $bModified = $this->UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, $oStatLog, 'stats_nb_obj', 'stats_nb_obj_updated_errors');
  1674. if ($this->HasWarnings())
  1675. {
  1676. if ($bModified)
  1677. {
  1678. $oStatLog->Inc('stats_nb_obj_updated_warnings');
  1679. }
  1680. else
  1681. {
  1682. $oStatLog->Inc('stats_nb_obj_unchanged_warnings');
  1683. }
  1684. }
  1685. }
  1686. $this->RecordWarnings();
  1687. break;
  1688. default: // Do nothing in all other cases
  1689. }
  1690. }
  1691. /**
  1692. * Updates the destination object with the Extended data found in the synchro_data_XXXX table
  1693. */
  1694. protected function UpdateObjectFromReplica($oDestObj, $aAttributes, $oChange, &$oStatLog, $sStatsCode, $sStatsCodeError)
  1695. {
  1696. $aValueTrace = array();
  1697. $bModified = false;
  1698. try
  1699. {
  1700. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1701. {
  1702. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1703. if (!is_null($value))
  1704. {
  1705. if ($oSyncAtt->Get('update_policy') == 'write_if_empty')
  1706. {
  1707. $oAttDef = MetaModel::GetAttributeDef(get_class($oDestObj), $sAttCode);
  1708. if ($oAttDef->IsNull($oDestObj->Get($sAttCode)))
  1709. {
  1710. // The value is still "empty" in the target object, we are allowed to write the new value
  1711. $oDestObj->Set($sAttCode, $value);
  1712. $aValueTrace[] = "$sAttCode: $value";
  1713. }
  1714. }
  1715. else
  1716. {
  1717. $oDestObj->Set($sAttCode, $value);
  1718. $aValueTrace[] = "$sAttCode: $value";
  1719. }
  1720. }
  1721. }
  1722. // Really modified ?
  1723. if ($oDestObj->IsModified())
  1724. {
  1725. $oDestObj->DBUpdateTracked($oChange);
  1726. $bModified = true;
  1727. $oStatLog->AddTrace('Updated object - Values: {'.implode(', ', $aValueTrace).'}', $this);
  1728. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_updated')))
  1729. {
  1730. $oStatLog->Inc($sStatsCode.'_updated');
  1731. }
  1732. $this->Set('info_last_modified', date(AttributeDateTime::GetSQLFormat()));
  1733. }
  1734. else
  1735. {
  1736. $oStatLog->AddTrace('Unchanged object', $this);
  1737. if (($sStatsCode != '') &&(MetaModel::IsValidAttCode(get_class($oStatLog), $sStatsCode.'_unchanged')))
  1738. {
  1739. $oStatLog->Inc($sStatsCode.'_unchanged');
  1740. }
  1741. }
  1742. $this->Set('status_last_error', '');
  1743. $this->Set('status', 'synchronized');
  1744. }
  1745. catch(Exception $e)
  1746. {
  1747. $oStatLog->AddTrace("Failed to update destination object: {$e->getMessage()}", $this);
  1748. $this->SetLastError('Unable to update destination object: ', $e);
  1749. $oStatLog->Inc($sStatsCodeError);
  1750. }
  1751. return $bModified;
  1752. }
  1753. /**
  1754. * Creates the destination object populating it with the Extended data found in the synchro_data_XXXX table
  1755. * @return bool Whether or not the object was created
  1756. */
  1757. protected function CreateObjectFromReplica($sClass, $aAttributes, $oChange, &$oStatLog)
  1758. {
  1759. $bCreated = false;
  1760. $oDestObj = MetaModel::NewObject($sClass);
  1761. try
  1762. {
  1763. $aValueTrace = array();
  1764. foreach($aAttributes as $sAttCode => $oSyncAtt)
  1765. {
  1766. $value = $this->GetValueFromExtData($sAttCode, $oSyncAtt, $oStatLog);
  1767. if (!is_null($value))
  1768. {
  1769. $oDestObj->Set($sAttCode, $value);
  1770. $aValueTrace[] = "$sAttCode: $value";
  1771. }
  1772. }
  1773. $iNew = $oDestObj->DBInsertTracked($oChange);
  1774. $this->Set('dest_id', $oDestObj->GetKey());
  1775. $this->Set('dest_class', get_class($oDestObj));
  1776. $this->Set('status_dest_creator', true);
  1777. $this->Set('status_last_error', '');
  1778. $this->Set('status', 'synchronized');
  1779. $this->Set('info_creation_date', date(AttributeDateTime::GetSQLFormat()));
  1780. $bCreated = true;
  1781. $oStatLog->AddTrace("Created (".implode(', ', $aValueTrace).")", $this);
  1782. $oStatLog->Inc('stats_nb_obj_created');
  1783. }
  1784. catch(Exception $e)
  1785. {
  1786. $oStatLog->AddTrace("Failed to create $sClass ({$e->getMessage()})", $this);
  1787. $this->SetLastError('Unable to create destination object: ', $e);
  1788. $oStatLog->Inc('stats_nb_obj_created_errors');
  1789. }
  1790. return $bCreated;
  1791. }
  1792. /**
  1793. * Update the destination object with given values
  1794. */
  1795. public function UpdateDestObject($aValues, $oChange, &$oStatLog)
  1796. {
  1797. try
  1798. {
  1799. if ($this->Get('dest_class') == '')
  1800. {
  1801. $this->SetLastError('No destination object to update');
  1802. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1803. }
  1804. else
  1805. {
  1806. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1807. foreach($aValues as $sAttCode => $value)
  1808. {
  1809. if (!MetaModel::IsValidAttCode(get_class($oDestObj), $sAttCode))
  1810. {
  1811. throw new Exception("Unknown attribute code '$sAttCode'");
  1812. }
  1813. $oDestObj->Set($sAttCode, $value);
  1814. }
  1815. $this->Set('info_last_modified', date(AttributeDateTime::GetSQLFormat()));
  1816. $oDestObj->DBUpdateTracked($oChange);
  1817. $oStatLog->AddTrace("Replica marked as obsolete", $this);
  1818. $oStatLog->Inc('stats_nb_obj_obsoleted');
  1819. }
  1820. }
  1821. catch(Exception $e)
  1822. {
  1823. $this->SetLastError('Unable to update the destination object: ', $e);
  1824. $oStatLog->Inc('stats_nb_obj_obsoleted_errors');
  1825. }
  1826. }
  1827. /**
  1828. * Delete the destination object
  1829. */
  1830. public function DeleteDestObject($oChange, &$oStatLog)
  1831. {
  1832. if($this->Get('status_dest_creator'))
  1833. {
  1834. try
  1835. {
  1836. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'));
  1837. $oCheckDeletionPlan = new DeletionPlan();
  1838. if ($oDestObj->CheckToDelete($oCheckDeletionPlan))
  1839. {
  1840. $oActualDeletionPlan = new DeletionPlan();
  1841. $oDestObj->DBDeleteTracked($oChange, null, $oActualDeletionPlan);
  1842. $this->DBDeleteTracked($oChange);
  1843. $oStatLog->Inc('stats_nb_obj_deleted');
  1844. }
  1845. else
  1846. {
  1847. $sIssues = implode("\n", $oCheckDeletionPlan->GetIssues());
  1848. throw(new Exception($sIssues));
  1849. }
  1850. }
  1851. catch(Exception $e)
  1852. {
  1853. $this->SetLastError('Unable to delete the destination object: ', $e);
  1854. $this->Set('status', 'obsolete');
  1855. $this->DBUpdateTracked($oChange);
  1856. $oStatLog->Inc('stats_nb_obj_deleted_errors');
  1857. }
  1858. }
  1859. else
  1860. {
  1861. $this->DBDeleteTracked($oChange);
  1862. $oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  1863. }
  1864. }
  1865. /**
  1866. * Get the value from the 'Extended Data' located in the synchro_data_xxx table for this replica
  1867. * Note: sExtAttCode could be a standard attcode, or 'primary_key'
  1868. */
  1869. protected function GetValueFromExtData($sExtAttCode, $oSyncAtt, &$oStatLog)
  1870. {
  1871. // $aData should contain attributes defined either for reconciliation or create/update
  1872. $aData = $this->GetExtendedData();
  1873. if ($sExtAttCode == 'primary_key')
  1874. {
  1875. return $aData['primary_key'];
  1876. }
  1877. // $sExtAttCode is a valid attribute code
  1878. //
  1879. $sClass = $this->Get('base_class');
  1880. $oAttDef = MetaModel::GetAttributeDef($sClass, $sExtAttCode);
  1881. if (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttExtKey))
  1882. {
  1883. $rawValue = $aData[$sExtAttCode];
  1884. if (is_null($rawValue))
  1885. {
  1886. // Null means "ignore" this attribute
  1887. return null;
  1888. }
  1889. $sReconcAttCode = $oSyncAtt->Get('reconciliation_attcode');
  1890. if (!empty($sReconcAttCode))
  1891. {
  1892. $sRemoteClass = $oAttDef->GetTargetClass();
  1893. $oObj = MetaModel::GetObjectByColumn($sRemoteClass, $sReconcAttCode, $rawValue, false);
  1894. if ($oObj)
  1895. {
  1896. $retValue = $oObj->GetKey();
  1897. }
  1898. else
  1899. {
  1900. if ($rawValue != '')
  1901. {
  1902. // Note: differs from null (in which case the value would be left unchanged)
  1903. $oStatLog->AddTrace("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'", $this);
  1904. $this->AddWarning("Could not find [unique] object for '$sExtAttCode': searched on $sReconcAttCode = '$rawValue'");
  1905. }
  1906. $retValue = 0;
  1907. }
  1908. }
  1909. else
  1910. {
  1911. $retValue = $rawValue;
  1912. }
  1913. }
  1914. elseif (!is_null($oSyncAtt) && ($oSyncAtt instanceof SynchroAttLinkSet))
  1915. {
  1916. $rawValue = $aData[$sExtAttCode];
  1917. if (is_null($rawValue))
  1918. {
  1919. // Null means "ignore" this attribute
  1920. return null;
  1921. }
  1922. // MakeValueFromString() throws an exception in case of failure
  1923. $bLocalizedValue = false;
  1924. $retValue = $oAttDef->MakeValueFromString($rawValue, $bLocalizedValue, $oSyncAtt->Get('row_separator'), $oSyncAtt->Get('attribute_separator'), $oSyncAtt->Get('value_separator'), $oSyncAtt->Get('attribute_qualifier'));
  1925. }
  1926. else
  1927. {
  1928. $aColumns = $oAttDef->GetImportColumns();
  1929. foreach($aColumns as $sColumn => $sFormat)
  1930. {
  1931. // In any case, a null column means "ignore this attribute"
  1932. //
  1933. if (is_null($aData[$sColumn]))
  1934. {
  1935. return null;
  1936. }
  1937. }
  1938. $retValue = $oAttDef->FromImportToValue($aData, $sExtAttCode);
  1939. }
  1940. return $retValue;
  1941. }
  1942. /**
  1943. * Maps the given context parameter name to the appropriate filter/search code for this class
  1944. * @param string $sContextParam Name of the context parameter, i.e. 'org_id'
  1945. * @return string Filter code, i.e. 'customer_id'
  1946. */
  1947. public static function MapContextParam($sContextParam)
  1948. {
  1949. if ($sContextParam == 'menu')
  1950. {
  1951. return null;
  1952. }
  1953. else
  1954. {
  1955. return $sContextParam;
  1956. }
  1957. }
  1958. /**
  1959. * This function returns a 'hilight' CSS class, used to hilight a given row in a table
  1960. * There are currently (i.e defined in the CSS) 4 possible values HILIGHT_CLASS_CRITICAL,
  1961. * HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1962. * To Be overridden by derived classes
  1963. * @param void
  1964. * @return String The desired higlight class for the object/row
  1965. */
  1966. public function GetHilightClass()
  1967. {
  1968. // Possible return values are:
  1969. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  1970. return HILIGHT_CLASS_NONE; // Not hilighted by default
  1971. }
  1972. public static function GetUIPage()
  1973. {
  1974. return '../synchro/replica.php';
  1975. }
  1976. function DisplayDetails(WebPage $oPage, $bEditMode = false)
  1977. {
  1978. // Object's details
  1979. //$this->DisplayBareHeader($oPage, $bEditMode);
  1980. $oPage->AddTabContainer(OBJECT_PROPERTIES_TAB);
  1981. $oPage->SetCurrentTabContainer(OBJECT_PROPERTIES_TAB);
  1982. $oPage->SetCurrentTab(Dict::S('UI:PropertiesTab'));
  1983. $this->DisplayBareProperties($oPage, $bEditMode);
  1984. }
  1985. function DisplayBareProperties(WebPage $oPage, $bEditMode = false, $sPrefix = '', $aExtraParams = array())
  1986. {
  1987. if ($bEditMode) return; // Not editable
  1988. $oPage->add('<table style="vertical-align:top"><tr style="vertical-align:top"><td>');
  1989. $aDetails = array();
  1990. $sClass = get_class($this);
  1991. $oPage->add('<fieldset>');
  1992. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PrivateDetails').'</legend>');
  1993. $aZList = MetaModel::FlattenZlist(MetaModel::GetZListItems($sClass, 'details'));
  1994. foreach( $aZList as $sAttCode)
  1995. {
  1996. $sDisplayValue = $this->GetAsHTML($sAttCode);
  1997. $aDetails[] = array('label' => '<span title="'.MetaModel::GetDescription($sClass, $sAttCode).'">'.MetaModel::GetLabel($sClass, $sAttCode).'</span>', 'value' => $sDisplayValue);
  1998. }
  1999. $oPage->Details($aDetails);
  2000. $oPage->add('</fieldset>');
  2001. if (strlen($this->Get('dest_class')) > 0)
  2002. {
  2003. $oDestObj = MetaModel::GetObject($this->Get('dest_class'), $this->Get('dest_id'), false);
  2004. if (is_object($oDestObj))
  2005. {
  2006. $oPage->add('<fieldset>');
  2007. $oPage->add('<legend>'.Dict::Format('Core:SynchroReplica:TargetObject', $oDestObj->GetHyperlink()).'</legend>');
  2008. $oDestObj->DisplayBareProperties($oPage, false, $sPrefix, $aExtraParams);
  2009. $oPage->add('<fieldset>');
  2010. }
  2011. }
  2012. $oPage->add('</td><td>');
  2013. $oPage->add('<fieldset>');
  2014. $oPage->add('<legend>'.Dict::S('Core:SynchroReplica:PublicData').'</legend>');
  2015. $oSource = MetaModel::GetObject('SynchroDataSource', $this->Get('sync_source_id'));
  2016. $sSQLTable = $oSource->GetDataTable();
  2017. $aData = $this->LoadExtendedDataFromTable($sSQLTable);
  2018. $aHeaders = array('attcode' => array('label' => 'Attribute Code', 'description' => ''),
  2019. 'data' => array('label' => 'Value', 'description' => ''));
  2020. $aRows = array();
  2021. foreach($aData as $sKey => $value)
  2022. {
  2023. $aRows[] = array('attcode' => $sKey, 'data' => $value);
  2024. }
  2025. $oPage->Table($aHeaders, $aRows);
  2026. $oPage->add('</fieldset>');
  2027. $oPage->add('</td></tr></table>');
  2028. }
  2029. public function LoadExtendedDataFromTable($sSQLTable)
  2030. {
  2031. $sSQL = "SELECT * FROM $sSQLTable WHERE id=".$this->GetKey();
  2032. $rQuery = CMDBSource::Query($sSQL);
  2033. return CMDBSource::FetchArray($rQuery);
  2034. }
  2035. }
  2036. /**
  2037. * Context of an ongoing synchronization
  2038. * Two usages:
  2039. * 1) Public usage: execute the synchronization
  2040. * $oSynchroExec = new SynchroExecution($oDataSource[, $iLastFullLoad]);
  2041. * $oSynchroExec->Process($iMaxChunkSize);
  2042. *
  2043. * 2) Internal usage: continue the synchronization (split into chunks, each performed in a separate process)
  2044. * This is implemented in the page priv_sync_chunk.php
  2045. * $oSynchroExec = SynchroExecution::Resume($oDataSource, $iLastFullLoad, $iSynchroLog, $iChange, $iMaxToProcess, $iJob, $iNextInJob);
  2046. * $oSynchroExec->Process()
  2047. */
  2048. class SynchroExecution
  2049. {
  2050. protected $m_oDataSource = null;
  2051. protected $m_oLastFullLoadStartDate = null;
  2052. protected $m_oChange = null;
  2053. protected $m_oStatLog = null;
  2054. // Context computed one for optimization and report inconsistencies ASAP
  2055. protected $m_aExtDataSpec = array();
  2056. protected $m_aReconciliationKeys = array();
  2057. protected $m_aAttributes = array();
  2058. protected $m_iCountAllReplicas = 0;
  2059. /**
  2060. * Constructor
  2061. * @param SynchroDataSource $oDataSource Synchronization task
  2062. * @param DateTime $oLastFullLoadStartDate Date of the last full load (start date/time), if known
  2063. * @return void
  2064. */
  2065. public function __construct($oDataSource, $oLastFullLoadStartDate = null)
  2066. {
  2067. $this->m_oDataSource = $oDataSource;
  2068. $this->m_oLastFullLoadStartDate = $oLastFullLoadStartDate;
  2069. }
  2070. /**
  2071. * Create the persistant information records, for the current synchronization
  2072. * In fact, those records ARE defining what is the "current" synchronization
  2073. */
  2074. protected function PrepareLogs()
  2075. {
  2076. if (!is_null($this->m_oChange))
  2077. {
  2078. return;
  2079. }
  2080. // Create a change used for logging all the modifications/creations happening during the synchro
  2081. $this->m_oChange = MetaModel::NewObject("CMDBChange");
  2082. $this->m_oChange->Set("date", time());
  2083. $sUserString = CMDBChange::GetCurrentUserName();
  2084. $this->m_oChange->Set("userinfo", $sUserString.' '.Dict::S('Core:SyncDataExchangeComment'));
  2085. $this->m_oChange->Set("origin", 'synchro-data-source');
  2086. $iChangeId = $this->m_oChange->DBInsert();
  2087. // Start logging this execution (stats + protection against reentrance)
  2088. //
  2089. $this->m_oStatLog = new SynchroLog();
  2090. $this->m_oStatLog->Set('sync_source_id', $this->m_oDataSource->GetKey());
  2091. $this->m_oStatLog->Set('start_date', time());
  2092. $this->m_oStatLog->Set('status', 'running');
  2093. $this->m_oStatLog->Set('stats_nb_replica_seen', 0);
  2094. $this->m_oStatLog->Set('stats_nb_replica_total', 0);
  2095. $this->m_oStatLog->Set('stats_nb_obj_deleted', 0);
  2096. $this->m_oStatLog->Set('stats_nb_obj_deleted_errors', 0);
  2097. $this->m_oStatLog->Set('stats_nb_obj_obsoleted', 0);
  2098. $this->m_oStatLog->Set('stats_nb_obj_obsoleted_errors', 0);
  2099. $this->m_oStatLog->Set('stats_nb_obj_created', 0);
  2100. $this->m_oStatLog->Set('stats_nb_obj_created_errors', 0);
  2101. $this->m_oStatLog->Set('stats_nb_obj_created_warnings', 0);
  2102. $this->m_oStatLog->Set('stats_nb_obj_updated', 0);
  2103. $this->m_oStatLog->Set('stats_nb_obj_updated_warnings', 0);
  2104. $this->m_oStatLog->Set('stats_nb_obj_updated_errors', 0);
  2105. $this->m_oStatLog->Set('stats_nb_obj_unchanged_warnings', 0);
  2106. // $this->m_oStatLog->Set('stats_nb_replica_reconciled', 0);
  2107. $this->m_oStatLog->Set('stats_nb_replica_reconciled_errors', 0);
  2108. $this->m_oStatLog->Set('stats_nb_replica_disappeared_no_action', 0);
  2109. $this->m_oStatLog->Set('stats_nb_obj_new_updated', 0);
  2110. $this->m_oStatLog->Set('stats_nb_obj_new_updated_warnings', 0);
  2111. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged',0);
  2112. $this->m_oStatLog->Set('stats_nb_obj_new_unchanged_warnings',0);
  2113. $sSelectTotal = "SELECT SynchroReplica WHERE sync_source_id = :source_id";
  2114. $oSetTotal = new DBObjectSet(DBObjectSearch::FromOQL($sSelectTotal), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()));
  2115. $this->m_iCountAllReplicas = $oSetTotal->Count();
  2116. $this->m_oStatLog->Set('stats_nb_replica_total', $this->m_iCountAllReplicas);
  2117. $this->m_oStatLog->DBInsertTracked($this->m_oChange);
  2118. }
  2119. /**
  2120. * Prevent against the reentrance... or allow the current task to do things forbidden by the others !
  2121. */
  2122. public static $m_oCurrentTask = null;
  2123. public static function GetCurrentTaskId()
  2124. {
  2125. if (is_object(self::$m_oCurrentTask))
  2126. {
  2127. return self::$m_oCurrentTask->GetKey();
  2128. }
  2129. else
  2130. {
  2131. return null;
  2132. }
  2133. }
  2134. /**
  2135. * Prepare structures in memory, to speedup the processing of a given replica
  2136. */
  2137. public function PrepareProcessing($bFirstPass = true)
  2138. {
  2139. if ($this->m_oDataSource->Get('status') == 'obsolete')
  2140. {
  2141. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceObsolete'));
  2142. }
  2143. if (!UserRights::IsAdministrator() && $this->m_oDataSource->Get('user_id') != UserRights::GetUserId())
  2144. {
  2145. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncDataSourceAccessRestriction'));
  2146. }
  2147. // Get the list of SQL columns
  2148. $sClass = $this->m_oDataSource->GetTargetClass();
  2149. $aAttCodesExpected = array();
  2150. $aAttCodesToReconcile = array();
  2151. $aAttCodesToUpdate = array();
  2152. $sSelectAtt = "SELECT SynchroAttribute WHERE sync_source_id = :source_id AND (update = 1 OR reconcile = 1)";
  2153. $oSetAtt = new DBObjectSet(DBObjectSearch::FromOQL($sSelectAtt), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey()) /* aArgs */);
  2154. while ($oSyncAtt = $oSetAtt->Fetch())
  2155. {
  2156. if ($oSyncAtt->Get('update'))
  2157. {
  2158. $aAttCodesToUpdate[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2159. }
  2160. if ($oSyncAtt->Get('reconcile'))
  2161. {
  2162. $aAttCodesToReconcile[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2163. }
  2164. $aAttCodesExpected[$oSyncAtt->Get('attcode')] = $oSyncAtt;
  2165. }
  2166. $aColumns = $this->m_oDataSource->GetSQLColumns(array_keys($aAttCodesExpected));
  2167. $aExtDataFields = array_keys($aColumns);
  2168. $aExtDataFields[] = 'primary_key';
  2169. $this->m_aExtDataSpec = array(
  2170. 'table' => $this->m_oDataSource->GetDataTable(),
  2171. 'join_key' => 'id',
  2172. 'fields' => $aExtDataFields
  2173. );
  2174. // Get the list of attributes, determine reconciliation keys and update targets
  2175. //
  2176. if ($this->m_oDataSource->Get('reconciliation_policy') == 'use_attributes')
  2177. {
  2178. $this->m_aReconciliationKeys = $aAttCodesToReconcile;
  2179. }
  2180. elseif ($this->m_oDataSource->Get('reconciliation_policy') == 'use_primary_key')
  2181. {
  2182. // Override the settings made at the attribute level !
  2183. $this->m_aReconciliationKeys = array("primary_key" => null);
  2184. }
  2185. if ($bFirstPass)
  2186. {
  2187. $this->m_oStatLog->AddTrace("Update of: {".implode(', ', array_keys($aAttCodesToUpdate))."}");
  2188. $this->m_oStatLog->AddTrace("Reconciliation on: {".implode(', ', array_keys($this->m_aReconciliationKeys))."}");
  2189. }
  2190. if (count($aAttCodesToUpdate) == 0)
  2191. {
  2192. $this->m_oStatLog->AddTrace("No attribute to update");
  2193. throw new SynchroExceptionNotStarted('There is no attribute to update');
  2194. }
  2195. if (count($this->m_aReconciliationKeys) == 0)
  2196. {
  2197. $this->m_oStatLog->AddTrace("No attribute for reconciliation");
  2198. throw new SynchroExceptionNotStarted('No attribute for reconciliation');
  2199. }
  2200. $this->m_aAttributes = array();
  2201. foreach($aAttCodesToUpdate as $sAttCode => $oSyncAtt)
  2202. {
  2203. $oAttDef = MetaModel::GetAttributeDef($this->m_oDataSource->GetTargetClass(), $sAttCode);
  2204. if ($oAttDef->IsWritable())
  2205. {
  2206. $this->m_aAttributes[$sAttCode] = $oSyncAtt;
  2207. }
  2208. }
  2209. // Compute and keep track of the limit date taken into account for obsoleting replicas
  2210. //
  2211. if ($this->m_oLastFullLoadStartDate == null)
  2212. {
  2213. // No previous import known, use the full_load_periodicity value... and the current date
  2214. $this->m_oLastFullLoadStartDate = new DateTime(); // Now
  2215. $iLoadPeriodicity = $this->m_oDataSource->Get('full_load_periodicity'); // Duration in seconds
  2216. if ($iLoadPeriodicity > 0)
  2217. {
  2218. $sInterval = "-$iLoadPeriodicity seconds";
  2219. $this->m_oLastFullLoadStartDate->Modify($sInterval);
  2220. }
  2221. else
  2222. {
  2223. $this->m_oLastFullLoadStartDate = new DateTime('1970-01-01');
  2224. }
  2225. }
  2226. if ($bFirstPass)
  2227. {
  2228. $this->m_oStatLog->AddTrace("Limit Date: ".$this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s'));
  2229. }
  2230. }
  2231. /**
  2232. * Perform a synchronization between the data stored in the replicas (&synchro_data_xxx_xx table)
  2233. * and the iTop objects. If the lastFullLoadStartDate is NOT specified then the full_load_periodicity
  2234. * is used to determine which records are obsolete.
  2235. * @return void
  2236. */
  2237. public function Process()
  2238. {
  2239. $this->PrepareLogs();
  2240. self::$m_oCurrentTask = $this->m_oDataSource;
  2241. $oMutex = new iTopMutex('synchro_process_'.$this->m_oDataSource->GetKey());
  2242. try
  2243. {
  2244. $oMutex->Lock();
  2245. $this->DoSynchronize();
  2246. $oMutex->Unlock();
  2247. $this->m_oStatLog->Set('end_date', time());
  2248. $this->m_oStatLog->Set('status', 'completed');
  2249. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2250. $iErrors = $this->m_oStatLog->GetErrorCount();
  2251. if ($iErrors > 0)
  2252. {
  2253. $sIssuesOQL = "SELECT SynchroReplica WHERE sync_source_id=".$this->m_oDataSource->GetKey()." AND status_last_error!=''";
  2254. $sAbsoluteUrl = utils::GetAbsoluteUrlAppRoot();
  2255. $sIssuesURL = "{$sAbsoluteUrl}synchro/replica.php?operation=oql&datasource=".$this->m_oDataSource->GetKey()."&oql=".urlencode($sIssuesOQL);
  2256. $sSeeIssues = "<p></p>";
  2257. $sStatistics = "<h1>Statistics</h1>\n";
  2258. $sStatistics .= "<ul>\n";
  2259. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('start_date').": ".$this->m_oStatLog->Get('start_date')."</li>\n";
  2260. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('end_date').": ".$this->m_oStatLog->Get('end_date')."</li>\n";
  2261. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_seen').": ".$this->m_oStatLog->Get('stats_nb_replica_seen')."</li>\n";
  2262. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_total').": ".$this->m_oStatLog->Get('stats_nb_replica_total')."</li>\n";
  2263. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted')."</li>\n";
  2264. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_deleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_deleted_errors')."</li>\n";
  2265. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted')."</li>\n";
  2266. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_obsoleted_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_obsoleted_errors')."</li>\n";
  2267. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created').": ".$this->m_oStatLog->Get('stats_nb_obj_created')." (".$this->m_oStatLog->Get('stats_nb_obj_created_warnings')." warnings)"."</li>\n";
  2268. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_created_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_created_errors')."</li>\n";
  2269. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_updated_warnings')." warnings)"."</li>\n";
  2270. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_updated_errors').": ".$this->m_oStatLog->Get('stats_nb_obj_updated_errors')."</li>\n";
  2271. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_reconciled_errors').": ".$this->m_oStatLog->Get('stats_nb_replica_reconciled_errors')."</li>\n";
  2272. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_replica_disappeared_no_action').": ".$this->m_oStatLog->Get('stats_nb_replica_disappeared_no_action')."</li>\n";
  2273. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_updated').": ".$this->m_oStatLog->Get('stats_nb_obj_new_updated')." (".$this->m_oStatLog->Get('stats_nb_obj_new_updated_warnings')." warnings)"."</li>\n";
  2274. $sStatistics .= "<li>".$this->m_oStatLog->GetLabel('stats_nb_obj_new_unchanged').": ".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged')." (".$this->m_oStatLog->Get('stats_nb_obj_new_unchanged_warnings')." warnings)"."</li>\n";
  2275. $sStatistics .= "</ul>\n";
  2276. $this->m_oDataSource->SendNotification("errors ($iErrors)", "<p>The synchronization has been executed, $iErrors errors have been encountered. Click <a href=\"$sIssuesURL\">here</a> to see the records being currently in error.</p>".$sStatistics);
  2277. }
  2278. else
  2279. {
  2280. //$this->m_oDataSource->SendNotification('success', '<p>The synchronization has been successfully executed.</p>');
  2281. }
  2282. }
  2283. catch (SynchroExceptionNotStarted $e)
  2284. {
  2285. $oMutex->Unlock();
  2286. // Set information for reporting... but delete the object in DB
  2287. $this->m_oStatLog->Set('end_date', time());
  2288. $this->m_oStatLog->Set('status', 'error');
  2289. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2290. $this->m_oStatLog->DBDeleteTracked($this->m_oChange);
  2291. $this->m_oDataSource->SendNotification('fatal error', '<p>The synchronization could not start: \''.$e->getMessage().'\'</p><p>Please check its configuration</p>');
  2292. }
  2293. catch (Exception $e)
  2294. {
  2295. $oMutex->Unlock();
  2296. $this->m_oStatLog->Set('end_date', time());
  2297. $this->m_oStatLog->Set('status', 'error');
  2298. $this->m_oStatLog->Set('last_error', $e->getMessage());
  2299. $this->m_oStatLog->DBUpdateTracked($this->m_oChange);
  2300. $this->m_oDataSource->SendNotification('exception', '<p>The synchronization has been interrupted: \''.$e->getMessage().'\'</p><p>Please contact the application support team</p>');
  2301. }
  2302. self::$m_oCurrentTask = null;
  2303. return $this->m_oStatLog;
  2304. }
  2305. /**
  2306. * Do the entire synchronization job
  2307. */
  2308. protected function DoSynchronize()
  2309. {
  2310. $this->m_oStatLog->Set('status_curr_job', 1);
  2311. $this->m_oStatLog->Set('status_curr_pos', -1);
  2312. $iMaxChunkSize = utils::ReadParam('max_chunk_size', 0, true /* allow CLI */);
  2313. if ($iMaxChunkSize > 0)
  2314. {
  2315. // Split the execution into several processes
  2316. // Each process will call DoSynchronizeChunk()
  2317. // The loop will end when a process does not reply "continue" on the last line of its output
  2318. if (!utils::IsModeCLI())
  2319. {
  2320. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncSplitModeCLIOnly'));
  2321. }
  2322. $aArguments = array();
  2323. $aArguments['source'] = $this->m_oDataSource->GetKey();
  2324. $aArguments['log'] = $this->m_oStatLog->GetKey();
  2325. $aArguments['change'] = $this->m_oChange->GetKey();
  2326. $aArguments['chunk'] = $iMaxChunkSize;
  2327. if ($this->m_oLastFullLoadStartDate)
  2328. {
  2329. $aArguments['last_full_load'] = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2330. }
  2331. else
  2332. {
  2333. $aArguments['last_full_load'] = '';
  2334. }
  2335. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2336. $iStepCount = 0;
  2337. do
  2338. {
  2339. $aArguments['step_count'] = $iStepCount;
  2340. $iStepCount++;
  2341. set_time_limit(0); // On Linux the time spent outside of the script does not count, but on Windows it does, so let give us time !
  2342. list ($iRes, $aOut) = utils::ExecITopScript('synchro/priv_sync_chunk.php', $aArguments);
  2343. // Reload the log that has been modified by the processes
  2344. $this->m_oStatLog->Reload();
  2345. $sLastRes = strtolower(trim(end($aOut)));
  2346. switch($sLastRes)
  2347. {
  2348. case 'continue':
  2349. $bContinue = true;
  2350. break;
  2351. case 'finished':
  2352. $bContinue = false;
  2353. break;
  2354. default:
  2355. $this->m_oStatLog->AddTrace("The script did not reply with the expected keywords:");
  2356. $aIndentedOut = array();
  2357. foreach ($aOut as $sOut)
  2358. {
  2359. $aIndentedOut[] = "-> $sOut";
  2360. $this->m_oStatLog->AddTrace(">>> $sOut");
  2361. }
  2362. throw new Exception("Encountered an error in an underspinned process:\n".implode("\n", $aIndentedOut));
  2363. }
  2364. }
  2365. while ($bContinue);
  2366. }
  2367. else
  2368. {
  2369. $this->PrepareProcessing(/* first pass */);
  2370. $this->DoJob1();
  2371. $this->DoJob2();
  2372. $this->DoJob3();
  2373. }
  2374. }
  2375. /**
  2376. * Do the synchronization job, limited to some amount of work
  2377. * This verb has been designed to be called from within a separate process
  2378. * @return true if the process has to be continued
  2379. */
  2380. public function DoSynchronizeChunk($oLog, $oChange, $iMaxChunkSize)
  2381. {
  2382. // Initialize the structures...
  2383. self::$m_oCurrentTask = $this->m_oDataSource;
  2384. $this->m_oStatLog = $oLog;
  2385. $this->m_oChange = $oChange;
  2386. // Prepare internal structures (not the first pass)
  2387. $this->PrepareProcessing(false);
  2388. $iCurrJob = $this->m_oStatLog->Get('status_curr_job');
  2389. $iCurrPos = $this->m_oStatLog->Get('status_curr_pos');
  2390. $this->m_oStatLog->AddTrace("Synchronizing chunk - curr_job:$iCurrJob, curr_pos:$iCurrPos, max_chunk_size:$iMaxChunkSize");
  2391. $bContinue = false;
  2392. switch ($iCurrJob)
  2393. {
  2394. case 1:
  2395. default:
  2396. $this->DoJob1($iMaxChunkSize, $iCurrPos);
  2397. $bContinue = true;
  2398. break;
  2399. case 2:
  2400. $this->DoJob2($iMaxChunkSize, $iCurrPos);
  2401. $bContinue = true;
  2402. break;
  2403. case 3:
  2404. $bContinue = $this->DoJob3($iMaxChunkSize, $iCurrPos);
  2405. break;
  2406. }
  2407. $this->m_oStatLog->DBUpdate($this->m_oChange);
  2408. self::$m_oCurrentTask = null;
  2409. return $bContinue;
  2410. }
  2411. /**
  2412. * Do the synchronization job #1: Obsolete replica "untouched" for some time
  2413. * @param integer $iMaxReplica Limit the number of replicas to process
  2414. * @param integer $iCurrPos Current position where to resume the processing
  2415. * @return true if the process must be continued
  2416. */
  2417. protected function DoJob1($iMaxReplica = null, $iCurrPos = -1)
  2418. {
  2419. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2420. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2421. // Get all the replicas that were not seen in the last import and mark them as obsolete
  2422. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2423. if ($sDeletePolicy != 'ignore')
  2424. {
  2425. $sSelectToObsolete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen < :last_import";
  2426. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2427. $iCountScope = $oSetScope->Count();
  2428. if (($this->m_iCountAllReplicas > 10) && ($this->m_iCountAllReplicas == $iCountScope) && MetaModel::GetConfig()->Get('synchro_prevent_delete_all'))
  2429. {
  2430. throw new SynchroExceptionNotStarted(Dict::S('Core:SyncTooManyMissingReplicas'));
  2431. }
  2432. if ($iMaxReplica)
  2433. {
  2434. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2435. // The replica have to be ordered by id
  2436. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToObsolete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos));
  2437. $oSetToProcess->SetLimit($iMaxReplica);
  2438. }
  2439. else
  2440. {
  2441. $oSetToProcess = $oSetScope;
  2442. }
  2443. $iLastReplicaProcessed = -1;
  2444. while($oReplica = $oSetToProcess->Fetch())
  2445. {
  2446. set_time_limit($iLoopTimeLimit);
  2447. $iLastReplicaProcessed = $oReplica->GetKey();
  2448. switch ($sDeletePolicy)
  2449. {
  2450. case 'update':
  2451. case 'update_then_delete':
  2452. $this->m_oStatLog->AddTrace("Destination object to be updated", $oReplica);
  2453. $aToUpdate = array();
  2454. $aToUpdateSpec = explode(';', $this->m_oDataSource->Get('delete_policy_update')); //ex: 'status:obsolete;description:stopped',
  2455. foreach($aToUpdateSpec as $sUpdateSpec)
  2456. {
  2457. $aUpdateSpec = explode(':', $sUpdateSpec);
  2458. if (count($aUpdateSpec) == 2)
  2459. {
  2460. $sAttCode = $aUpdateSpec[0];
  2461. $sValue = $aUpdateSpec[1];
  2462. $aToUpdate[$sAttCode] = $sValue;
  2463. }
  2464. }
  2465. $oReplica->Set('status_last_error', '');
  2466. if ($oReplica->Get('dest_id') == '')
  2467. {
  2468. $oReplica->Set('status', 'obsolete');
  2469. $this->m_oStatLog->Inc('stats_nb_replica_disappeared_no_action');
  2470. }
  2471. else
  2472. {
  2473. $oReplica->UpdateDestObject($aToUpdate, $this->m_oChange, $this->m_oStatLog);
  2474. if ($oReplica->Get('status_last_error') == '')
  2475. {
  2476. // Change the status of the replica IIF
  2477. $oReplica->Set('status', 'obsolete');
  2478. }
  2479. }
  2480. $oReplica->DBUpdateTracked($this->m_oChange);
  2481. break;
  2482. case 'delete':
  2483. default:
  2484. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2485. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2486. }
  2487. }
  2488. if ($iMaxReplica)
  2489. {
  2490. if ($iMaxReplica < $iCountScope)
  2491. {
  2492. // Continue with this job!
  2493. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2494. return true;
  2495. }
  2496. }
  2497. } // if ($sDeletePolicy != 'ignore'
  2498. //Count "seen" objects
  2499. $sSelectSeen = "SELECT SynchroReplica WHERE sync_source_id = :source_id AND status IN ('new', 'synchronized', 'modified', 'orphan') AND status_last_seen >= :last_import";
  2500. $oSetSeen = new DBObjectSet(DBObjectSearch::FromOQL($sSelectSeen), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate));
  2501. $this->m_oStatLog->Set('stats_nb_replica_seen', $oSetSeen->Count());
  2502. // Job complete!
  2503. $this->m_oStatLog->Set('status_curr_job', 2);
  2504. $this->m_oStatLog->Set('status_curr_pos', -1);
  2505. return false;
  2506. }
  2507. /**
  2508. * Do the synchronization job #2: Create and modify object for new/modified replicas
  2509. * @param integer $iMaxReplica Limit the number of replicas to process
  2510. * @param integer $iCurrPos Current position where to resume the processing
  2511. * @return true if the process must be continued
  2512. */
  2513. protected function DoJob2($iMaxReplica = null, $iCurrPos = -1)
  2514. {
  2515. $sLimitDate = $this->m_oLastFullLoadStartDate->Format('Y-m-d H:i:s');
  2516. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2517. // Get all the replicas that are 'new' or modified or synchronized with a warning
  2518. //
  2519. $sSelectToSync = "SELECT SynchroReplica WHERE id > :curr_pos AND (status = 'new' OR status = 'modified' OR (status = 'synchronized' AND status_last_warning != '')) AND sync_source_id = :source_id AND status_last_seen >= :last_import";
  2520. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2521. $iCountScope = $oSetScope->Count();
  2522. if ($iMaxReplica)
  2523. {
  2524. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2525. // The replica have to be ordered by id
  2526. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToSync), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sLimitDate, 'curr_pos' => $iCurrPos), $this->m_aExtDataSpec);
  2527. $oSetToProcess->SetLimit($iMaxReplica);
  2528. }
  2529. else
  2530. {
  2531. $oSetToProcess = $oSetScope;
  2532. }
  2533. $iLastReplicaProcessed = -1;
  2534. while($oReplica = $oSetToProcess->Fetch())
  2535. {
  2536. set_time_limit($iLoopTimeLimit);
  2537. $iLastReplicaProcessed = $oReplica->GetKey();
  2538. $oReplica->Synchro($this->m_oDataSource, $this->m_aReconciliationKeys, $this->m_aAttributes, $this->m_oChange, $this->m_oStatLog);
  2539. $oReplica->DBUpdateTracked($this->m_oChange);
  2540. }
  2541. if ($iMaxReplica)
  2542. {
  2543. if ($iMaxReplica < $iCountScope)
  2544. {
  2545. // Continue with this job!
  2546. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2547. return true;
  2548. }
  2549. }
  2550. // Job complete!
  2551. $this->m_oStatLog->Set('status_curr_job', 3);
  2552. $this->m_oStatLog->Set('status_curr_pos', -1);
  2553. return false;
  2554. }
  2555. /**
  2556. * Do the synchronization job #3: Delete replica depending on the obsolescence scheme
  2557. * @param integer $iMaxReplica Limit the number of replicas to process
  2558. * @param integer $iCurrPos Current position where to resume the processing
  2559. * @return true if the process must be continued
  2560. */
  2561. protected function DoJob3($iMaxReplica = null, $iCurrPos = -1)
  2562. {
  2563. $iLoopTimeLimit = MetaModel::GetConfig()->Get('max_execution_time_per_loop');
  2564. $sDeletePolicy = $this->m_oDataSource->Get('delete_policy');
  2565. if ($sDeletePolicy != 'update_then_delete')
  2566. {
  2567. // Job complete!
  2568. $this->m_oStatLog->Set('status_curr_job', 0);
  2569. $this->m_oStatLog->Set('status_curr_pos', -1);
  2570. return false;
  2571. }
  2572. $bFirstPass = ($iCurrPos == -1);
  2573. // Get all the replicas that are to be deleted
  2574. //
  2575. $oDeletionDate = $this->m_oLastFullLoadStartDate;
  2576. $iDeleteRetention = $this->m_oDataSource->Get('delete_policy_retention'); // Duration in seconds
  2577. if ($iDeleteRetention > 0)
  2578. {
  2579. $sInterval = "-$iDeleteRetention seconds";
  2580. $oDeletionDate->Modify($sInterval);
  2581. }
  2582. $sDeletionDate = $oDeletionDate->Format('Y-m-d H:i:s');
  2583. if ($bFirstPass)
  2584. {
  2585. $this->m_oStatLog->AddTrace("Deletion date: $sDeletionDate");
  2586. }
  2587. $sSelectToDelete = "SELECT SynchroReplica WHERE id > :curr_pos AND sync_source_id = :source_id AND status IN ('obsolete') AND status_last_seen < :last_import";
  2588. $oSetScope = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array() /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2589. $iCountScope = $oSetScope->Count();
  2590. if ($iMaxReplica)
  2591. {
  2592. // Consider a given subset, starting from replica iCurrPos, limited to the count of iMaxReplica
  2593. // The replica have to be ordered by id
  2594. $oSetToProcess = new DBObjectSet(DBObjectSearch::FromOQL($sSelectToDelete), array('id'=>true) /* order by*/, array('source_id' => $this->m_oDataSource->GetKey(), 'last_import' => $sDeletionDate, 'curr_pos' => $iCurrPos));
  2595. $oSetToProcess->SetLimit($iMaxReplica);
  2596. }
  2597. else
  2598. {
  2599. $oSetToProcess = $oSetScope;
  2600. }
  2601. $iLastReplicaProcessed = -1;
  2602. while($oReplica = $oSetToProcess->Fetch())
  2603. {
  2604. set_time_limit($iLoopTimeLimit);
  2605. $iLastReplicaProcessed = $oReplica->GetKey();
  2606. $this->m_oStatLog->AddTrace("Destination object to be DELETED", $oReplica);
  2607. $oReplica->DeleteDestObject($this->m_oChange, $this->m_oStatLog);
  2608. }
  2609. if ($iMaxReplica)
  2610. {
  2611. if ($iMaxReplica < $iCountScope)
  2612. {
  2613. // Continue with this job!
  2614. $this->m_oStatLog->Set('status_curr_pos', $iLastReplicaProcessed);
  2615. return true;
  2616. }
  2617. }
  2618. // Job complete!
  2619. $this->m_oStatLog->Set('status_curr_job', 0);
  2620. $this->m_oStatLog->Set('status_curr_pos', -1);
  2621. return false;
  2622. }
  2623. }
  2624. $oAdminMenu = new MenuGroup('AdminTools', 80 /* fRank */, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2625. new OQLMenuNode('DataSources', 'SELECT SynchroDataSource', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroDataSource', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2626. // new OQLMenuNode('Replicas', 'SELECT SynchroReplica', $oAdminMenu->GetIndex(), 12 /* fRank */, true, 'SynchroReplica', UR_ACTION_MODIFY, UR_ALLOWED_YES);
  2627. // new WebPageMenuNode('Test:RunSynchro', '../synchro/synchro_exec.php', $oAdminMenu->GetIndex(), 13 /* fRank */, 'SynchroDataSource');
  2628. ?>