synchrodatasource.class.inc.php 119 KB

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