attributedef.class.inc.php 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. /**
  17. * Typology for the attributes
  18. *
  19. * @author Erwan Taloc <erwan.taloc@combodo.com>
  20. * @author Romain Quetiez <romain.quetiez@combodo.com>
  21. * @author Denis Flaven <denis.flaven@combodo.com>
  22. * @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
  23. */
  24. require_once('MyHelpers.class.inc.php');
  25. require_once('ormdocument.class.inc.php');
  26. require_once('ormstopwatch.class.inc.php');
  27. require_once('ormpassword.class.inc.php');
  28. require_once('ormcaselog.class.inc.php');
  29. /**
  30. * MissingColumnException - sent if an attribute is being created but the column is missing in the row
  31. *
  32. * @package iTopORM
  33. */
  34. class MissingColumnException extends Exception
  35. {}
  36. /**
  37. * add some description here...
  38. *
  39. * @package iTopORM
  40. */
  41. define('EXTKEY_RELATIVE', 1);
  42. /**
  43. * add some description here...
  44. *
  45. * @package iTopORM
  46. */
  47. define('EXTKEY_ABSOLUTE', 2);
  48. /**
  49. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  50. *
  51. * @package iTopORM
  52. */
  53. define('DEL_MANUAL', 1);
  54. /**
  55. * Propagation of the deletion through an external key - ask the user to delete the referencing object
  56. *
  57. * @package iTopORM
  58. */
  59. define('DEL_AUTO', 2);
  60. /**
  61. * Fully silent delete... not yet implemented
  62. */
  63. define('DEL_SILENT', 2);
  64. /**
  65. * For HierarchicalKeys only: move all the children up one level automatically
  66. */
  67. define('DEL_MOVEUP', 3);
  68. /**
  69. * Attribute definition API, implemented in and many flavours (Int, String, Enum, etc.)
  70. *
  71. * @package iTopORM
  72. */
  73. abstract class AttributeDefinition
  74. {
  75. public function GetType()
  76. {
  77. return Dict::S('Core:'.get_class($this));
  78. }
  79. public function GetTypeDesc()
  80. {
  81. return Dict::S('Core:'.get_class($this).'+');
  82. }
  83. abstract public function GetEditClass();
  84. protected $m_sCode;
  85. private $m_aParams = array();
  86. protected $m_sHostClass = '!undefined!';
  87. public function Get($sParamName) {return $this->m_aParams[$sParamName];}
  88. protected function IsParam($sParamName) {return (array_key_exists($sParamName, $this->m_aParams));}
  89. protected function GetOptional($sParamName, $default)
  90. {
  91. if (array_key_exists($sParamName, $this->m_aParams))
  92. {
  93. return $this->m_aParams[$sParamName];
  94. }
  95. else
  96. {
  97. return $default;
  98. }
  99. }
  100. public function __construct($sCode, $aParams)
  101. {
  102. $this->m_sCode = $sCode;
  103. $this->m_aParams = $aParams;
  104. $this->ConsistencyCheck();
  105. }
  106. public function GetParams()
  107. {
  108. return $this->m_aParams;
  109. }
  110. public function SetHostClass($sHostClass)
  111. {
  112. $this->m_sHostClass = $sHostClass;
  113. }
  114. public function GetHostClass()
  115. {
  116. return $this->m_sHostClass;
  117. }
  118. // Note: I could factorize this code with the parameter management made for the AttributeDef class
  119. // to be overloaded
  120. static public function ListExpectedParams()
  121. {
  122. return array();
  123. }
  124. private function ConsistencyCheck()
  125. {
  126. // Check that any mandatory param has been specified
  127. //
  128. $aExpectedParams = $this->ListExpectedParams();
  129. foreach($aExpectedParams as $sParamName)
  130. {
  131. if (!array_key_exists($sParamName, $this->m_aParams))
  132. {
  133. $aBacktrace = debug_backtrace();
  134. $sTargetClass = $aBacktrace[2]["class"];
  135. $sCodeInfo = $aBacktrace[1]["file"]." - ".$aBacktrace[1]["line"];
  136. throw new Exception("ERROR missing parameter '$sParamName' in ".get_class($this)." declaration for class $sTargetClass ($sCodeInfo)");
  137. }
  138. }
  139. }
  140. // table, key field, name field
  141. public function ListDBJoins()
  142. {
  143. return "";
  144. // e.g: return array("Site", "infrid", "name");
  145. }
  146. public function GetFinalAttDef()
  147. {
  148. return $this;
  149. }
  150. public function IsDirectField() {return false;}
  151. public function IsScalar() {return false;}
  152. public function IsLinkSet() {return false;}
  153. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return false;}
  154. public function IsHierarchicalKey() {return false;}
  155. public function IsExternalField() {return false;}
  156. public function IsWritable() {return false;}
  157. public function IsNullAllowed() {return true;}
  158. public function GetCode() {return $this->m_sCode;}
  159. public function GetLabel($sDefault = null)
  160. {
  161. // If no default value is specified, let's define the most relevant one for developping purposes
  162. if (is_null($sDefault))
  163. {
  164. $sDefault = str_replace('_', ' ', $this->m_sCode);
  165. }
  166. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode, '');
  167. if (strlen($sLabel) == 0)
  168. {
  169. // Nothing found: go higher in the hierarchy (if possible)
  170. //
  171. $sLabel = $sDefault;
  172. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  173. if ($sParentClass)
  174. {
  175. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  176. {
  177. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  178. $sLabel = $oAttDef->GetLabel($sDefault);
  179. }
  180. }
  181. }
  182. return $sLabel;
  183. }
  184. /**
  185. * Get the label corresponding to the given value
  186. * To be overloaded for localized enums
  187. */
  188. public function GetValueLabel($sValue)
  189. {
  190. return $this->GetAsHTML($sValue);
  191. }
  192. public function GetLabel_Obsolete()
  193. {
  194. // Written for compatibility with a data model written prior to version 0.9.1
  195. if (array_key_exists('label', $this->m_aParams))
  196. {
  197. return $this->m_aParams['label'];
  198. }
  199. else
  200. {
  201. return $this->GetLabel();
  202. }
  203. }
  204. public function GetDescription($sDefault = null)
  205. {
  206. // If no default value is specified, let's define the most relevant one for developping purposes
  207. if (is_null($sDefault))
  208. {
  209. $sDefault = '';
  210. }
  211. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'+', '');
  212. if (strlen($sLabel) == 0)
  213. {
  214. // Nothing found: go higher in the hierarchy (if possible)
  215. //
  216. $sLabel = $sDefault;
  217. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  218. if ($sParentClass)
  219. {
  220. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  221. {
  222. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  223. $sLabel = $oAttDef->GetDescription($sDefault);
  224. }
  225. }
  226. }
  227. return $sLabel;
  228. }
  229. public function GetHelpOnEdition($sDefault = null)
  230. {
  231. // If no default value is specified, let's define the most relevant one for developping purposes
  232. if (is_null($sDefault))
  233. {
  234. $sDefault = '';
  235. }
  236. $sLabel = Dict::S('Class:'.$this->m_sHostClass.'/Attribute:'.$this->m_sCode.'?', '');
  237. if (strlen($sLabel) == 0)
  238. {
  239. // Nothing found: go higher in the hierarchy (if possible)
  240. //
  241. $sLabel = $sDefault;
  242. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  243. if ($sParentClass)
  244. {
  245. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  246. {
  247. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  248. $sLabel = $oAttDef->GetHelpOnEdition($sDefault);
  249. }
  250. }
  251. }
  252. return $sLabel;
  253. }
  254. public function GetHelpOnSmartSearch()
  255. {
  256. $aParents = array_merge(array(get_class($this) => get_class($this)), class_parents($this));
  257. foreach ($aParents as $sClass)
  258. {
  259. $sHelp = Dict::S("Core:$sClass?SmartSearch", '-missing-');
  260. if ($sHelp != '-missing-')
  261. {
  262. return $sHelp;
  263. }
  264. }
  265. return '';
  266. }
  267. public function GetDescription_Obsolete()
  268. {
  269. // Written for compatibility with a data model written prior to version 0.9.1
  270. if (array_key_exists('description', $this->m_aParams))
  271. {
  272. return $this->m_aParams['description'];
  273. }
  274. else
  275. {
  276. return $this->GetDescription();
  277. }
  278. }
  279. public function GetValuesDef() {return null;}
  280. public function GetPrerequisiteAttributes() {return array();}
  281. public function GetNullValue() {return null;}
  282. public function IsNull($proposedValue) {return is_null($proposedValue);}
  283. public function MakeRealValue($proposedValue, $oHostObj) {return $proposedValue;} // force an allowed value (type conversion and possibly forces a value as mySQL would do upon writing!)
  284. public function Equals($val1, $val2) {return ($val1 == $val2);}
  285. public function GetSQLExpressions($sPrefix = '') {return array();} // returns suffix/expression pairs (1 in most of the cases), for READING (Select)
  286. public function FromSQLToValue($aCols, $sPrefix = '') {return null;} // returns a value out of suffix/value pairs, for SELECT result interpretation
  287. public function GetSQLColumns() {return array();} // returns column/spec pairs (1 in most of the cases), for STRUCTURING (DB creation)
  288. public function GetSQLValues($value) {return array();} // returns column/value pairs (1 in most of the cases), for WRITING (Insert, Update)
  289. public function RequiresIndex() {return false;}
  290. public function GetOrderBySQLExpressions($sClassAlias)
  291. {
  292. // Note: This is the responsibility of this function to place backticks around column aliases
  293. return array('`'.$sClassAlias.$this->GetCode().'`');
  294. }
  295. public function GetOrderByHint()
  296. {
  297. return '';
  298. }
  299. // Import - differs slightly from SQL input, but identical in most cases
  300. //
  301. public function GetImportColumns() {return $this->GetSQLColumns();}
  302. public function FromImportToValue($aCols, $sPrefix = '')
  303. {
  304. $aValues = array();
  305. foreach ($this->GetSQLExpressions($sPrefix) as $sAlias => $sExpr)
  306. {
  307. // This is working, based on the assumption that importable fields
  308. // are not computed fields => the expression is the name of a column
  309. $aValues[$sPrefix.$sAlias] = $aCols[$sExpr];
  310. }
  311. return $this->FromSQLToValue($aValues, $sPrefix);
  312. }
  313. public function GetValidationPattern()
  314. {
  315. return '';
  316. }
  317. public function CheckFormat($value)
  318. {
  319. return true;
  320. }
  321. public function GetMaxSize()
  322. {
  323. return null;
  324. }
  325. public function MakeValue()
  326. {
  327. $sComputeFunc = $this->Get("compute_func");
  328. if (empty($sComputeFunc)) return null;
  329. return call_user_func($sComputeFunc);
  330. }
  331. abstract public function GetDefaultValue();
  332. //
  333. // To be overloaded in subclasses
  334. //
  335. abstract public function GetBasicFilterOperators(); // returns an array of "opCode"=>"description"
  336. abstract public function GetBasicFilterLooseOperator(); // returns an "opCode"
  337. //abstract protected GetBasicFilterHTMLInput();
  338. abstract public function GetBasicFilterSQLExpr($sOpCode, $value);
  339. public function GetFilterDefinitions()
  340. {
  341. return array();
  342. }
  343. public function GetEditValue($sValue, $oHostObj = null)
  344. {
  345. return (string)$sValue;
  346. }
  347. public function GetAsHTML($sValue, $oHostObject = null)
  348. {
  349. return Str::pure2html((string)$sValue);
  350. }
  351. public function GetAsXML($sValue, $oHostObject = null)
  352. {
  353. return Str::pure2xml((string)$sValue);
  354. }
  355. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  356. {
  357. return (string)$sValue;
  358. }
  359. public function GetAllowedValues($aArgs = array(), $sContains = '')
  360. {
  361. $oValSetDef = $this->GetValuesDef();
  362. if (!$oValSetDef) return null;
  363. return $oValSetDef->GetValues($aArgs, $sContains);
  364. }
  365. /**
  366. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  367. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  368. * does nothing special, and just calls the default (loose) operator
  369. * @param string $sSearchText The search string to analyze for smart patterns
  370. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  371. * @param Hash $aParams Values of the query parameters
  372. * @return Expression The search condition to be added (AND) to the current search
  373. */
  374. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  375. {
  376. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  377. $oRightExpr = new VariableExpression($sParamName);
  378. $sOperator = $this->GetBasicFilterLooseOperator();
  379. switch ($sOperator)
  380. {
  381. case 'Contains':
  382. $aParams[$sParamName] = "%$sSearchText%";
  383. $sSQLOperator = 'LIKE';
  384. break;
  385. default:
  386. $sSQLOperator = $sOperator;
  387. $aParams[$sParamName] = $sSearchText;
  388. }
  389. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  390. return $oNewCondition;
  391. }
  392. }
  393. /**
  394. * Set of objects directly linked to an object, and being part of its definition
  395. *
  396. * @package iTopORM
  397. */
  398. class AttributeLinkedSet extends AttributeDefinition
  399. {
  400. static public function ListExpectedParams()
  401. {
  402. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "linked_class", "ext_key_to_me", "count_min", "count_max"));
  403. }
  404. public function GetEditClass() {return "List";}
  405. public function IsWritable() {return true;}
  406. public function IsLinkSet() {return true;}
  407. public function IsIndirect() {return false;}
  408. public function GetValuesDef() {return $this->Get("allowed_values");}
  409. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  410. public function GetDefaultValue($aArgs = array())
  411. {
  412. // Note: so far, this feature is a prototype,
  413. // later, the argument 'this' should always be present in the arguments
  414. //
  415. if (($this->IsParam('default_value')) && array_key_exists('this', $aArgs))
  416. {
  417. $aValues = $this->Get('default_value')->GetValues($aArgs);
  418. $oSet = DBObjectSet::FromArray($this->Get('linked_class'), $aValues);
  419. return $oSet;
  420. }
  421. else
  422. {
  423. return DBObjectSet::FromScratch($this->Get('linked_class'));
  424. }
  425. }
  426. public function GetLinkedClass() {return $this->Get('linked_class');}
  427. public function GetExtKeyToMe() {return $this->Get('ext_key_to_me');}
  428. public function GetBasicFilterOperators() {return array();}
  429. public function GetBasicFilterLooseOperator() {return '';}
  430. public function GetBasicFilterSQLExpr($sOpCode, $value) {return '';}
  431. public function GetAsHTML($sValue, $oHostObject = null)
  432. {
  433. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  434. {
  435. $sValue->Rewind();
  436. $aItems = array();
  437. while ($oObj = $sValue->Fetch())
  438. {
  439. // Show only relevant information (hide the external key to the current object)
  440. $aAttributes = array();
  441. foreach(MetaModel::ListAttributeDefs($this->GetLinkedClass()) as $sAttCode => $oAttDef)
  442. {
  443. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  444. if ($oAttDef->IsExternalField()) continue;
  445. $sAttValue = $oObj->GetAsHTML($sAttCode);
  446. if (strlen($sAttValue) > 0)
  447. {
  448. $aAttributes[] = $sAttValue;
  449. }
  450. }
  451. $sAttributes = implode(', ', $aAttributes);
  452. $aItems[] = $sAttributes;
  453. }
  454. return implode('<br/>', $aItems);
  455. }
  456. return null;
  457. }
  458. public function GetAsXML($sValue, $oHostObject = null)
  459. {
  460. return "Sorry, no yet implemented";
  461. }
  462. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  463. {
  464. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  465. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  466. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  467. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  468. if (is_object($sValue) && ($sValue instanceof DBObjectSet))
  469. {
  470. $sValue->Rewind();
  471. $aItems = array();
  472. while ($oObj = $sValue->Fetch())
  473. {
  474. $sObjClass = get_class($oObj);
  475. // Show only relevant information (hide the external key to the current object)
  476. $aAttributes = array();
  477. foreach(MetaModel::ListAttributeDefs($sObjClass) as $sAttCode => $oAttDef)
  478. {
  479. if ($sAttCode == 'finalclass')
  480. {
  481. if ($sObjClass == $this->GetLinkedClass())
  482. {
  483. // Simplify the output if the exact class could be determined implicitely
  484. continue;
  485. }
  486. }
  487. if ($sAttCode == $this->GetExtKeyToMe()) continue;
  488. if ($oAttDef->IsExternalField()) continue;
  489. if (!$oAttDef->IsDirectField()) continue;
  490. if (!$oAttDef->IsScalar()) continue;
  491. $sAttValue = $oObj->GetAsCSV($sAttCode, $sSepValue, '');
  492. if (strlen($sAttValue) > 0)
  493. {
  494. $sAttributeData = str_replace($sAttributeQualifier, $sAttributeQualifier.$sAttributeQualifier, $sAttCode.$sSepValue.$sAttValue);
  495. $aAttributes[] = $sAttributeQualifier.$sAttributeData.$sAttributeQualifier;
  496. }
  497. }
  498. $sAttributes = implode($sSepAttribute, $aAttributes);
  499. $aItems[] = $sAttributes;
  500. }
  501. $sRes = implode($sSepItem, $aItems);
  502. }
  503. else
  504. {
  505. $sRes = '';
  506. }
  507. $sRes = str_replace($sTextQualifier, $sTextQualifier.$sTextQualifier, $sRes);
  508. $sRes = $sTextQualifier.$sRes.$sTextQualifier;
  509. return $sRes;
  510. }
  511. public function DuplicatesAllowed() {return false;} // No duplicates for 1:n links, never
  512. public function GetImportColumns()
  513. {
  514. $aColumns = array();
  515. $aColumns[$this->GetCode()] = 'TEXT';
  516. return $aColumns;
  517. }
  518. // Specific to this kind of attribute : transform a string into a value
  519. public function MakeValueFromString($sProposedValue, $sSepItem = null, $sSepAttribute = null, $sSepValue = null, $sAttributeQualifier = null)
  520. {
  521. if (is_null($sSepItem) || empty($sSepItem))
  522. {
  523. $sSepItem = MetaModel::GetConfig()->Get('link_set_item_separator');
  524. }
  525. if (is_null($sSepAttribute) || empty($sSepAttribute))
  526. {
  527. $sSepAttribute = MetaModel::GetConfig()->Get('link_set_attribute_separator');
  528. }
  529. if (is_null($sSepValue) || empty($sSepValue))
  530. {
  531. $sSepValue = MetaModel::GetConfig()->Get('link_set_value_separator');
  532. }
  533. if (is_null($sAttributeQualifier) || empty($sAttributeQualifier))
  534. {
  535. $sAttributeQualifier = MetaModel::GetConfig()->Get('link_set_attribute_qualifier');
  536. }
  537. $sTargetClass = $this->Get('linked_class');
  538. $sInput = str_replace($sSepItem, "\n", $sProposedValue);
  539. $oCSVParser = new CSVParser($sInput, $sSepAttribute, $sAttributeQualifier);
  540. $aInput = $oCSVParser->ToArray(0 /* do not skip lines */);
  541. $aLinks = array();
  542. foreach($aInput as $aRow)
  543. {
  544. // 1st - get the values, split the extkey->searchkey specs, and eventually get the finalclass value
  545. $aExtKeys = array();
  546. $aValues = array();
  547. foreach($aRow as $sCell)
  548. {
  549. $iSepPos = strpos($sCell, $sSepValue);
  550. if ($iSepPos === false)
  551. {
  552. // Houston...
  553. throw new CoreException('Wrong format for link attribute specification', array('value' => $sCell));
  554. }
  555. $sAttCode = trim(substr($sCell, 0, $iSepPos));
  556. $sValue = substr($sCell, $iSepPos + strlen($sSepValue));
  557. if (preg_match('/^(.+)->(.+)$/', $sAttCode, $aMatches))
  558. {
  559. $sKeyAttCode = $aMatches[1];
  560. $sRemoteAttCode = $aMatches[2];
  561. $aExtKeys[$sKeyAttCode][$sRemoteAttCode] = $sValue;
  562. if (!MetaModel::IsValidAttCode($sTargetClass, $sKeyAttCode))
  563. {
  564. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sKeyAttCode));
  565. }
  566. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  567. $sRemoteClass = $oKeyAttDef->GetTargetClass();
  568. if (!MetaModel::IsValidAttCode($sRemoteClass, $sRemoteAttCode))
  569. {
  570. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sRemoteClass, 'attcode' => $sRemoteAttCode));
  571. }
  572. }
  573. else
  574. {
  575. if(!MetaModel::IsValidAttCode($sTargetClass, $sAttCode))
  576. {
  577. throw new CoreException('Wrong attribute code for link attribute specification', array('class' => $sTargetClass, 'attcode' => $sAttCode));
  578. }
  579. $aValues[$sAttCode] = $sValue;
  580. }
  581. }
  582. // 2nd - Instanciate the object and set the value
  583. if (isset($aValues['finalclass']))
  584. {
  585. $sLinkClass = $aValues['finalclass'];
  586. if (!is_subclass_of($sLinkClass, $sTargetClass))
  587. {
  588. throw new CoreException('Wrong class for link attribute specification', array('requested_class' => $sLinkClass, 'expected_class' => $sTargetClass));
  589. }
  590. }
  591. elseif (MetaModel::IsAbstract($sTargetClass))
  592. {
  593. throw new CoreException('Missing finalclass for link attribute specification');
  594. }
  595. else
  596. {
  597. $sLinkClass = $sTargetClass;
  598. }
  599. $oLink = MetaModel::NewObject($sLinkClass);
  600. foreach ($aValues as $sAttCode => $sValue)
  601. {
  602. $oLink->Set($sAttCode, $sValue);
  603. }
  604. // 3rd - Set external keys from search conditions
  605. foreach ($aExtKeys as $sKeyAttCode => $aReconciliation)
  606. {
  607. $oKeyAttDef = MetaModel::GetAttributeDef($sTargetClass, $sKeyAttCode);
  608. $sKeyClass = $oKeyAttDef->GetTargetClass();
  609. $oExtKeyFilter = new CMDBSearchFilter($sKeyClass);
  610. $aReconciliationDesc = array();
  611. foreach($aReconciliation as $sRemoteAttCode => $sValue)
  612. {
  613. $oExtKeyFilter->AddCondition($sRemoteAttCode, $sValue, '=');
  614. $aReconciliationDesc[] = "$sRemoteAttCode=$sValue";
  615. }
  616. $oExtKeySet = new CMDBObjectSet($oExtKeyFilter);
  617. switch($oExtKeySet->Count())
  618. {
  619. case 0:
  620. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  621. throw new CoreException("Found no match", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  622. break;
  623. case 1:
  624. $oRemoteObj = $oExtKeySet->Fetch();
  625. $oLink->Set($sKeyAttCode, $oRemoteObj->GetKey());
  626. break;
  627. default:
  628. $sReconciliationDesc = implode(', ', $aReconciliationDesc);
  629. throw new CoreException("Found several matches", array('ext_key' => $sKeyAttCode, 'reconciliation' => $sReconciliationDesc));
  630. // Found several matches, ambiguous
  631. }
  632. }
  633. // Check (roughly) if such a link is valid
  634. $aErrors = array();
  635. foreach(MetaModel::ListAttributeDefs($sTargetClass) as $sAttCode => $oAttDef)
  636. {
  637. if ($oAttDef->IsExternalKey())
  638. {
  639. if (($oAttDef->GetTargetClass() == $this->GetHostClass()) || (is_subclass_of($this->GetHostClass(), $oAttDef->GetTargetClass())))
  640. {
  641. continue; // Don't check the key to self
  642. }
  643. }
  644. if ($oAttDef->IsWritable() && $oAttDef->IsNull($oLink->Get($sAttCode)) && !$oAttDef->IsNullAllowed())
  645. {
  646. $aErrors[] = $sAttCode;
  647. }
  648. }
  649. if (count($aErrors) > 0)
  650. {
  651. throw new CoreException("Missing value for mandatory attribute(s): ".implode(', ', $aErrors));
  652. }
  653. $aLinks[] = $oLink;
  654. }
  655. $oSet = DBObjectSet::FromArray($sTargetClass, $aLinks);
  656. return $oSet;
  657. }
  658. public function Equals($val1, $val2)
  659. {
  660. if ($val1 === $val2) return true;
  661. if (is_object($val1) != is_object($val2))
  662. {
  663. return false;
  664. }
  665. if (!is_object($val1))
  666. {
  667. // string ?
  668. // todo = implement this case ?
  669. return false;
  670. }
  671. // Both values are Object sets
  672. return $val1->HasSameContents($val2);
  673. }
  674. }
  675. /**
  676. * Set of objects linked to an object (n-n), and being part of its definition
  677. *
  678. * @package iTopORM
  679. */
  680. class AttributeLinkedSetIndirect extends AttributeLinkedSet
  681. {
  682. static public function ListExpectedParams()
  683. {
  684. return array_merge(parent::ListExpectedParams(), array("ext_key_to_remote"));
  685. }
  686. public function IsIndirect() {return true;}
  687. public function GetExtKeyToRemote() { return $this->Get('ext_key_to_remote'); }
  688. public function GetEditClass() {return "LinkedSet";}
  689. public function DuplicatesAllowed() {return $this->GetOptional("duplicates", false);} // The same object may be linked several times... or not...
  690. }
  691. /**
  692. * Abstract class implementing default filters for a DB column
  693. *
  694. * @package iTopORM
  695. */
  696. class AttributeDBFieldVoid extends AttributeDefinition
  697. {
  698. static public function ListExpectedParams()
  699. {
  700. return array_merge(parent::ListExpectedParams(), array("allowed_values", "depends_on", "sql"));
  701. }
  702. // To be overriden, used in GetSQLColumns
  703. protected function GetSQLCol() {return "VARCHAR(255)";}
  704. public function GetEditClass() {return "String";}
  705. public function GetValuesDef() {return $this->Get("allowed_values");}
  706. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  707. public function IsDirectField() {return true;}
  708. public function IsScalar() {return true;}
  709. public function IsWritable() {return true;}
  710. public function GetSQLExpr() {return $this->Get("sql");}
  711. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  712. public function IsNullAllowed() {return false;}
  713. //
  714. protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  715. public function GetSQLExpressions($sPrefix = '')
  716. {
  717. $aColumns = array();
  718. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  719. $aColumns[''] = $this->Get("sql");
  720. return $aColumns;
  721. }
  722. public function FromSQLToValue($aCols, $sPrefix = '')
  723. {
  724. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  725. return $value;
  726. }
  727. public function GetSQLValues($value)
  728. {
  729. $aValues = array();
  730. $aValues[$this->Get("sql")] = $this->ScalarToSQL($value);
  731. return $aValues;
  732. }
  733. public function GetSQLColumns()
  734. {
  735. $aColumns = array();
  736. $aColumns[$this->Get("sql")] = $this->GetSQLCol();
  737. return $aColumns;
  738. }
  739. public function GetFilterDefinitions()
  740. {
  741. return array($this->GetCode() => new FilterFromAttribute($this));
  742. }
  743. public function GetBasicFilterOperators()
  744. {
  745. return array("="=>"equals", "!="=>"differs from");
  746. }
  747. public function GetBasicFilterLooseOperator()
  748. {
  749. return "=";
  750. }
  751. public function GetBasicFilterSQLExpr($sOpCode, $value)
  752. {
  753. $sQValue = CMDBSource::Quote($value);
  754. switch ($sOpCode)
  755. {
  756. case '!=':
  757. return $this->GetSQLExpr()." != $sQValue";
  758. break;
  759. case '=':
  760. default:
  761. return $this->GetSQLExpr()." = $sQValue";
  762. }
  763. }
  764. }
  765. /**
  766. * Base class for all kind of DB attributes, with the exception of external keys
  767. *
  768. * @package iTopORM
  769. */
  770. class AttributeDBField extends AttributeDBFieldVoid
  771. {
  772. static public function ListExpectedParams()
  773. {
  774. return array_merge(parent::ListExpectedParams(), array("default_value", "is_null_allowed"));
  775. }
  776. public function GetDefaultValue() {return $this->MakeRealValue($this->Get("default_value"), null);}
  777. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  778. }
  779. /**
  780. * Map an integer column to an attribute
  781. *
  782. * @package iTopORM
  783. */
  784. class AttributeInteger extends AttributeDBField
  785. {
  786. static public function ListExpectedParams()
  787. {
  788. return parent::ListExpectedParams();
  789. //return array_merge(parent::ListExpectedParams(), array());
  790. }
  791. public function GetEditClass() {return "String";}
  792. protected function GetSQLCol() {return "INT(11)";}
  793. public function GetValidationPattern()
  794. {
  795. return "^[0-9]+$";
  796. }
  797. public function GetBasicFilterOperators()
  798. {
  799. return array(
  800. "!="=>"differs from",
  801. "="=>"equals",
  802. ">"=>"greater (strict) than",
  803. ">="=>"greater than",
  804. "<"=>"less (strict) than",
  805. "<="=>"less than",
  806. "in"=>"in"
  807. );
  808. }
  809. public function GetBasicFilterLooseOperator()
  810. {
  811. // Unless we implement an "equals approximately..." or "same order of magnitude"
  812. return "=";
  813. }
  814. public function GetBasicFilterSQLExpr($sOpCode, $value)
  815. {
  816. $sQValue = CMDBSource::Quote($value);
  817. switch ($sOpCode)
  818. {
  819. case '!=':
  820. return $this->GetSQLExpr()." != $sQValue";
  821. break;
  822. case '>':
  823. return $this->GetSQLExpr()." > $sQValue";
  824. break;
  825. case '>=':
  826. return $this->GetSQLExpr()." >= $sQValue";
  827. break;
  828. case '<':
  829. return $this->GetSQLExpr()." < $sQValue";
  830. break;
  831. case '<=':
  832. return $this->GetSQLExpr()." <= $sQValue";
  833. break;
  834. case 'in':
  835. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  836. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  837. break;
  838. case '=':
  839. default:
  840. return $this->GetSQLExpr()." = \"$value\"";
  841. }
  842. }
  843. public function GetNullValue()
  844. {
  845. return null;
  846. }
  847. public function IsNull($proposedValue)
  848. {
  849. return is_null($proposedValue);
  850. }
  851. public function MakeRealValue($proposedValue, $oHostObj)
  852. {
  853. if (is_null($proposedValue)) return null;
  854. if ($proposedValue === '') return null; // 0 is transformed into '' !
  855. return (int)$proposedValue;
  856. }
  857. public function ScalarToSQL($value)
  858. {
  859. assert(is_numeric($value) || is_null($value));
  860. return $value; // supposed to be an int
  861. }
  862. }
  863. /**
  864. * Display an integer between 0 and 100 as a percentage / horizontal bar graph
  865. *
  866. * @package iTopORM
  867. */
  868. class AttributePercentage extends AttributeInteger
  869. {
  870. public function GetAsHTML($sValue, $oHostObject = null)
  871. {
  872. $iWidth = 5; // Total width of the percentage bar graph, in em...
  873. $iValue = (int)$sValue;
  874. if ($iValue > 100)
  875. {
  876. $iValue = 100;
  877. }
  878. else if ($iValue < 0)
  879. {
  880. $iValue = 0;
  881. }
  882. if ($iValue > 90)
  883. {
  884. $sColor = "#cc3300";
  885. }
  886. else if ($iValue > 50)
  887. {
  888. $sColor = "#cccc00";
  889. }
  890. else
  891. {
  892. $sColor = "#33cc00";
  893. }
  894. $iPercentWidth = ($iWidth * $iValue) / 100;
  895. return "<div style=\"width:{$iWidth}em;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;display:inline-block;border: 1px #ccc solid;\"><div style=\"width:{$iPercentWidth}em; display:inline-block;background-color:$sColor;\">&nbsp;</div></div>&nbsp;$sValue %";
  896. }
  897. }
  898. /**
  899. * Map a decimal value column (suitable for financial computations) to an attribute
  900. * internally in PHP such numbers are represented as string. Should you want to perform
  901. * a calculation on them, it is recommended to use the BC Math functions in order to
  902. * retain the precision
  903. *
  904. * @package iTopORM
  905. */
  906. class AttributeDecimal extends AttributeDBField
  907. {
  908. static public function ListExpectedParams()
  909. {
  910. return array_merge(parent::ListExpectedParams(), array('digits', 'decimals' /* including precision */));
  911. }
  912. public function GetEditClass() {return "String";}
  913. protected function GetSQLCol() {return "DECIMAL(".$this->Get('digits').",".$this->Get('decimals').")";}
  914. public function GetValidationPattern()
  915. {
  916. $iNbDigits = $this->Get('digits');
  917. $iPrecision = $this->Get('decimals');
  918. $iNbIntegerDigits = $iNbDigits - $iPrecision - 1; // -1 because the first digit is treated separately in the pattern below
  919. return "^[-+]?[0-9]\d{0,$iNbIntegerDigits}(\.\d{0,$iPrecision})?$";
  920. }
  921. public function GetBasicFilterOperators()
  922. {
  923. return array(
  924. "!="=>"differs from",
  925. "="=>"equals",
  926. ">"=>"greater (strict) than",
  927. ">="=>"greater than",
  928. "<"=>"less (strict) than",
  929. "<="=>"less than",
  930. "in"=>"in"
  931. );
  932. }
  933. public function GetBasicFilterLooseOperator()
  934. {
  935. // Unless we implement an "equals approximately..." or "same order of magnitude"
  936. return "=";
  937. }
  938. public function GetBasicFilterSQLExpr($sOpCode, $value)
  939. {
  940. $sQValue = CMDBSource::Quote($value);
  941. switch ($sOpCode)
  942. {
  943. case '!=':
  944. return $this->GetSQLExpr()." != $sQValue";
  945. break;
  946. case '>':
  947. return $this->GetSQLExpr()." > $sQValue";
  948. break;
  949. case '>=':
  950. return $this->GetSQLExpr()." >= $sQValue";
  951. break;
  952. case '<':
  953. return $this->GetSQLExpr()." < $sQValue";
  954. break;
  955. case '<=':
  956. return $this->GetSQLExpr()." <= $sQValue";
  957. break;
  958. case 'in':
  959. if (!is_array($value)) throw new CoreException("Expected an array for argument value (sOpCode='$sOpCode')");
  960. return $this->GetSQLExpr()." IN ('".implode("', '", $value)."')";
  961. break;
  962. case '=':
  963. default:
  964. return $this->GetSQLExpr()." = \"$value\"";
  965. }
  966. }
  967. public function GetNullValue()
  968. {
  969. return null;
  970. }
  971. public function IsNull($proposedValue)
  972. {
  973. return is_null($proposedValue);
  974. }
  975. public function MakeRealValue($proposedValue, $oHostObj)
  976. {
  977. if (is_null($proposedValue)) return null;
  978. if ($proposedValue == '') return null;
  979. return (string)$proposedValue;
  980. }
  981. public function ScalarToSQL($value)
  982. {
  983. assert(is_null($value) || preg_match('/'.$this->GetValidationPattern().'/', $value));
  984. return (string)$value; // treated as a string
  985. }
  986. }
  987. /**
  988. * Map a boolean column to an attribute
  989. *
  990. * @package iTopORM
  991. */
  992. class AttributeBoolean extends AttributeInteger
  993. {
  994. static public function ListExpectedParams()
  995. {
  996. return parent::ListExpectedParams();
  997. //return array_merge(parent::ListExpectedParams(), array());
  998. }
  999. public function GetEditClass() {return "Integer";}
  1000. protected function GetSQLCol() {return "TINYINT(1)";}
  1001. public function MakeRealValue($proposedValue, $oHostObj)
  1002. {
  1003. if (is_null($proposedValue)) return null;
  1004. if ($proposedValue === '') return null;
  1005. if ((int)$proposedValue) return true;
  1006. return false;
  1007. }
  1008. public function ScalarToSQL($value)
  1009. {
  1010. if ($value) return 1;
  1011. return 0;
  1012. }
  1013. public function GetAsXML($sValue, $oHostObject = null)
  1014. {
  1015. return $sValue ? '1' : '0';
  1016. }
  1017. }
  1018. /**
  1019. * Map a varchar column (size < ?) to an attribute
  1020. *
  1021. * @package iTopORM
  1022. */
  1023. class AttributeString extends AttributeDBField
  1024. {
  1025. static public function ListExpectedParams()
  1026. {
  1027. return parent::ListExpectedParams();
  1028. //return array_merge(parent::ListExpectedParams(), array());
  1029. }
  1030. public function GetEditClass() {return "String";}
  1031. protected function GetSQLCol() {return "VARCHAR(255)";}
  1032. public function GetValidationPattern()
  1033. {
  1034. $sPattern = $this->GetOptional('validation_pattern', '');
  1035. if (empty($sPattern))
  1036. {
  1037. return parent::GetValidationPattern();
  1038. }
  1039. else
  1040. {
  1041. return $sPattern;
  1042. }
  1043. }
  1044. public function CheckFormat($value)
  1045. {
  1046. $sRegExp = $this->GetValidationPattern();
  1047. if (empty($sRegExp))
  1048. {
  1049. return true;
  1050. }
  1051. else
  1052. {
  1053. $sRegExp = str_replace('/', '\\/', $sRegExp);
  1054. return preg_match("/$sRegExp/", $value);
  1055. }
  1056. }
  1057. public function GetMaxSize()
  1058. {
  1059. return 255;
  1060. }
  1061. public function GetBasicFilterOperators()
  1062. {
  1063. return array(
  1064. "="=>"equals",
  1065. "!="=>"differs from",
  1066. "Like"=>"equals (no case)",
  1067. "NotLike"=>"differs from (no case)",
  1068. "Contains"=>"contains",
  1069. "Begins with"=>"begins with",
  1070. "Finishes with"=>"finishes with"
  1071. );
  1072. }
  1073. public function GetBasicFilterLooseOperator()
  1074. {
  1075. return "Contains";
  1076. }
  1077. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1078. {
  1079. $sQValue = CMDBSource::Quote($value);
  1080. switch ($sOpCode)
  1081. {
  1082. case '=':
  1083. case '!=':
  1084. return $this->GetSQLExpr()." $sOpCode $sQValue";
  1085. case 'Begins with':
  1086. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("$value%");
  1087. case 'Finishes with':
  1088. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value");
  1089. case 'Contains':
  1090. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  1091. case 'NotLike':
  1092. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  1093. case 'Like':
  1094. default:
  1095. return $this->GetSQLExpr()." LIKE $sQValue";
  1096. }
  1097. }
  1098. public function GetNullValue()
  1099. {
  1100. return '';
  1101. }
  1102. public function IsNull($proposedValue)
  1103. {
  1104. return ($proposedValue == '');
  1105. }
  1106. public function MakeRealValue($proposedValue, $oHostObj)
  1107. {
  1108. if (is_null($proposedValue)) return '';
  1109. return (string)$proposedValue;
  1110. }
  1111. public function ScalarToSQL($value)
  1112. {
  1113. if (!is_string($value) && !is_null($value))
  1114. {
  1115. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1116. }
  1117. return $value;
  1118. }
  1119. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1120. {
  1121. $sFrom = array("\r\n", $sTextQualifier);
  1122. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  1123. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  1124. return $sTextQualifier.$sEscaped.$sTextQualifier;
  1125. }
  1126. public function GetDisplayStyle()
  1127. {
  1128. return $this->GetOptional('display_style', 'select');
  1129. }
  1130. }
  1131. /**
  1132. * An attibute that matches an object class
  1133. *
  1134. * @package iTopORM
  1135. */
  1136. class AttributeClass extends AttributeString
  1137. {
  1138. static public function ListExpectedParams()
  1139. {
  1140. return array_merge(parent::ListExpectedParams(), array("class_category", "more_values"));
  1141. }
  1142. public function __construct($sCode, $aParams)
  1143. {
  1144. $this->m_sCode = $sCode;
  1145. $aParams["allowed_values"] = new ValueSetEnumClasses($aParams['class_category'], $aParams['more_values']);
  1146. parent::__construct($sCode, $aParams);
  1147. }
  1148. public function GetDefaultValue()
  1149. {
  1150. $sDefault = parent::GetDefaultValue();
  1151. if (!$this->IsNullAllowed() && $this->IsNull($sDefault))
  1152. {
  1153. // For this kind of attribute specifying null as default value
  1154. // is authorized even if null is not allowed
  1155. // Pick the first one...
  1156. $aClasses = $this->GetAllowedValues();
  1157. $sDefault = key($aClasses);
  1158. }
  1159. return $sDefault;
  1160. }
  1161. public function GetAsHTML($sValue, $oHostObject = null)
  1162. {
  1163. if (empty($sValue)) return '';
  1164. return MetaModel::GetName($sValue);
  1165. }
  1166. public function RequiresIndex()
  1167. {
  1168. return true;
  1169. }
  1170. public function GetBasicFilterLooseOperator()
  1171. {
  1172. return '=';
  1173. }
  1174. }
  1175. /**
  1176. * An attibute that matches one of the language codes availables in the dictionnary
  1177. *
  1178. * @package iTopORM
  1179. */
  1180. class AttributeApplicationLanguage extends AttributeString
  1181. {
  1182. static public function ListExpectedParams()
  1183. {
  1184. return parent::ListExpectedParams();
  1185. }
  1186. public function __construct($sCode, $aParams)
  1187. {
  1188. $this->m_sCode = $sCode;
  1189. $aAvailableLanguages = Dict::GetLanguages();
  1190. $aLanguageCodes = array();
  1191. foreach($aAvailableLanguages as $sLangCode => $aInfo)
  1192. {
  1193. $aLanguageCodes[$sLangCode] = $aInfo['description'].' ('.$aInfo['localized_description'].')';
  1194. }
  1195. $aParams["allowed_values"] = new ValueSetEnum($aLanguageCodes);
  1196. parent::__construct($sCode, $aParams);
  1197. }
  1198. public function RequiresIndex()
  1199. {
  1200. return true;
  1201. }
  1202. public function GetBasicFilterLooseOperator()
  1203. {
  1204. return '=';
  1205. }
  1206. }
  1207. /**
  1208. * The attribute dedicated to the finalclass automatic attribute
  1209. *
  1210. * @package iTopORM
  1211. */
  1212. class AttributeFinalClass extends AttributeString
  1213. {
  1214. public function __construct($sCode, $aParams)
  1215. {
  1216. $this->m_sCode = $sCode;
  1217. $aParams["allowed_values"] = null;
  1218. parent::__construct($sCode, $aParams);
  1219. $this->m_sValue = $this->Get("default_value");
  1220. }
  1221. public function IsWritable()
  1222. {
  1223. return false;
  1224. }
  1225. public function RequiresIndex()
  1226. {
  1227. return true;
  1228. }
  1229. public function SetFixedValue($sValue)
  1230. {
  1231. $this->m_sValue = $sValue;
  1232. }
  1233. public function GetDefaultValue()
  1234. {
  1235. return $this->m_sValue;
  1236. }
  1237. public function GetAsHTML($sValue, $oHostObject = null)
  1238. {
  1239. if (empty($sValue)) return '';
  1240. return MetaModel::GetName($sValue);
  1241. }
  1242. public function GetBasicFilterLooseOperator()
  1243. {
  1244. return '=';
  1245. }
  1246. public function GetValueLabel($sValue)
  1247. {
  1248. if (empty($sValue)) return '';
  1249. return MetaModel::GetName($sValue);
  1250. }
  1251. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1252. {
  1253. $aRawValues = MetaModel::EnumChildClasses($this->GetHostClass());
  1254. $aLocalizedValues = array();
  1255. foreach ($aRawValues as $sClass)
  1256. {
  1257. $aLocalizedValues[$sClass] = MetaModel::GetName($sClass);
  1258. }
  1259. return $aLocalizedValues;
  1260. }
  1261. }
  1262. /**
  1263. * Map a varchar column (size < ?) to an attribute that must never be shown to the user
  1264. *
  1265. * @package iTopORM
  1266. */
  1267. class AttributePassword extends AttributeString
  1268. {
  1269. static public function ListExpectedParams()
  1270. {
  1271. return parent::ListExpectedParams();
  1272. //return array_merge(parent::ListExpectedParams(), array());
  1273. }
  1274. public function GetEditClass() {return "Password";}
  1275. protected function GetSQLCol() {return "VARCHAR(64)";}
  1276. public function GetMaxSize()
  1277. {
  1278. return 64;
  1279. }
  1280. public function GetFilterDefinitions()
  1281. {
  1282. // Note: due to this, you will get an error if a password is being declared as a search criteria (see ZLists)
  1283. // not allowed to search on passwords!
  1284. return array();
  1285. }
  1286. public function GetAsHTML($sValue, $oHostObject = null)
  1287. {
  1288. if (strlen($sValue) == 0)
  1289. {
  1290. return '';
  1291. }
  1292. else
  1293. {
  1294. return '******';
  1295. }
  1296. }
  1297. }
  1298. /**
  1299. * Map a text column (size < 255) to an attribute that is encrypted in the database
  1300. * The encryption is based on a key set per iTop instance. Thus if you export your
  1301. * database (in SQL) to someone else without providing the key at the same time
  1302. * the encrypted fields will remain encrypted
  1303. *
  1304. * @package iTopORM
  1305. */
  1306. class AttributeEncryptedString extends AttributeString
  1307. {
  1308. static $sKey = null; // Encryption key used for all encrypted fields
  1309. public function __construct($sCode, $aParams)
  1310. {
  1311. parent::__construct($sCode, $aParams);
  1312. if (self::$sKey == null)
  1313. {
  1314. self::$sKey = MetaModel::GetConfig()->GetEncryptionKey();
  1315. }
  1316. }
  1317. protected function GetSQLCol() {return "TINYBLOB";}
  1318. public function GetMaxSize()
  1319. {
  1320. return 255;
  1321. }
  1322. public function GetFilterDefinitions()
  1323. {
  1324. // Note: due to this, you will get an error if a an encrypted field is declared as a search criteria (see ZLists)
  1325. // not allowed to search on encrypted fields !
  1326. return array();
  1327. }
  1328. public function MakeRealValue($proposedValue, $oHostObj)
  1329. {
  1330. if (is_null($proposedValue)) return null;
  1331. return (string)$proposedValue;
  1332. }
  1333. /**
  1334. * Decrypt the value when reading from the database
  1335. */
  1336. public function FromSQLToValue($aCols, $sPrefix = '')
  1337. {
  1338. $oSimpleCrypt = new SimpleCrypt();
  1339. $sValue = $oSimpleCrypt->Decrypt(self::$sKey, $aCols[$sPrefix]);
  1340. return $sValue;
  1341. }
  1342. /**
  1343. * Encrypt the value before storing it in the database
  1344. */
  1345. public function GetSQLValues($value)
  1346. {
  1347. $oSimpleCrypt = new SimpleCrypt();
  1348. $encryptedValue = $oSimpleCrypt->Encrypt(self::$sKey, $value);
  1349. $aValues = array();
  1350. $aValues[$this->Get("sql")] = $encryptedValue;
  1351. return $aValues;
  1352. }
  1353. }
  1354. // Wiki formatting - experimental
  1355. //
  1356. // [[<objClass>:<objName>]]
  1357. // Example: [[Server:db1.tnut.com]]
  1358. define('WIKI_OBJECT_REGEXP', '/\[\[(.+):(.+)\]\]/U');
  1359. // <url>
  1360. // Example: http://romain:trustno1@127.0.0.1:8888/iTop-trunk/modules/itop-caches/itop-caches.php?agument=machin%20#monAncre
  1361. define('WIKI_URL', "/(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?([a-z0-9-.]{3,})(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?/i");
  1362. // SHEME............. USER.................... PASSWORD...................... HOST/IP......... PORT.......... PATH...................... GET................................... ANCHOR....................
  1363. // Origin of this regexp: http://www.php.net/manual/fr/function.preg-match.php#93824
  1364. /**
  1365. * Map a text column (size > ?) to an attribute
  1366. *
  1367. * @package iTopORM
  1368. */
  1369. class AttributeText extends AttributeString
  1370. {
  1371. public function GetEditClass() {return "Text";}
  1372. protected function GetSQLCol() {return "TEXT";}
  1373. public function GetMaxSize()
  1374. {
  1375. // Is there a way to know the current limitation for mysql?
  1376. // See mysql_field_len()
  1377. return 65535;
  1378. }
  1379. static public function RenderWikiHtml($sText)
  1380. {
  1381. if (preg_match_all(WIKI_URL, $sText, $aAllMatches, PREG_SET_ORDER /* important !*/ |PREG_OFFSET_CAPTURE /* important ! */))
  1382. {
  1383. $aUrls = array();
  1384. $i = count($aAllMatches);
  1385. // Replace the URLs by an actual hyperlink <a href="...">...</a>
  1386. // Let's do it backwards so that the initial positions are not modified by the replacement
  1387. // This works if the matches are captured: in the order they occur in the string AND
  1388. // with their offset (i.e. position) inside the string
  1389. while($i > 0)
  1390. {
  1391. $i--;
  1392. $sUrl = $aAllMatches[$i][0][0]; // String corresponding to the main pattern
  1393. $iPos = $aAllMatches[$i][0][1]; // Position of the main pattern
  1394. $sText = substr_replace($sText, "<a href=\"$sUrl\">$sUrl</a>", $iPos, strlen($sUrl));
  1395. }
  1396. }
  1397. if (preg_match_all(WIKI_OBJECT_REGEXP, $sText, $aAllMatches, PREG_SET_ORDER))
  1398. {
  1399. foreach($aAllMatches as $iPos => $aMatches)
  1400. {
  1401. $sClass = $aMatches[1];
  1402. $sName = $aMatches[2];
  1403. if (MetaModel::IsValidClass($sClass))
  1404. {
  1405. $oObj = MetaModel::GetObjectByName($sClass, $sName, false /* MustBeFound */);
  1406. if (is_object($oObj))
  1407. {
  1408. // Propose a std link to the object
  1409. $sText = str_replace($aMatches[0], $oObj->GetHyperlink(), $sText);
  1410. }
  1411. else
  1412. {
  1413. // Propose a std link to the object
  1414. $sClassLabel = MetaModel::GetName($sClass);
  1415. $sText = str_replace($aMatches[0], "<span class=\"wiki_broken_link\">$sClassLabel:$sName</span>", $sText);
  1416. // Later: propose a link to create a new object
  1417. // Anyhow... there is no easy way to suggest default values based on the given FRIENDLY name
  1418. //$sText = preg_replace('/\[\[(.+):(.+)\]\]/', '<a href="'.utils::GetAbsoluteUrlAppRoot().'pages/UI.php?operation=new&class='.$sClass.'&default[att1]=xxx&default[att2]=yyy">'.$sName.'</a>', $sText);
  1419. }
  1420. }
  1421. }
  1422. }
  1423. return $sText;
  1424. }
  1425. public function GetAsHTML($sValue, $oHostObject = null)
  1426. {
  1427. $sValue = parent::GetAsHTML($sValue);
  1428. $sValue = self::RenderWikiHtml($sValue);
  1429. $aStyles = array();
  1430. if ($this->GetWidth() != '')
  1431. {
  1432. $aStyles[] = 'width:'.$this->GetWidth();
  1433. }
  1434. if ($this->GetHeight() != '')
  1435. {
  1436. $aStyles[] = 'height:'.$this->GetHeight();
  1437. }
  1438. $sStyle = '';
  1439. if (count($aStyles) > 0)
  1440. {
  1441. $aStyles[] = 'overflow:auto';
  1442. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1443. }
  1444. return "<div $sStyle>".str_replace("\n", "<br>\n", $sValue).'</div>';
  1445. }
  1446. public function GetEditValue($sValue, $oHostObj = null)
  1447. {
  1448. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1449. {
  1450. foreach($aAllMatches as $iPos => $aMatches)
  1451. {
  1452. $sClass = $aMatches[1];
  1453. $sName = $aMatches[2];
  1454. if (MetaModel::IsValidClass($sClass))
  1455. {
  1456. $sClassLabel = MetaModel::GetName($sClass);
  1457. $sValue = str_replace($aMatches[0], "[[$sClassLabel:$sName]]", $sValue);
  1458. }
  1459. }
  1460. }
  1461. return $sValue;
  1462. }
  1463. public function MakeRealValue($proposedValue, $oHostObj)
  1464. {
  1465. $sValue = $proposedValue;
  1466. if (preg_match_all(WIKI_OBJECT_REGEXP, $sValue, $aAllMatches, PREG_SET_ORDER))
  1467. {
  1468. foreach($aAllMatches as $iPos => $aMatches)
  1469. {
  1470. $sClassLabel = $aMatches[1];
  1471. $sName = $aMatches[2];
  1472. if (!MetaModel::IsValidClass($sClassLabel))
  1473. {
  1474. $sClass = MetaModel::GetClassFromLabel($sClassLabel);
  1475. if ($sClass)
  1476. {
  1477. $sValue = str_replace($aMatches[0], "[[$sClass:$sName]]", $sValue);
  1478. }
  1479. }
  1480. }
  1481. }
  1482. return $sValue;
  1483. }
  1484. public function GetAsXML($value, $oHostObject = null)
  1485. {
  1486. return Str::pure2xml($value);
  1487. }
  1488. public function GetWidth()
  1489. {
  1490. return $this->GetOptional('width', '');
  1491. }
  1492. public function GetHeight()
  1493. {
  1494. return $this->GetOptional('height', '');
  1495. }
  1496. }
  1497. /**
  1498. * Map a log to an attribute
  1499. *
  1500. * @package iTopORM
  1501. */
  1502. class AttributeLongText extends AttributeText
  1503. {
  1504. protected function GetSQLCol() {return "LONGTEXT";}
  1505. public function GetMaxSize()
  1506. {
  1507. // Is there a way to know the current limitation for mysql?
  1508. // See mysql_field_len()
  1509. return 65535*1024; // Limited... still 64 Mb!
  1510. }
  1511. }
  1512. /**
  1513. * An attibute that stores a case log (i.e journal)
  1514. *
  1515. * @package iTopORM
  1516. */
  1517. class AttributeCaseLog extends AttributeLongText
  1518. {
  1519. public function GetNullValue()
  1520. {
  1521. return '';
  1522. }
  1523. public function IsNull($proposedValue)
  1524. {
  1525. if (!($proposedValue instanceof ormCaseLog))
  1526. {
  1527. return ($proposedValue == '');
  1528. }
  1529. return ($proposedValue->GetText() == '');
  1530. }
  1531. public function ScalarToSQL($value)
  1532. {
  1533. if (!is_string($value) && !is_null($value))
  1534. {
  1535. throw new CoreWarning('Expected the attribute value to be a string', array('found_type' => gettype($value), 'value' => $value, 'class' => $this->GetCode(), 'attribute' => $this->GetHostClass()));
  1536. }
  1537. return $value;
  1538. }
  1539. public function GetEditClass() {return "CaseLog";}
  1540. public function GetEditValue($sValue, $oHostObj = null)
  1541. {
  1542. if (!($sValue instanceOf ormCaseLog))
  1543. {
  1544. return '';
  1545. }
  1546. return $sValue->GetModifiedEntry();
  1547. }
  1548. public function GetDefaultValue() {return new ormCaseLog();}
  1549. public function Equals($val1, $val2) {return ($val1->GetText() == $val2->GetText());}
  1550. // Facilitate things: allow the user to Set the value from a string
  1551. public function MakeRealValue($proposedValue, $oHostObj)
  1552. {
  1553. if (!($proposedValue instanceof ormCaseLog))
  1554. {
  1555. // Append the new value if an instance of the object is supplied
  1556. //
  1557. $oPreviousLog = null;
  1558. if ($oHostObj != null)
  1559. {
  1560. $oPreviousLog = $oHostObj->Get($this->GetCode());
  1561. if (!is_object($oPreviousLog))
  1562. {
  1563. $oPreviousLog = $oHostObj->GetOriginal($this->GetCode());;
  1564. }
  1565. }
  1566. if (is_object($oPreviousLog))
  1567. {
  1568. $oCaseLog = clone($oPreviousLog);
  1569. }
  1570. else
  1571. {
  1572. $oCaseLog = new ormCaseLog();
  1573. }
  1574. if (strlen($proposedValue) > 0)
  1575. {
  1576. $oCaseLog->AddLogEntry(parent::MakeRealValue($proposedValue, $oHostObj));
  1577. }
  1578. return $oCaseLog;
  1579. }
  1580. return $proposedValue;
  1581. }
  1582. public function GetSQLExpressions($sPrefix = '')
  1583. {
  1584. if ($sPrefix == '')
  1585. {
  1586. $sPrefix = $this->GetCode();
  1587. }
  1588. $aColumns = array();
  1589. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  1590. $aColumns[''] = $sPrefix;
  1591. $aColumns['_index'] = $sPrefix.'_index';
  1592. return $aColumns;
  1593. }
  1594. public function FromSQLToValue($aCols, $sPrefix = '')
  1595. {
  1596. if (!isset($aCols[$sPrefix]))
  1597. {
  1598. $sAvailable = implode(', ', array_keys($aCols));
  1599. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  1600. }
  1601. $sLog = $aCols[$sPrefix];
  1602. if (isset($aCols[$sPrefix.'_index']))
  1603. {
  1604. $sIndex = $aCols[$sPrefix.'_index'];
  1605. }
  1606. else
  1607. {
  1608. // For backward compatibility, allow the current state to be: 1 log, no index
  1609. $sIndex = '';
  1610. }
  1611. if (strlen($sIndex) > 0)
  1612. {
  1613. $aIndex = unserialize($sIndex);
  1614. $value = new ormCaseLog($sLog, $aIndex);
  1615. }
  1616. else
  1617. {
  1618. $value = new ormCaseLog($sLog);
  1619. }
  1620. return $value;
  1621. }
  1622. public function GetSQLValues($value)
  1623. {
  1624. if (!($value instanceOf ormCaseLog))
  1625. {
  1626. $value = new ormCaseLog('');
  1627. }
  1628. $aValues = array();
  1629. $aValues[$this->GetCode()] = $value->GetText();
  1630. $aValues[$this->GetCode().'_index'] = serialize($value->GetIndex());
  1631. return $aValues;
  1632. }
  1633. public function GetSQLColumns()
  1634. {
  1635. $aColumns = array();
  1636. $aColumns[$this->GetCode()] = 'LONGTEXT'; // 2^32 (4 Gb)
  1637. $aColumns[$this->GetCode().'_index'] = 'BLOB';
  1638. return $aColumns;
  1639. }
  1640. public function GetAsHTML($value, $oHostObject = null)
  1641. {
  1642. if ($value instanceOf ormCaseLog)
  1643. {
  1644. $sContent = $value->GetAsHTML(null, false, array(__class__, 'RenderWikiHtml'));
  1645. }
  1646. else
  1647. {
  1648. $sContent = '';
  1649. }
  1650. $aStyles = array();
  1651. if ($this->GetWidth() != '')
  1652. {
  1653. $aStyles[] = 'width:'.$this->GetWidth();
  1654. }
  1655. if ($this->GetHeight() != '')
  1656. {
  1657. $aStyles[] = 'height:'.$this->GetHeight();
  1658. }
  1659. $sStyle = '';
  1660. if (count($aStyles) > 0)
  1661. {
  1662. $sStyle = 'style="'.implode(';', $aStyles).'"';
  1663. }
  1664. return "<div class=\"caselog\" $sStyle>".$sContent.'</div>'; }
  1665. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  1666. {
  1667. if ($value instanceOf ormCaseLog)
  1668. {
  1669. return parent::GetAsCSV($value->GetText(), $sSeparator, $sTextQualifier, $oHostObject);
  1670. }
  1671. else
  1672. {
  1673. return '';
  1674. }
  1675. }
  1676. public function GetAsXML($value, $oHostObject = null)
  1677. {
  1678. if ($value instanceOf ormCaseLog)
  1679. {
  1680. return parent::GetAsXML($value->GetText(), $oHostObject);
  1681. }
  1682. else
  1683. {
  1684. return '';
  1685. }
  1686. }
  1687. }
  1688. /**
  1689. * Map a text column (size > ?), containing HTML code, to an attribute
  1690. *
  1691. * @package iTopORM
  1692. */
  1693. class AttributeHTML extends AttributeLongText
  1694. {
  1695. public function GetEditClass() {return "HTML";}
  1696. public function GetAsHTML($sValue, $oHostObject = null)
  1697. {
  1698. return $sValue;
  1699. }
  1700. }
  1701. /**
  1702. * Specialization of a string: email
  1703. *
  1704. * @package iTopORM
  1705. */
  1706. class AttributeEmailAddress extends AttributeString
  1707. {
  1708. public function GetValidationPattern()
  1709. {
  1710. // return "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";
  1711. return "^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$";
  1712. }
  1713. public function GetAsHTML($sValue, $oHostObject = null)
  1714. {
  1715. if (empty($sValue)) return '';
  1716. return '<a class="mailto" href="mailto:'.$sValue.'">'.parent::GetAsHTML($sValue).'</a>';
  1717. }
  1718. }
  1719. /**
  1720. * Specialization of a string: IP address
  1721. *
  1722. * @package iTopORM
  1723. */
  1724. class AttributeIPAddress extends AttributeString
  1725. {
  1726. public function GetValidationPattern()
  1727. {
  1728. $sNum = '(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])';
  1729. return "^($sNum\\.$sNum\\.$sNum\\.$sNum)$";
  1730. }
  1731. public function GetOrderBySQLExpressions($sClassAlias)
  1732. {
  1733. // Note: This is the responsibility of this function to place backticks around column aliases
  1734. return array('INET_ATON(`'.$sClassAlias.$this->GetCode().'`)');
  1735. }
  1736. }
  1737. /**
  1738. * Specialization of a string: OQL expression
  1739. *
  1740. * @package iTopORM
  1741. */
  1742. class AttributeOQL extends AttributeText
  1743. {
  1744. public function GetEditClass() {return "OQLExpression";}
  1745. }
  1746. /**
  1747. * Specialization of a string: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1748. *
  1749. * @package iTopORM
  1750. */
  1751. class AttributeTemplateString extends AttributeString
  1752. {
  1753. }
  1754. /**
  1755. * Specialization of a text: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1756. *
  1757. * @package iTopORM
  1758. */
  1759. class AttributeTemplateText extends AttributeText
  1760. {
  1761. }
  1762. /**
  1763. * Specialization of a HTML: template (contains iTop placeholders like $current_contact_id$ or $this->name$)
  1764. *
  1765. * @package iTopORM
  1766. */
  1767. class AttributeTemplateHTML extends AttributeText
  1768. {
  1769. public function GetEditClass() {return "HTML";}
  1770. public function GetAsHTML($sValue, $oHostObject = null)
  1771. {
  1772. return $sValue;
  1773. }
  1774. }
  1775. /**
  1776. * Map a enum column to an attribute
  1777. *
  1778. * @package iTopORM
  1779. */
  1780. class AttributeEnum extends AttributeString
  1781. {
  1782. static public function ListExpectedParams()
  1783. {
  1784. return parent::ListExpectedParams();
  1785. //return array_merge(parent::ListExpectedParams(), array());
  1786. }
  1787. public function GetEditClass() {return "String";}
  1788. protected function GetSQLCol()
  1789. {
  1790. $oValDef = $this->GetValuesDef();
  1791. if ($oValDef)
  1792. {
  1793. $aValues = CMDBSource::Quote(array_keys($oValDef->GetValues(array(), "")), true);
  1794. }
  1795. else
  1796. {
  1797. $aValues = array();
  1798. }
  1799. if (count($aValues) > 0)
  1800. {
  1801. // The syntax used here do matters
  1802. // In particular, I had to remove unnecessary spaces to
  1803. // make sure that this string will match the field type returned by the DB
  1804. // (used to perform a comparison between the current DB format and the data model)
  1805. return "ENUM(".implode(",", $aValues).")";
  1806. }
  1807. else
  1808. {
  1809. return "VARCHAR(255)"; // ENUM() is not an allowed syntax!
  1810. }
  1811. }
  1812. public function ScalarToSQL($value)
  1813. {
  1814. // Note: for strings, the null value is an empty string and it is recorded as such in the DB
  1815. // but that wasn't working for enums, because '' is NOT one of the allowed values
  1816. // that's why a null value must be forced to a real null
  1817. $value = parent::ScalarToSQL($value);
  1818. if ($this->IsNull($value))
  1819. {
  1820. return null;
  1821. }
  1822. else
  1823. {
  1824. return $value;
  1825. }
  1826. }
  1827. public function RequiresIndex()
  1828. {
  1829. return false;
  1830. }
  1831. public function GetBasicFilterOperators()
  1832. {
  1833. return parent::GetBasicFilterOperators();
  1834. }
  1835. public function GetBasicFilterLooseOperator()
  1836. {
  1837. return '=';
  1838. }
  1839. public function GetBasicFilterSQLExpr($sOpCode, $value)
  1840. {
  1841. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  1842. }
  1843. public function GetValueLabel($sValue)
  1844. {
  1845. if (is_null($sValue))
  1846. {
  1847. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1848. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, Dict::S('Enum:Undefined'));
  1849. }
  1850. else
  1851. {
  1852. $sLabel = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue, '');
  1853. if (strlen($sLabel) == 0)
  1854. {
  1855. $sLabel = str_replace('_', ' ', $sValue);
  1856. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1857. if ($sParentClass)
  1858. {
  1859. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1860. {
  1861. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1862. $sLabel = $oAttDef->GetValueLabel($sValue);
  1863. }
  1864. }
  1865. }
  1866. }
  1867. return $sLabel;
  1868. }
  1869. public function GetValueDescription($sValue)
  1870. {
  1871. if (is_null($sValue))
  1872. {
  1873. // Unless a specific label is defined for the null value of this enum, use a generic "undefined" label
  1874. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', Dict::S('Enum:Undefined'));
  1875. }
  1876. else
  1877. {
  1878. $sDescription = Dict::S('Class:'.$this->GetHostClass().'/Attribute:'.$this->GetCode().'/Value:'.$sValue.'+', '');
  1879. if (strlen($sDescription) == 0)
  1880. {
  1881. $sParentClass = MetaModel::GetParentClass($this->m_sHostClass);
  1882. if ($sParentClass)
  1883. {
  1884. if (MetaModel::IsValidAttCode($sParentClass, $this->m_sCode))
  1885. {
  1886. $oAttDef = MetaModel::GetAttributeDef($sParentClass, $this->m_sCode);
  1887. $sDescription = $oAttDef->GetValueDescription($sValue);
  1888. }
  1889. }
  1890. }
  1891. }
  1892. return $sDescription;
  1893. }
  1894. public function GetAsHTML($sValue, $oHostObject = null)
  1895. {
  1896. $sLabel = $this->GetValueLabel($sValue);
  1897. $sDescription = $this->GetValueDescription($sValue);
  1898. // later, we could imagine a detailed description in the title
  1899. return "<span title=\"$sDescription\">".parent::GetAsHtml($sLabel)."</span>";
  1900. }
  1901. public function GetEditValue($sValue, $oHostObj = null)
  1902. {
  1903. return $this->GetValueLabel($sValue);
  1904. }
  1905. public function GetAllowedValues($aArgs = array(), $sContains = '')
  1906. {
  1907. $aRawValues = parent::GetAllowedValues($aArgs, $sContains);
  1908. if (is_null($aRawValues)) return null;
  1909. $aLocalizedValues = array();
  1910. foreach ($aRawValues as $sKey => $sValue)
  1911. {
  1912. $aLocalizedValues[$sKey] = $this->GetValueLabel($sKey);
  1913. }
  1914. return $aLocalizedValues;
  1915. }
  1916. /**
  1917. * Processes the input value to align it with the values supported
  1918. * by this type of attribute. In this case: turns empty strings into nulls
  1919. * @param mixed $proposedValue The value to be set for the attribute
  1920. * @return mixed The actual value that will be set
  1921. */
  1922. public function MakeRealValue($proposedValue, $oHostObj)
  1923. {
  1924. if ($proposedValue == '') return null;
  1925. return parent::MakeRealValue($proposedValue, $oHostObj);
  1926. }
  1927. public function GetOrderByHint()
  1928. {
  1929. $aValues = $this->GetAllowedValues();
  1930. return Dict::Format('UI:OrderByHint_Values', implode(', ', $aValues));
  1931. }
  1932. }
  1933. /**
  1934. * Map a date+time column to an attribute
  1935. *
  1936. * @package iTopORM
  1937. */
  1938. class AttributeDateTime extends AttributeDBField
  1939. {
  1940. static protected function GetDateFormat()
  1941. {
  1942. return "Y-m-d H:i:s";
  1943. }
  1944. static public function ListExpectedParams()
  1945. {
  1946. return parent::ListExpectedParams();
  1947. //return array_merge(parent::ListExpectedParams(), array());
  1948. }
  1949. public function GetEditClass() {return "DateTime";}
  1950. protected function GetSQLCol() {return "TIMESTAMP";}
  1951. public static function GetAsUnixSeconds($value)
  1952. {
  1953. $oDeadlineDateTime = new DateTime($value);
  1954. $iUnixSeconds = $oDeadlineDateTime->format('U');
  1955. return $iUnixSeconds;
  1956. }
  1957. // #@# THIS HAS TO REVISED
  1958. // Having null not allowed was interpreted by mySQL
  1959. // which was creating the field with the flag 'ON UPDATE CURRENT_TIMESTAMP'
  1960. // Then, on each update of the record, the field was modified.
  1961. // We will have to specify the default value if we want to restore this option
  1962. // In fact, we could also have more verbs dedicated to the DB:
  1963. // GetDBDefaultValue()... or GetDBFieldCreationStatement()....
  1964. public function IsNullAllowed() {return true;}
  1965. public function GetDefaultValue()
  1966. {
  1967. $default = parent::GetDefaultValue();
  1968. if (!parent::IsNullAllowed())
  1969. {
  1970. if (empty($default))
  1971. {
  1972. $default = date($this->GetDateFormat());
  1973. }
  1974. }
  1975. return $default;
  1976. }
  1977. // END OF THE WORKAROUND
  1978. ///////////////////////////////////////////////////////////////
  1979. public function GetValidationPattern()
  1980. {
  1981. return "^([0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30))))( (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])){0,1}|0000-00-00 00:00:00|0000-00-00$";
  1982. }
  1983. public function GetBasicFilterOperators()
  1984. {
  1985. return array(
  1986. "="=>"equals",
  1987. "!="=>"differs from",
  1988. "<"=>"before",
  1989. "<="=>"before",
  1990. ">"=>"after (strictly)",
  1991. ">="=>"after",
  1992. "SameDay"=>"same day (strip time)",
  1993. "SameMonth"=>"same year/month",
  1994. "SameYear"=>"same year",
  1995. "Today"=>"today",
  1996. ">|"=>"after today + N days",
  1997. "<|"=>"before today + N days",
  1998. "=|"=>"equals today + N days",
  1999. );
  2000. }
  2001. public function GetBasicFilterLooseOperator()
  2002. {
  2003. // Unless we implement a "same xxx, depending on given precision" !
  2004. return "=";
  2005. }
  2006. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2007. {
  2008. $sQValue = CMDBSource::Quote($value);
  2009. switch ($sOpCode)
  2010. {
  2011. case '=':
  2012. case '!=':
  2013. case '<':
  2014. case '<=':
  2015. case '>':
  2016. case '>=':
  2017. return $this->GetSQLExpr()." $sOpCode $sQValue";
  2018. case 'SameDay':
  2019. return "DATE(".$this->GetSQLExpr().") = DATE($sQValue)";
  2020. case 'SameMonth':
  2021. return "DATE_FORMAT(".$this->GetSQLExpr().", '%Y-%m') = DATE_FORMAT($sQValue, '%Y-%m')";
  2022. case 'SameYear':
  2023. return "MONTH(".$this->GetSQLExpr().") = MONTH($sQValue)";
  2024. case 'Today':
  2025. return "DATE(".$this->GetSQLExpr().") = CURRENT_DATE()";
  2026. case '>|':
  2027. return "DATE(".$this->GetSQLExpr().") > DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2028. case '<|':
  2029. return "DATE(".$this->GetSQLExpr().") < DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2030. case '=|':
  2031. return "DATE(".$this->GetSQLExpr().") = DATE_ADD(CURRENT_DATE(), INTERVAL $sQValue DAY)";
  2032. default:
  2033. return $this->GetSQLExpr()." = $sQValue";
  2034. }
  2035. }
  2036. public function MakeRealValue($proposedValue, $oHostObj)
  2037. {
  2038. if (is_null($proposedValue))
  2039. {
  2040. return null;
  2041. }
  2042. if (is_string($proposedValue) && ($proposedValue == "") && $this->IsNullAllowed())
  2043. {
  2044. return null;
  2045. }
  2046. if (!is_numeric($proposedValue))
  2047. {
  2048. return $proposedValue;
  2049. }
  2050. return date(self::GetDateFormat(), $proposedValue);
  2051. }
  2052. public function ScalarToSQL($value)
  2053. {
  2054. if (is_null($value))
  2055. {
  2056. return null;
  2057. }
  2058. elseif (empty($value))
  2059. {
  2060. // Make a valid date for MySQL. TO DO: support NULL as a literal value for fields that can be null.
  2061. return '0000-00-00 00:00:00';
  2062. }
  2063. return $value;
  2064. }
  2065. public function GetAsHTML($value, $oHostObject = null)
  2066. {
  2067. return Str::pure2html($value);
  2068. }
  2069. public function GetAsXML($value, $oHostObject = null)
  2070. {
  2071. return Str::pure2xml($value);
  2072. }
  2073. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2074. {
  2075. $sFrom = array("\r\n", $sTextQualifier);
  2076. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  2077. $sEscaped = str_replace($sFrom, $sTo, (string)$sValue);
  2078. return '"'.$sEscaped.'"';
  2079. }
  2080. /**
  2081. * Parses a string to find some smart search patterns and build the corresponding search/OQL condition
  2082. * Each derived class is reponsible for defining and processing their own smart patterns, the base class
  2083. * does nothing special, and just calls the default (loose) operator
  2084. * @param string $sSearchText The search string to analyze for smart patterns
  2085. * @param FieldExpression The FieldExpression representing the atttribute code in this OQL query
  2086. * @param Hash $aParams Values of the query parameters
  2087. * @return Expression The search condition to be added (AND) to the current search
  2088. */
  2089. public function GetSmartConditionExpression($sSearchText, FieldExpression $oField, &$aParams)
  2090. {
  2091. // Possible smart patterns
  2092. $aPatterns = array(
  2093. 'between' => array('pattern' => '/^\[(.*),(.*)\]$/', 'operator' => 'n/a'),
  2094. 'greater than or equal' => array('pattern' => '/^>=(.*)$/', 'operator' => '>='),
  2095. 'greater than' => array('pattern' => '/^>(.*)$/', 'operator' => '>'),
  2096. 'less than or equal' => array('pattern' => '/^<=(.*)$/', 'operator' => '<='),
  2097. 'less than' => array('pattern' => '/^<(.*)$/', 'operator' => '<'),
  2098. );
  2099. $sPatternFound = '';
  2100. $aMatches = array();
  2101. foreach($aPatterns as $sPatName => $sPattern)
  2102. {
  2103. if (preg_match($sPattern['pattern'], $sSearchText, $aMatches))
  2104. {
  2105. $sPatternFound = $sPatName;
  2106. break;
  2107. }
  2108. }
  2109. switch($sPatternFound)
  2110. {
  2111. case 'between':
  2112. $sParamName1 = $oField->GetParent().'_'.$oField->GetName().'_1';
  2113. $oRightExpr = new VariableExpression($sParamName1);
  2114. $aParams[$sParamName1] = $aMatches[1];
  2115. $oCondition1 = new BinaryExpression($oField, '>=', $oRightExpr);
  2116. $sParamName2 = $oField->GetParent().'_'.$oField->GetName().'_2';
  2117. $oRightExpr = new VariableExpression($sParamName2);
  2118. $sOperator = $this->GetBasicFilterLooseOperator();
  2119. $aParams[$sParamName2] = $aMatches[2];
  2120. $oCondition2 = new BinaryExpression($oField, '<=', $oRightExpr);
  2121. $oNewCondition = new BinaryExpression($oCondition1, 'AND', $oCondition2);
  2122. break;
  2123. case 'greater than':
  2124. case 'greater than or equal':
  2125. case 'less than':
  2126. case 'less than or equal':
  2127. $sSQLOperator = $aPatterns[$sPatternFound]['operator'];
  2128. $sParamName = $oField->GetParent().'_'.$oField->GetName();
  2129. $oRightExpr = new VariableExpression($sParamName);
  2130. $aParams[$sParamName] = $aMatches[1];
  2131. $oNewCondition = new BinaryExpression($oField, $sSQLOperator, $oRightExpr);
  2132. break;
  2133. default:
  2134. $oNewCondition = parent::GetSmartConditionExpression($sSearchText, $oField, $aParams);
  2135. }
  2136. return $oNewCondition;
  2137. }
  2138. }
  2139. /**
  2140. * Store a duration as a number of seconds
  2141. *
  2142. * @package iTopORM
  2143. */
  2144. class AttributeDuration extends AttributeInteger
  2145. {
  2146. public function GetEditClass() {return "Duration";}
  2147. protected function GetSQLCol() {return "INT(11) UNSIGNED";}
  2148. public function GetNullValue() {return '0';}
  2149. public function GetDefaultValue()
  2150. {
  2151. return 0;
  2152. }
  2153. public function MakeRealValue($proposedValue, $oHostObj)
  2154. {
  2155. if (is_null($proposedValue)) return null;
  2156. if (!is_numeric($proposedValue)) return null;
  2157. if ( ((int)$proposedValue) < 0) return null;
  2158. return (int)$proposedValue;
  2159. }
  2160. public function ScalarToSQL($value)
  2161. {
  2162. if (is_null($value))
  2163. {
  2164. return null;
  2165. }
  2166. return $value;
  2167. }
  2168. public function GetAsHTML($value, $oHostObject = null)
  2169. {
  2170. return Str::pure2html(self::FormatDuration($value));
  2171. }
  2172. static function FormatDuration($duration)
  2173. {
  2174. $aDuration = self::SplitDuration($duration);
  2175. $sResult = '';
  2176. if ($duration < 60)
  2177. {
  2178. // Less than 1 min
  2179. $sResult = Dict::Format('Core:Duration_Seconds', $aDuration['seconds']);
  2180. }
  2181. else if ($duration < 3600)
  2182. {
  2183. // less than 1 hour, display it in minutes/seconds
  2184. $sResult = Dict::Format('Core:Duration_Minutes_Seconds', $aDuration['minutes'], $aDuration['seconds']);
  2185. }
  2186. else if ($duration < 86400)
  2187. {
  2188. // Less than 1 day, display it in hours/minutes/seconds
  2189. $sResult = Dict::Format('Core:Duration_Hours_Minutes_Seconds', $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2190. }
  2191. else
  2192. {
  2193. // more than 1 day, display it in days/hours/minutes/seconds
  2194. $sResult = Dict::Format('Core:Duration_Days_Hours_Minutes_Seconds', $aDuration['days'], $aDuration['hours'], $aDuration['minutes'], $aDuration['seconds']);
  2195. }
  2196. return $sResult;
  2197. }
  2198. static function SplitDuration($duration)
  2199. {
  2200. $duration = (int) $duration;
  2201. $days = floor($duration / 86400);
  2202. $hours = floor(($duration - (86400*$days)) / 3600);
  2203. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2204. $seconds = ($duration % 60); // modulo
  2205. return array( 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds );
  2206. }
  2207. }
  2208. /**
  2209. * Map a date+time column to an attribute
  2210. *
  2211. * @package iTopORM
  2212. */
  2213. class AttributeDate extends AttributeDateTime
  2214. {
  2215. const MYDATEFORMAT = "Y-m-d";
  2216. static protected function GetDateFormat()
  2217. {
  2218. return "Y-m-d";
  2219. }
  2220. static public function ListExpectedParams()
  2221. {
  2222. return parent::ListExpectedParams();
  2223. //return array_merge(parent::ListExpectedParams(), array());
  2224. }
  2225. public function GetEditClass() {return "Date";}
  2226. protected function GetSQLCol() {return "DATE";}
  2227. public function GetValidationPattern()
  2228. {
  2229. return "^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$";
  2230. }
  2231. }
  2232. /**
  2233. * A dead line stored as a date & time
  2234. * The only difference with the DateTime attribute is the display:
  2235. * relative to the current time
  2236. */
  2237. class AttributeDeadline extends AttributeDateTime
  2238. {
  2239. public function GetAsHTML($value, $oHostObject = null)
  2240. {
  2241. $sResult = '';
  2242. if ($value !== null)
  2243. {
  2244. $iValue = AttributeDateTime::GetAsUnixSeconds($value);
  2245. $sDate = parent::GetAsHTML($value, $oHostObject);
  2246. $difference = $iValue - time();
  2247. if ($difference >= 0)
  2248. {
  2249. $sDifference = self::FormatDuration($difference);
  2250. }
  2251. else
  2252. {
  2253. $sDifference = Dict::Format('UI:DeadlineMissedBy_duration', self::FormatDuration(-$difference));
  2254. }
  2255. $sFormat = MetaModel::GetConfig()->Get('deadline_format', '$difference$');
  2256. $sResult = str_replace(array('$date$', '$difference$'), array($sDate, $sDifference), $sFormat);
  2257. }
  2258. return $sResult;
  2259. }
  2260. static function FormatDuration($duration)
  2261. {
  2262. $days = floor($duration / 86400);
  2263. $hours = floor(($duration - (86400*$days)) / 3600);
  2264. $minutes = floor(($duration - (86400*$days + 3600*$hours)) / 60);
  2265. $sResult = '';
  2266. if ($duration < 60)
  2267. {
  2268. // Less than 1 min
  2269. $sResult =Dict::S('UI:Deadline_LessThan1Min');
  2270. }
  2271. else if ($duration < 3600)
  2272. {
  2273. // less than 1 hour, display it in minutes
  2274. $sResult =Dict::Format('UI:Deadline_Minutes', $minutes);
  2275. }
  2276. else if ($duration < 86400)
  2277. {
  2278. // Less that 1 day, display it in hours/minutes
  2279. $sResult =Dict::Format('UI:Deadline_Hours_Minutes', $hours, $minutes);
  2280. }
  2281. else
  2282. {
  2283. // Less that 1 day, display it in hours/minutes
  2284. $sResult =Dict::Format('UI:Deadline_Days_Hours_Minutes', $days, $hours, $minutes);
  2285. }
  2286. return $sResult;
  2287. }
  2288. }
  2289. /**
  2290. * Map a foreign key to an attribute
  2291. * AttributeExternalKey and AttributeExternalField may be an external key
  2292. * the difference is that AttributeExternalKey corresponds to a column into the defined table
  2293. * where an AttributeExternalField corresponds to a column into another table (class)
  2294. *
  2295. * @package iTopORM
  2296. */
  2297. class AttributeExternalKey extends AttributeDBFieldVoid
  2298. {
  2299. static public function ListExpectedParams()
  2300. {
  2301. return array_merge(parent::ListExpectedParams(), array("targetclass", "is_null_allowed", "on_target_delete"));
  2302. }
  2303. public function GetEditClass() {return "ExtKey";}
  2304. protected function GetSQLCol() {return "INT(11)";}
  2305. public function RequiresIndex()
  2306. {
  2307. return true;
  2308. }
  2309. public function IsExternalKey($iType = EXTKEY_RELATIVE) {return true;}
  2310. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->Get("targetclass");}
  2311. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2312. public function GetKeyAttCode() {return $this->GetCode();}
  2313. public function GetDisplayStyle() { return $this->GetOptional('display_style', 'select'); }
  2314. public function GetDefaultValue() {return 0;}
  2315. public function IsNullAllowed() {return $this->Get("is_null_allowed");}
  2316. public function GetBasicFilterOperators()
  2317. {
  2318. return parent::GetBasicFilterOperators();
  2319. }
  2320. public function GetBasicFilterLooseOperator()
  2321. {
  2322. return parent::GetBasicFilterLooseOperator();
  2323. }
  2324. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2325. {
  2326. return parent::GetBasicFilterSQLExpr($sOpCode, $value);
  2327. }
  2328. // overloaded here so that an ext key always have the answer to
  2329. // "what are your possible values?"
  2330. public function GetValuesDef()
  2331. {
  2332. $oValSetDef = $this->Get("allowed_values");
  2333. if (!$oValSetDef)
  2334. {
  2335. // Let's propose every existing value
  2336. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2337. }
  2338. return $oValSetDef;
  2339. }
  2340. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2341. {
  2342. //throw new Exception("GetAllowedValues on ext key has been deprecated");
  2343. try
  2344. {
  2345. return parent::GetAllowedValues($aArgs, $sContains);
  2346. }
  2347. catch (MissingQueryArgument $e)
  2348. {
  2349. // Some required arguments could not be found, enlarge to any existing value
  2350. $oValSetDef = new ValueSetObjects('SELECT '.$this->GetTargetClass());
  2351. return $oValSetDef->GetValues($aArgs, $sContains);
  2352. }
  2353. }
  2354. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2355. {
  2356. $oValSetDef = $this->GetValuesDef();
  2357. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2358. return $oSet;
  2359. }
  2360. public function GetDeletionPropagationOption()
  2361. {
  2362. return $this->Get("on_target_delete");
  2363. }
  2364. public function GetNullValue()
  2365. {
  2366. return 0;
  2367. }
  2368. public function IsNull($proposedValue)
  2369. {
  2370. return ($proposedValue == 0);
  2371. }
  2372. public function MakeRealValue($proposedValue, $oHostObj)
  2373. {
  2374. if (is_null($proposedValue)) return 0;
  2375. if ($proposedValue === '') return 0;
  2376. if (MetaModel::IsValidObject($proposedValue)) return $proposedValue->GetKey();
  2377. return (int)$proposedValue;
  2378. }
  2379. public function GetMaximumComboLength()
  2380. {
  2381. return $this->GetOptional('max_combo_length', MetaModel::GetConfig()->Get('max_combo_length'));
  2382. }
  2383. public function GetMinAutoCompleteChars()
  2384. {
  2385. return $this->GetOptional('min_autocomplete_chars', MetaModel::GetConfig()->Get('min_autocomplete_chars'));
  2386. }
  2387. public function AllowTargetCreation()
  2388. {
  2389. return $this->GetOptional('allow_target_creation', MetaModel::GetConfig()->Get('allow_target_creation'));
  2390. }
  2391. }
  2392. /**
  2393. * Special kind of External Key to manage a hierarchy of objects
  2394. */
  2395. class AttributeHierarchicalKey extends AttributeExternalKey
  2396. {
  2397. protected $m_sTargetClass;
  2398. static public function ListExpectedParams()
  2399. {
  2400. $aParams = parent::ListExpectedParams();
  2401. $idx = array_search('targetclass', $aParams);
  2402. unset($aParams[$idx]);
  2403. $idx = array_search('jointype', $aParams);
  2404. unset($aParams[$idx]);
  2405. return $aParams; // TODO: mettre les bons parametres ici !!
  2406. }
  2407. public function GetEditClass() {return "ExtKey";}
  2408. public function RequiresIndex()
  2409. {
  2410. return true;
  2411. }
  2412. /*
  2413. * The target class is the class for which the attribute has been defined first
  2414. */
  2415. public function SetHostClass($sHostClass)
  2416. {
  2417. if (!isset($this->m_sTargetClass))
  2418. {
  2419. $this->m_sTargetClass = $sHostClass;
  2420. }
  2421. parent::SetHostClass($sHostClass);
  2422. }
  2423. public function IsHierarchicalKey() {return true;}
  2424. public function GetTargetClass($iType = EXTKEY_RELATIVE) {return $this->m_sTargetClass;}
  2425. public function GetKeyAttDef($iType = EXTKEY_RELATIVE){return $this;}
  2426. public function GetKeyAttCode() {return $this->GetCode();}
  2427. public function GetBasicFilterOperators()
  2428. {
  2429. return parent::GetBasicFilterOperators();
  2430. }
  2431. public function GetBasicFilterLooseOperator()
  2432. {
  2433. return parent::GetBasicFilterLooseOperator();
  2434. }
  2435. public function GetSQLColumns()
  2436. {
  2437. $aColumns = array();
  2438. $aColumns[$this->GetCode()] = 'INT(11)';
  2439. $aColumns[$this->GetSQLLeft()] = 'INT(11)';
  2440. $aColumns[$this->GetSQLRight()] = 'INT(11)';
  2441. return $aColumns;
  2442. }
  2443. public function GetSQLRight()
  2444. {
  2445. return $this->GetCode().'_right';
  2446. }
  2447. public function GetSQLLeft()
  2448. {
  2449. return $this->GetCode().'_left';
  2450. }
  2451. public function GetSQLValues($value)
  2452. {
  2453. if (!is_array($value))
  2454. {
  2455. $aValues[$this->GetCode()] = $value;
  2456. }
  2457. else
  2458. {
  2459. $aValues = array();
  2460. $aValues[$this->GetCode()] = $value[$this->GetCode()];
  2461. $aValues[$this->GetSQLRight()] = $value[$this->GetSQLRight()];
  2462. $aValues[$this->GetSQLLeft()] = $value[$this->GetSQLLeft()];
  2463. }
  2464. return $aValues;
  2465. }
  2466. public function GetAllowedValues($aArgs = array(), $sContains = '')
  2467. {
  2468. if (array_key_exists('this', $aArgs))
  2469. {
  2470. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2471. // "under" themselves
  2472. $iRootId = $aArgs['this']->GetKey();
  2473. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2474. {
  2475. $oValSetDef = $this->GetValuesDef();
  2476. $sClass = $this->m_sTargetClass;
  2477. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2478. $oValSetDef->AddCondition($oFilter);
  2479. }
  2480. }
  2481. else
  2482. {
  2483. return parent::GetAllowedValues($aArgs, $sContains);
  2484. }
  2485. }
  2486. public function GetAllowedValuesAsObjectSet($aArgs = array(), $sContains = '')
  2487. {
  2488. $oValSetDef = $this->GetValuesDef();
  2489. if (array_key_exists('this', $aArgs))
  2490. {
  2491. // Hierarchical keys have one more constraint: the "parent value" cannot be
  2492. // "under" themselves
  2493. $iRootId = $aArgs['this']->GetKey();
  2494. if ($iRootId > 0) // ignore objects that do no exist in the database...
  2495. {
  2496. $aValuesSetDef = $this->GetValuesDef();
  2497. $sClass = $this->m_sTargetClass;
  2498. $oFilter = DBObjectSearch::FromOQL("SELECT $sClass AS node JOIN $sClass AS root ON node.".$this->GetCode()." NOT BELOW root.id WHERE root.id = $iRootId");
  2499. $oValSetDef->AddCondition($oFilter);
  2500. }
  2501. }
  2502. $oSet = $oValSetDef->ToObjectSet($aArgs, $sContains);
  2503. return $oSet;
  2504. }
  2505. }
  2506. /**
  2507. * An attribute which corresponds to an external key (direct or indirect)
  2508. *
  2509. * @package iTopORM
  2510. */
  2511. class AttributeExternalField extends AttributeDefinition
  2512. {
  2513. static public function ListExpectedParams()
  2514. {
  2515. return array_merge(parent::ListExpectedParams(), array("extkey_attcode", "target_attcode"));
  2516. }
  2517. public function GetEditClass() {return "ExtField";}
  2518. public function GetFinalAttDef()
  2519. {
  2520. $oExtAttDef = $this->GetExtAttDef();
  2521. return $oExtAttDef->GetFinalAttDef();
  2522. }
  2523. protected function GetSQLCol()
  2524. {
  2525. // throw new CoreException("external attribute: does it make any sense to request its type ?");
  2526. $oExtAttDef = $this->GetExtAttDef();
  2527. return $oExtAttDef->GetSQLCol();
  2528. }
  2529. public function GetSQLExpressions($sPrefix = '')
  2530. {
  2531. if ($sPrefix == '')
  2532. {
  2533. return array('' => $this->GetCode());
  2534. }
  2535. else
  2536. {
  2537. return $sPrefix;
  2538. }
  2539. }
  2540. public function GetLabel($sDefault = null)
  2541. {
  2542. $sLabel = parent::GetLabel('');
  2543. if (strlen($sLabel) == 0)
  2544. {
  2545. $oRemoteAtt = $this->GetExtAttDef();
  2546. $sLabel = $oRemoteAtt->GetLabel($this->m_sCode);
  2547. }
  2548. return $sLabel;
  2549. }
  2550. public function GetDescription($sDefault = null)
  2551. {
  2552. $sLabel = parent::GetDescription('');
  2553. if (strlen($sLabel) == 0)
  2554. {
  2555. $oRemoteAtt = $this->GetExtAttDef();
  2556. $sLabel = $oRemoteAtt->GetDescription('');
  2557. }
  2558. return $sLabel;
  2559. }
  2560. public function GetHelpOnEdition($sDefault = null)
  2561. {
  2562. $sLabel = parent::GetHelpOnEdition('');
  2563. if (strlen($sLabel) == 0)
  2564. {
  2565. $oRemoteAtt = $this->GetExtAttDef();
  2566. $sLabel = $oRemoteAtt->GetHelpOnEdition('');
  2567. }
  2568. return $sLabel;
  2569. }
  2570. public function IsExternalKey($iType = EXTKEY_RELATIVE)
  2571. {
  2572. switch($iType)
  2573. {
  2574. case EXTKEY_ABSOLUTE:
  2575. // see further
  2576. $oRemoteAtt = $this->GetExtAttDef();
  2577. return $oRemoteAtt->IsExternalKey($iType);
  2578. case EXTKEY_RELATIVE:
  2579. return false;
  2580. default:
  2581. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2582. }
  2583. }
  2584. public function GetTargetClass($iType = EXTKEY_RELATIVE)
  2585. {
  2586. return $this->GetKeyAttDef($iType)->GetTargetClass();
  2587. }
  2588. public function IsExternalField() {return true;}
  2589. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  2590. public function GetExtAttCode() {return $this->Get("target_attcode");}
  2591. public function GetKeyAttDef($iType = EXTKEY_RELATIVE)
  2592. {
  2593. switch($iType)
  2594. {
  2595. case EXTKEY_ABSOLUTE:
  2596. // see further
  2597. $oRemoteAtt = $this->GetExtAttDef();
  2598. if ($oRemoteAtt->IsExternalField())
  2599. {
  2600. return $oRemoteAtt->GetKeyAttDef(EXTKEY_ABSOLUTE);
  2601. }
  2602. else if ($oRemoteAtt->IsExternalKey())
  2603. {
  2604. return $oRemoteAtt;
  2605. }
  2606. return $this->GetKeyAttDef(EXTKEY_RELATIVE); // which corresponds to the code hereafter !
  2607. case EXTKEY_RELATIVE:
  2608. return MetaModel::GetAttributeDef($this->GetHostClass(), $this->Get("extkey_attcode"));
  2609. default:
  2610. throw new CoreException("Unexpected value for argument iType: '$iType'");
  2611. }
  2612. }
  2613. public function GetExtAttDef()
  2614. {
  2615. $oKeyAttDef = $this->GetKeyAttDef();
  2616. $oExtAttDef = MetaModel::GetAttributeDef($oKeyAttDef->GetTargetClass(), $this->Get("target_attcode"));
  2617. if (!is_object($oExtAttDef)) throw new CoreException("Invalid external field ".$this->GetCode()." in class ".$this->GetHostClass().". The class ".$oKeyAttDef->GetTargetClass()." has no attribute ".$this->Get("target_attcode"));
  2618. return $oExtAttDef;
  2619. }
  2620. public function GetSQLExpr()
  2621. {
  2622. $oExtAttDef = $this->GetExtAttDef();
  2623. return $oExtAttDef->GetSQLExpr();
  2624. }
  2625. public function GetDefaultValue()
  2626. {
  2627. $oExtAttDef = $this->GetExtAttDef();
  2628. return $oExtAttDef->GetDefaultValue();
  2629. }
  2630. public function IsNullAllowed()
  2631. {
  2632. $oExtAttDef = $this->GetExtAttDef();
  2633. return $oExtAttDef->IsNullAllowed();
  2634. }
  2635. public function IsScalar()
  2636. {
  2637. $oExtAttDef = $this->GetExtAttDef();
  2638. return $oExtAttDef->IsScalar();
  2639. }
  2640. public function GetFilterDefinitions()
  2641. {
  2642. return array($this->GetCode() => new FilterFromAttribute($this));
  2643. }
  2644. public function GetBasicFilterOperators()
  2645. {
  2646. $oExtAttDef = $this->GetExtAttDef();
  2647. return $oExtAttDef->GetBasicFilterOperators();
  2648. }
  2649. public function GetBasicFilterLooseOperator()
  2650. {
  2651. $oExtAttDef = $this->GetExtAttDef();
  2652. return $oExtAttDef->GetBasicFilterLooseOperator();
  2653. }
  2654. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2655. {
  2656. $oExtAttDef = $this->GetExtAttDef();
  2657. return $oExtAttDef->GetBasicFilterSQLExpr($sOpCode, $value);
  2658. }
  2659. public function GetNullValue()
  2660. {
  2661. $oExtAttDef = $this->GetExtAttDef();
  2662. return $oExtAttDef->GetNullValue();
  2663. }
  2664. public function IsNull($proposedValue)
  2665. {
  2666. $oExtAttDef = $this->GetExtAttDef();
  2667. return $oExtAttDef->IsNull($proposedValue);
  2668. }
  2669. public function MakeRealValue($proposedValue, $oHostObj)
  2670. {
  2671. $oExtAttDef = $this->GetExtAttDef();
  2672. return $oExtAttDef->MakeRealValue($proposedValue, $oHostObj);
  2673. }
  2674. public function ScalarToSQL($value)
  2675. {
  2676. // This one could be used in case of filtering only
  2677. $oExtAttDef = $this->GetExtAttDef();
  2678. return $oExtAttDef->ScalarToSQL($value);
  2679. }
  2680. // Do not overload GetSQLExpression here because this is handled in the joins
  2681. //public function GetSQLExpressions($sPrefix = '') {return array();}
  2682. // Here, we get the data...
  2683. public function FromSQLToValue($aCols, $sPrefix = '')
  2684. {
  2685. $oExtAttDef = $this->GetExtAttDef();
  2686. return $oExtAttDef->FromSQLToValue($aCols, $sPrefix);
  2687. }
  2688. public function GetAsHTML($value, $oHostObject = null)
  2689. {
  2690. $oExtAttDef = $this->GetExtAttDef();
  2691. return $oExtAttDef->GetAsHTML($value);
  2692. }
  2693. public function GetAsXML($value, $oHostObject = null)
  2694. {
  2695. $oExtAttDef = $this->GetExtAttDef();
  2696. return $oExtAttDef->GetAsXML($value);
  2697. }
  2698. public function GetAsCSV($value, $sSeparator = ',', $sTestQualifier = '"', $oHostObject = null)
  2699. {
  2700. $oExtAttDef = $this->GetExtAttDef();
  2701. return $oExtAttDef->GetAsCSV($value, $sSeparator, $sTestQualifier);
  2702. }
  2703. }
  2704. /**
  2705. * Map a varchar column to an URL (formats the ouput in HMTL)
  2706. *
  2707. * @package iTopORM
  2708. */
  2709. class AttributeURL extends AttributeString
  2710. {
  2711. static public function ListExpectedParams()
  2712. {
  2713. //return parent::ListExpectedParams();
  2714. return array_merge(parent::ListExpectedParams(), array("target"));
  2715. }
  2716. public function GetEditClass() {return "String";}
  2717. public function GetAsHTML($sValue, $oHostObject = null)
  2718. {
  2719. $sTarget = $this->Get("target");
  2720. if (empty($sTarget)) $sTarget = "_blank";
  2721. $sLabel = Str::pure2html($sValue);
  2722. if (strlen($sLabel) > 40)
  2723. {
  2724. // Truncate the length to about 40 characters, by removing the middle
  2725. $sLabel = substr($sLabel, 0, 25).'...'.substr($sLabel, -15);
  2726. }
  2727. return "<a target=\"$sTarget\" href=\"$sValue\">$sLabel</a>";
  2728. }
  2729. public function GetValidationPattern()
  2730. {
  2731. return "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*$";
  2732. }
  2733. }
  2734. /**
  2735. * A blob is an ormDocument, it is stored as several columns in the database
  2736. *
  2737. * @package iTopORM
  2738. */
  2739. class AttributeBlob extends AttributeDefinition
  2740. {
  2741. static public function ListExpectedParams()
  2742. {
  2743. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  2744. }
  2745. public function GetEditClass() {return "Document";}
  2746. public function IsDirectField() {return true;}
  2747. public function IsScalar() {return true;}
  2748. public function IsWritable() {return true;}
  2749. public function GetDefaultValue() {return "";}
  2750. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2751. // Facilitate things: allow the user to Set the value from a string
  2752. public function MakeRealValue($proposedValue, $oHostObj)
  2753. {
  2754. if (!is_object($proposedValue))
  2755. {
  2756. return new ormDocument($proposedValue, 'text/plain');
  2757. }
  2758. return $proposedValue;
  2759. }
  2760. public function GetSQLExpressions($sPrefix = '')
  2761. {
  2762. if ($sPrefix == '')
  2763. {
  2764. $sPrefix = $this->GetCode();
  2765. }
  2766. $aColumns = array();
  2767. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2768. $aColumns[''] = $sPrefix.'_mimetype';
  2769. $aColumns['_data'] = $sPrefix.'_data';
  2770. $aColumns['_filename'] = $sPrefix.'_filename';
  2771. return $aColumns;
  2772. }
  2773. public function FromSQLToValue($aCols, $sPrefix = '')
  2774. {
  2775. if (!isset($aCols[$sPrefix]))
  2776. {
  2777. $sAvailable = implode(', ', array_keys($aCols));
  2778. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  2779. }
  2780. $sMimeType = $aCols[$sPrefix];
  2781. if (!isset($aCols[$sPrefix.'_data']))
  2782. {
  2783. $sAvailable = implode(', ', array_keys($aCols));
  2784. throw new MissingColumnException("Missing column '".$sPrefix."_data' from {$sAvailable}");
  2785. }
  2786. $data = $aCols[$sPrefix.'_data'];
  2787. if (!isset($aCols[$sPrefix.'_filename']))
  2788. {
  2789. $sAvailable = implode(', ', array_keys($aCols));
  2790. throw new MissingColumnException("Missing column '".$sPrefix."_filename' from {$sAvailable}");
  2791. }
  2792. $sFileName = $aCols[$sPrefix.'_filename'];
  2793. $value = new ormDocument($data, $sMimeType, $sFileName);
  2794. return $value;
  2795. }
  2796. public function GetSQLValues($value)
  2797. {
  2798. // #@# Optimization: do not load blobs anytime
  2799. // As per mySQL doc, selecting blob columns will prevent mySQL from
  2800. // using memory in case a temporary table has to be created
  2801. // (temporary tables created on disk)
  2802. // We will have to remove the blobs from the list of attributes when doing the select
  2803. // then the use of Get() should finalize the load
  2804. if ($value instanceOf ormDocument)
  2805. {
  2806. $aValues = array();
  2807. $aValues[$this->GetCode().'_data'] = $value->GetData();
  2808. $aValues[$this->GetCode().'_mimetype'] = $value->GetMimeType();
  2809. $aValues[$this->GetCode().'_filename'] = $value->GetFileName();
  2810. }
  2811. else
  2812. {
  2813. $aValues = array();
  2814. $aValues[$this->GetCode().'_data'] = '';
  2815. $aValues[$this->GetCode().'_mimetype'] = '';
  2816. $aValues[$this->GetCode().'_filename'] = '';
  2817. }
  2818. return $aValues;
  2819. }
  2820. public function GetSQLColumns()
  2821. {
  2822. $aColumns = array();
  2823. $aColumns[$this->GetCode().'_data'] = 'LONGBLOB'; // 2^32 (4 Gb)
  2824. $aColumns[$this->GetCode().'_mimetype'] = 'VARCHAR(255)';
  2825. $aColumns[$this->GetCode().'_filename'] = 'VARCHAR(255)';
  2826. return $aColumns;
  2827. }
  2828. public function GetFilterDefinitions()
  2829. {
  2830. return array();
  2831. // still not working... see later...
  2832. return array(
  2833. $this->GetCode().'->filename' => new FilterFromAttribute($this, '_filename'),
  2834. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype'),
  2835. $this->GetCode().'_mimetype' => new FilterFromAttribute($this, '_mimetype')
  2836. );
  2837. }
  2838. public function GetBasicFilterOperators()
  2839. {
  2840. return array();
  2841. }
  2842. public function GetBasicFilterLooseOperator()
  2843. {
  2844. return '=';
  2845. }
  2846. public function GetBasicFilterSQLExpr($sOpCode, $value)
  2847. {
  2848. return 'true';
  2849. }
  2850. public function GetAsHTML($value, $oHostObject = null)
  2851. {
  2852. if (is_object($value))
  2853. {
  2854. return $value->GetAsHTML();
  2855. }
  2856. }
  2857. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  2858. {
  2859. return ''; // Not exportable in CSV !
  2860. }
  2861. public function GetAsXML($value, $oHostObject = null)
  2862. {
  2863. return ''; // Not exportable in XML, or as CDATA + some subtags ??
  2864. }
  2865. }
  2866. /**
  2867. * A stop watch is an ormStopWatch object, it is stored as several columns in the database
  2868. *
  2869. * @package iTopORM
  2870. */
  2871. class AttributeStopWatch extends AttributeDefinition
  2872. {
  2873. static public function ListExpectedParams()
  2874. {
  2875. // The list of thresholds must be an array of iPercent => array of 'option' => value
  2876. return array_merge(parent::ListExpectedParams(), array("states", "goal_computing", "working_time_computing", "thresholds"));
  2877. }
  2878. public function GetEditClass() {return "StopWatch";}
  2879. public function IsDirectField() {return true;}
  2880. public function IsScalar() {return true;}
  2881. public function IsWritable() {return false;}
  2882. public function GetDefaultValue() {return $this->NewStopWatch();}
  2883. //public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  2884. public function GetStates()
  2885. {
  2886. return $this->Get('states');
  2887. }
  2888. /**
  2889. * Construct a brand new (but configured) stop watch
  2890. */
  2891. public function NewStopWatch()
  2892. {
  2893. $oSW = new ormStopWatch();
  2894. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  2895. {
  2896. $oSW->DefineThreshold($iThreshold);
  2897. }
  2898. return $oSW;
  2899. }
  2900. // Facilitate things: allow the user to Set the value from a string
  2901. public function MakeRealValue($proposedValue, $oHostObj)
  2902. {
  2903. if (!$proposedValue instanceof ormStopWatch)
  2904. {
  2905. return $this->NewStopWatch();
  2906. }
  2907. return $proposedValue;
  2908. }
  2909. public function GetSQLExpressions($sPrefix = '')
  2910. {
  2911. if ($sPrefix == '')
  2912. {
  2913. $sPrefix = $this->GetCode();
  2914. }
  2915. $aColumns = array();
  2916. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  2917. $aColumns[''] = $sPrefix.'_timespent';
  2918. $aColumns['_started'] = $sPrefix.'_started';
  2919. $aColumns['_laststart'] = $sPrefix.'_laststart';
  2920. $aColumns['_stopped'] = $sPrefix.'_stopped';
  2921. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  2922. {
  2923. $sThPrefix = '_'.$iThreshold;
  2924. $aColumns[$sThPrefix.'_deadline'] = $sPrefix.$sThPrefix.'_deadline';
  2925. $aColumns[$sThPrefix.'_passed'] = $sPrefix.$sThPrefix.'_passed';
  2926. $aColumns[$sThPrefix.'_overrun'] = $sPrefix.$sThPrefix.'_overrun';
  2927. }
  2928. return $aColumns;
  2929. }
  2930. public static function DateToSeconds($sDate)
  2931. {
  2932. if (is_null($sDate))
  2933. {
  2934. return null;
  2935. }
  2936. $oDateTime = new DateTime($sDate);
  2937. $iSeconds = $oDateTime->format('U');
  2938. return $iSeconds;
  2939. }
  2940. public static function SecondsToDate($iSeconds)
  2941. {
  2942. if (is_null($iSeconds))
  2943. {
  2944. return null;
  2945. }
  2946. return date("Y-m-d H:i:s", $iSeconds);
  2947. }
  2948. public function FromSQLToValue($aCols, $sPrefix = '')
  2949. {
  2950. $aExpectedCols = array($sPrefix, $sPrefix.'_started', $sPrefix.'_laststart', $sPrefix.'_stopped');
  2951. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  2952. {
  2953. $sThPrefix = '_'.$iThreshold;
  2954. $aExpectedCols[] = $sPrefix.$sThPrefix.'_deadline';
  2955. $aExpectedCols[] = $sPrefix.$sThPrefix.'_passed';
  2956. $aExpectedCols[] = $sPrefix.$sThPrefix.'_overrun';
  2957. }
  2958. foreach ($aExpectedCols as $sExpectedCol)
  2959. {
  2960. if (!array_key_exists($sExpectedCol, $aCols))
  2961. {
  2962. $sAvailable = implode(', ', array_keys($aCols));
  2963. throw new MissingColumnException("Missing column '$sExpectedCol' from {$sAvailable}");
  2964. }
  2965. }
  2966. $value = new ormStopWatch(
  2967. $aCols[$sPrefix],
  2968. self::DateToSeconds($aCols[$sPrefix.'_started']),
  2969. self::DateToSeconds($aCols[$sPrefix.'_laststart']),
  2970. self::DateToSeconds($aCols[$sPrefix.'_stopped'])
  2971. );
  2972. $aThresholds = array();
  2973. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  2974. {
  2975. $sThPrefix = '_'.$iThreshold;
  2976. $value->DefineThreshold(
  2977. $iThreshold,
  2978. self::DateToSeconds($aCols[$sPrefix.$sThPrefix.'_deadline']),
  2979. (bool)($aCols[$sPrefix.$sThPrefix.'_passed'] == 1),
  2980. $aCols[$sPrefix.$sThPrefix.'_overrun']
  2981. );
  2982. }
  2983. return $value;
  2984. }
  2985. public function GetSQLValues($value)
  2986. {
  2987. if ($value instanceOf ormStopWatch)
  2988. {
  2989. $aValues = array();
  2990. $aValues[$this->GetCode().'_timespent'] = $value->GetTimeSpent();
  2991. $aValues[$this->GetCode().'_started'] = self::SecondsToDate($value->GetStartDate());
  2992. $aValues[$this->GetCode().'_laststart'] = self::SecondsToDate($value->GetLastStartDate());
  2993. $aValues[$this->GetCode().'_stopped'] = self::SecondsToDate($value->GetStopDate());
  2994. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  2995. {
  2996. $sPrefix = $this->GetCode().'_'.$iThreshold;
  2997. $aValues[$sPrefix.'_deadline'] = self::SecondsToDate($value->GetThresholdDate($iThreshold));
  2998. $aValues[$sPrefix.'_passed'] = $value->IsThresholdPassed($iThreshold) ? '1' : '0';
  2999. $aValues[$sPrefix.'_overrun'] = $value->GetOverrun($iThreshold);
  3000. }
  3001. }
  3002. else
  3003. {
  3004. $aValues = array();
  3005. $aValues[$this->GetCode().'_timespent'] = '';
  3006. $aValues[$this->GetCode().'_started'] = '';
  3007. $aValues[$this->GetCode().'_laststart'] = '';
  3008. $aValues[$this->GetCode().'_stopped'] = '';
  3009. }
  3010. return $aValues;
  3011. }
  3012. public function GetSQLColumns()
  3013. {
  3014. $aColumns = array();
  3015. $aColumns[$this->GetCode().'_timespent'] = 'INT(11) UNSIGNED DEFAULT 0';
  3016. $aColumns[$this->GetCode().'_started'] = 'DATETIME NULL';
  3017. $aColumns[$this->GetCode().'_laststart'] = 'DATETIME NULL';
  3018. $aColumns[$this->GetCode().'_stopped'] = 'DATETIME NULL';
  3019. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3020. {
  3021. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3022. $aColumns[$sPrefix.'_deadline'] = 'DATETIME NULL';
  3023. $aColumns[$sPrefix.'_passed'] = 'TINYINT(1) NULL';
  3024. $aColumns[$sPrefix.'_overrun'] = 'INT(11) UNSIGNED NULL';
  3025. }
  3026. return $aColumns;
  3027. }
  3028. public function GetFilterDefinitions()
  3029. {
  3030. //return array();
  3031. // still not working... see later...
  3032. $aRes = array(
  3033. $this->GetCode() => new FilterFromAttribute($this),
  3034. $this->GetCode().'_started' => new FilterFromAttribute($this, '_started'),
  3035. $this->GetCode().'_laststart' => new FilterFromAttribute($this, '_laststart'),
  3036. $this->GetCode().'_stopped' => new FilterFromAttribute($this, '_stopped')
  3037. );
  3038. foreach ($this->ListThresholds() as $iThreshold => $aFoo)
  3039. {
  3040. $sPrefix = $this->GetCode().'_'.$iThreshold;
  3041. $aRes[$sPrefix.'_deadline'] = new FilterFromAttribute($this, '_deadline');
  3042. $aRes[$sPrefix.'_passed'] = new FilterFromAttribute($this, '_passed');
  3043. $aRes[$sPrefix.'_overrun'] = new FilterFromAttribute($this, '_overrun');
  3044. }
  3045. return $aRes;
  3046. }
  3047. public function GetBasicFilterOperators()
  3048. {
  3049. return array();
  3050. }
  3051. public function GetBasicFilterLooseOperator()
  3052. {
  3053. return '=';
  3054. }
  3055. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3056. {
  3057. return 'true';
  3058. }
  3059. public function GetAsHTML($value, $oHostObject = null)
  3060. {
  3061. if (is_object($value))
  3062. {
  3063. return $value->GetAsHTML($this, $oHostObject);
  3064. }
  3065. }
  3066. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3067. {
  3068. return $value->GetTimeSpent();
  3069. }
  3070. public function GetAsXML($value, $oHostObject = null)
  3071. {
  3072. return $value->GetTimeSpent();
  3073. }
  3074. public function ListThresholds()
  3075. {
  3076. return $this->Get('thresholds');
  3077. }
  3078. }
  3079. /**
  3080. * One way encrypted (hashed) password
  3081. */
  3082. class AttributeOneWayPassword extends AttributeDefinition
  3083. {
  3084. static public function ListExpectedParams()
  3085. {
  3086. return array_merge(parent::ListExpectedParams(), array("depends_on"));
  3087. }
  3088. public function GetEditClass() {return "One Way Password";}
  3089. public function IsDirectField() {return true;}
  3090. public function IsScalar() {return true;}
  3091. public function IsWritable() {return true;}
  3092. public function GetDefaultValue() {return "";}
  3093. public function IsNullAllowed() {return $this->GetOptional("is_null_allowed", false);}
  3094. // Facilitate things: allow the user to Set the value from a string or from an ormPassword (already encrypted)
  3095. public function MakeRealValue($proposedValue, $oHostObj)
  3096. {
  3097. $oPassword = $proposedValue;
  3098. if (!is_object($oPassword))
  3099. {
  3100. $oPassword = new ormPassword('', '');
  3101. $oPassword->SetPassword($proposedValue);
  3102. }
  3103. return $oPassword;
  3104. }
  3105. public function GetSQLExpressions($sPrefix = '')
  3106. {
  3107. if ($sPrefix == '')
  3108. {
  3109. $sPrefix = $this->GetCode();
  3110. }
  3111. $aColumns = array();
  3112. // Note: to optimize things, the existence of the attribute is determined by the existence of one column with an empty suffix
  3113. $aColumns[''] = $sPrefix.'_hash';
  3114. $aColumns['_salt'] = $sPrefix.'_salt';
  3115. return $aColumns;
  3116. }
  3117. public function FromSQLToValue($aCols, $sPrefix = '')
  3118. {
  3119. if (!isset($aCols[$sPrefix]))
  3120. {
  3121. $sAvailable = implode(', ', array_keys($aCols));
  3122. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3123. }
  3124. $hashed = $aCols[$sPrefix];
  3125. if (!isset($aCols[$sPrefix.'_salt']))
  3126. {
  3127. $sAvailable = implode(', ', array_keys($aCols));
  3128. throw new MissingColumnException("Missing column '".$sPrefix."_salt' from {$sAvailable}");
  3129. }
  3130. $sSalt = $aCols[$sPrefix.'_salt'];
  3131. $value = new ormPassword($hashed, $sSalt);
  3132. return $value;
  3133. }
  3134. public function GetSQLValues($value)
  3135. {
  3136. // #@# Optimization: do not load blobs anytime
  3137. // As per mySQL doc, selecting blob columns will prevent mySQL from
  3138. // using memory in case a temporary table has to be created
  3139. // (temporary tables created on disk)
  3140. // We will have to remove the blobs from the list of attributes when doing the select
  3141. // then the use of Get() should finalize the load
  3142. if ($value instanceOf ormPassword)
  3143. {
  3144. $aValues = array();
  3145. $aValues[$this->GetCode().'_hash'] = $value->GetHash();
  3146. $aValues[$this->GetCode().'_salt'] = $value->GetSalt();
  3147. }
  3148. else
  3149. {
  3150. $aValues = array();
  3151. $aValues[$this->GetCode().'_hash'] = '';
  3152. $aValues[$this->GetCode().'_salt'] = '';
  3153. }
  3154. return $aValues;
  3155. }
  3156. public function GetSQLColumns()
  3157. {
  3158. $aColumns = array();
  3159. $aColumns[$this->GetCode().'_hash'] = 'TINYBLOB';
  3160. $aColumns[$this->GetCode().'_salt'] = 'TINYBLOB';
  3161. return $aColumns;
  3162. }
  3163. public function GetImportColumns()
  3164. {
  3165. $aColumns = array();
  3166. $aColumns[$this->GetCode()] = 'TINYTEXT';
  3167. return $aColumns;
  3168. }
  3169. public function FromImportToValue($aCols, $sPrefix = '')
  3170. {
  3171. if (!isset($aCols[$sPrefix]))
  3172. {
  3173. $sAvailable = implode(', ', array_keys($aCols));
  3174. throw new MissingColumnException("Missing column '$sPrefix' from {$sAvailable}");
  3175. }
  3176. $sClearPwd = $aCols[$sPrefix];
  3177. $oPassword = new ormPassword('', '');
  3178. $oPassword->SetPassword($sClearPwd);
  3179. return $oPassword;
  3180. }
  3181. public function GetFilterDefinitions()
  3182. {
  3183. return array();
  3184. // still not working... see later...
  3185. }
  3186. public function GetBasicFilterOperators()
  3187. {
  3188. return array();
  3189. }
  3190. public function GetBasicFilterLooseOperator()
  3191. {
  3192. return '=';
  3193. }
  3194. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3195. {
  3196. return 'true';
  3197. }
  3198. public function GetAsHTML($value, $oHostObject = null)
  3199. {
  3200. if (is_object($value))
  3201. {
  3202. return $value->GetAsHTML();
  3203. }
  3204. }
  3205. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3206. {
  3207. return ''; // Not exportable in CSV
  3208. }
  3209. public function GetAsXML($value, $oHostObject = null)
  3210. {
  3211. return ''; // Not exportable in XML
  3212. }
  3213. }
  3214. // Indexed array having two dimensions
  3215. class AttributeTable extends AttributeDBField
  3216. {
  3217. public function GetEditClass() {return "Table";}
  3218. protected function GetSQLCol() {return "LONGTEXT";}
  3219. public function GetMaxSize()
  3220. {
  3221. return null;
  3222. }
  3223. public function GetNullValue()
  3224. {
  3225. return array();
  3226. }
  3227. public function IsNull($proposedValue)
  3228. {
  3229. return (count($proposedValue) == 0);
  3230. }
  3231. // Facilitate things: allow the user to Set the value from a string
  3232. public function MakeRealValue($proposedValue, $oHostObj)
  3233. {
  3234. if (!is_array($proposedValue))
  3235. {
  3236. return array(0 => array(0 => $proposedValue));
  3237. }
  3238. return $proposedValue;
  3239. }
  3240. public function FromSQLToValue($aCols, $sPrefix = '')
  3241. {
  3242. try
  3243. {
  3244. $value = @unserialize($aCols[$sPrefix.'']);
  3245. if ($value === false)
  3246. {
  3247. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  3248. }
  3249. }
  3250. catch(Exception $e)
  3251. {
  3252. $value = $this->MakeRealValue($aCols[$sPrefix.''], null);
  3253. }
  3254. return $value;
  3255. }
  3256. public function GetSQLValues($value)
  3257. {
  3258. $aValues = array();
  3259. $aValues[$this->Get("sql")] = serialize($value);
  3260. return $aValues;
  3261. }
  3262. public function GetAsHTML($value, $oHostObject = null)
  3263. {
  3264. if (!is_array($value))
  3265. {
  3266. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3267. }
  3268. if (count($value) == 0)
  3269. {
  3270. return "";
  3271. }
  3272. $sRes = "<TABLE class=\"listResults\">";
  3273. $sRes .= "<TBODY>";
  3274. foreach($value as $iRow => $aRawData)
  3275. {
  3276. $sRes .= "<TR>";
  3277. foreach ($aRawData as $iCol => $cell)
  3278. {
  3279. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$cell));
  3280. $sRes .= "<TD>$sCell</TD>";
  3281. }
  3282. $sRes .= "</TR>";
  3283. }
  3284. $sRes .= "</TBODY>";
  3285. $sRes .= "</TABLE>";
  3286. return $sRes;
  3287. }
  3288. public function GetAsCSV($sValue, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3289. {
  3290. // Not implemented
  3291. return '';
  3292. }
  3293. public function GetAsXML($value, $oHostObject = null)
  3294. {
  3295. if (count($value) == 0)
  3296. {
  3297. return "";
  3298. }
  3299. $sRes = "";
  3300. foreach($value as $iRow => $aRawData)
  3301. {
  3302. $sRes .= "<row>";
  3303. foreach ($aRawData as $iCol => $cell)
  3304. {
  3305. $sCell = Str::pure2xml((string)$cell);
  3306. $sRes .= "<cell icol=\"$iCol\">$sCell</cell>";
  3307. }
  3308. $sRes .= "</row>";
  3309. }
  3310. return $sRes;
  3311. }
  3312. }
  3313. // The PHP value is a hash array, it is stored as a TEXT column
  3314. class AttributePropertySet extends AttributeTable
  3315. {
  3316. public function GetEditClass() {return "PropertySet";}
  3317. // Facilitate things: allow the user to Set the value from a string
  3318. public function MakeRealValue($proposedValue, $oHostObj)
  3319. {
  3320. if (!is_array($proposedValue))
  3321. {
  3322. return array('?' => (string)$proposedValue);
  3323. }
  3324. return $proposedValue;
  3325. }
  3326. public function GetAsHTML($value, $oHostObject = null)
  3327. {
  3328. if (!is_array($value))
  3329. {
  3330. throw new CoreException('Expecting an array', array('found' => get_class($value)));
  3331. }
  3332. if (count($value) == 0)
  3333. {
  3334. return "";
  3335. }
  3336. $sRes = "<TABLE class=\"listResults\">";
  3337. $sRes .= "<TBODY>";
  3338. foreach($value as $sProperty => $sValue)
  3339. {
  3340. if ($sProperty == 'auth_pwd')
  3341. {
  3342. $sValue = '*****';
  3343. }
  3344. $sRes .= "<TR>";
  3345. $sCell = str_replace("\n", "<br>\n", Str::pure2html((string)$sValue));
  3346. $sRes .= "<TD class=\"label\">$sProperty</TD><TD>$sCell</TD>";
  3347. $sRes .= "</TR>";
  3348. }
  3349. $sRes .= "</TBODY>";
  3350. $sRes .= "</TABLE>";
  3351. return $sRes;
  3352. }
  3353. public function GetAsCSV($value, $sSeparator = ',', $sTextQualifier = '"', $oHostObject = null)
  3354. {
  3355. if (count($value) == 0)
  3356. {
  3357. return "";
  3358. }
  3359. $aRes = array();
  3360. foreach($value as $sProperty => $sValue)
  3361. {
  3362. if ($sProperty == 'auth_pwd')
  3363. {
  3364. $sValue = '*****';
  3365. }
  3366. $sFrom = array(',', '=');
  3367. $sTo = array('\,', '\=');
  3368. $aRes[] = $sProperty.'='.str_replace($sFrom, $sTo, (string)$sValue);
  3369. }
  3370. $sRaw = implode(',', $aRes);
  3371. $sFrom = array("\r\n", $sTextQualifier);
  3372. $sTo = array("\n", $sTextQualifier.$sTextQualifier);
  3373. $sEscaped = str_replace($sFrom, $sTo, $sRaw);
  3374. return $sTextQualifier.$sEscaped.$sTextQualifier;
  3375. }
  3376. public function GetAsXML($value, $oHostObject = null)
  3377. {
  3378. if (count($value) == 0)
  3379. {
  3380. return "";
  3381. }
  3382. $sRes = "";
  3383. foreach($value as $sProperty => $sValue)
  3384. {
  3385. if ($sProperty == 'auth_pwd')
  3386. {
  3387. $sValue = '*****';
  3388. }
  3389. $sRes .= "<property id=\"$sProperty\">";
  3390. $sRes .= Str::pure2xml((string)$sValue);
  3391. $sRes .= "</property>";
  3392. }
  3393. return $sRes;
  3394. }
  3395. }
  3396. /**
  3397. * The attribute dedicated to the friendly name automatic attribute (not written)
  3398. *
  3399. * @package iTopORM
  3400. */
  3401. class AttributeComputedFieldVoid extends AttributeDefinition
  3402. {
  3403. static public function ListExpectedParams()
  3404. {
  3405. return array_merge(parent::ListExpectedParams(), array());
  3406. }
  3407. public function GetEditClass() {return "";}
  3408. public function GetValuesDef() {return null;}
  3409. public function GetPrerequisiteAttributes() {return $this->Get("depends_on");}
  3410. public function IsDirectField() {return true;}
  3411. public function IsScalar() {return true;}
  3412. public function IsWritable() {return false;}
  3413. public function GetSQLExpr() {return null;}
  3414. public function GetDefaultValue() {return $this->MakeRealValue("", null);}
  3415. public function IsNullAllowed() {return false;}
  3416. //
  3417. // protected function ScalarToSQL($value) {return $value;} // format value as a valuable SQL literal (quoted outside)
  3418. public function GetSQLExpressions($sPrefix = '')
  3419. {
  3420. if ($sPrefix == '')
  3421. {
  3422. $sPrefix = $this->GetCode();
  3423. }
  3424. return array('' => $sPrefix);
  3425. }
  3426. public function FromSQLToValue($aCols, $sPrefix = '')
  3427. {
  3428. return null;
  3429. }
  3430. public function GetSQLValues($value)
  3431. {
  3432. return array();
  3433. }
  3434. public function GetSQLColumns()
  3435. {
  3436. return array();
  3437. }
  3438. public function GetFilterDefinitions()
  3439. {
  3440. return array($this->GetCode() => new FilterFromAttribute($this));
  3441. }
  3442. public function GetBasicFilterOperators()
  3443. {
  3444. return array();
  3445. }
  3446. public function GetBasicFilterLooseOperator()
  3447. {
  3448. return "=";
  3449. }
  3450. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3451. {
  3452. $sQValue = CMDBSource::Quote($value);
  3453. switch ($sOpCode)
  3454. {
  3455. case '!=':
  3456. return $this->GetSQLExpr()." != $sQValue";
  3457. break;
  3458. case '=':
  3459. default:
  3460. return $this->GetSQLExpr()." = $sQValue";
  3461. }
  3462. }
  3463. }
  3464. /**
  3465. * The attribute dedicated to the friendly name automatic attribute (not written)
  3466. *
  3467. * @package iTopORM
  3468. */
  3469. class AttributeFriendlyName extends AttributeComputedFieldVoid
  3470. {
  3471. public function __construct($sCode, $sExtKeyAttCode)
  3472. {
  3473. $this->m_sCode = $sCode;
  3474. $aParams = array();
  3475. // $aParams["is_null_allowed"] = false,
  3476. $aParams["default_value"] = '';
  3477. $aParams["extkey_attcode"] = $sExtKeyAttCode;
  3478. parent::__construct($sCode, $aParams);
  3479. $this->m_sValue = $this->Get("default_value");
  3480. }
  3481. public function GetKeyAttCode() {return $this->Get("extkey_attcode");}
  3482. public function GetExtAttCode() {return 'friendlyname';}
  3483. public function GetLabel($sDefault = null)
  3484. {
  3485. $sLabel = parent::GetLabel('');
  3486. if (strlen($sLabel) == 0)
  3487. {
  3488. $sKeyAttCode = $this->Get("extkey_attcode");
  3489. if ($sKeyAttCode == 'id')
  3490. {
  3491. return Dict::S('Core:FriendlyName-Label');
  3492. }
  3493. else
  3494. {
  3495. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3496. $sLabel = $oExtKeyAttDef->GetLabel($this->m_sCode);
  3497. }
  3498. }
  3499. return $sLabel;
  3500. }
  3501. public function GetDescription($sDefault = null)
  3502. {
  3503. $sLabel = parent::GetDescription('');
  3504. if (strlen($sLabel) == 0)
  3505. {
  3506. $sKeyAttCode = $this->Get("extkey_attcode");
  3507. if ($sKeyAttCode == 'id')
  3508. {
  3509. return Dict::S('Core:FriendlyName-Description');
  3510. }
  3511. else
  3512. {
  3513. $oExtKeyAttDef = MetaModel::GetAttributeDef($this->GetHostClass(), $sKeyAttCode);
  3514. $sLabel = $oExtKeyAttDef->GetDescription('');
  3515. }
  3516. }
  3517. return $sLabel;
  3518. }
  3519. // n/a, the friendly name is made of a complex expression (see GetNameSpec)
  3520. protected function GetSQLCol() {return "";}
  3521. public function FromSQLToValue($aCols, $sPrefix = '')
  3522. {
  3523. $sValue = $aCols[$sPrefix];
  3524. return $sValue;
  3525. }
  3526. /**
  3527. * Encrypt the value before storing it in the database
  3528. */
  3529. public function GetSQLValues($value)
  3530. {
  3531. return array();
  3532. }
  3533. public function IsWritable()
  3534. {
  3535. return false;
  3536. }
  3537. public function IsDirectField()
  3538. {
  3539. return false;
  3540. }
  3541. public function SetFixedValue($sValue)
  3542. {
  3543. $this->m_sValue = $sValue;
  3544. }
  3545. public function GetDefaultValue()
  3546. {
  3547. return $this->m_sValue;
  3548. }
  3549. public function GetAsHTML($sValue, $oHostObject = null)
  3550. {
  3551. return Str::pure2html((string)$sValue);
  3552. }
  3553. public function GetBasicFilterLooseOperator()
  3554. {
  3555. return "Contains";
  3556. }
  3557. public function GetBasicFilterSQLExpr($sOpCode, $value)
  3558. {
  3559. $sQValue = CMDBSource::Quote($value);
  3560. switch ($sOpCode)
  3561. {
  3562. case '=':
  3563. case '!=':
  3564. return $this->GetSQLExpr()." $sOpCode $sQValue";
  3565. case 'Contains':
  3566. return $this->GetSQLExpr()." LIKE ".CMDBSource::Quote("%$value%");
  3567. case 'NotLike':
  3568. return $this->GetSQLExpr()." NOT LIKE $sQValue";
  3569. case 'Like':
  3570. default:
  3571. return $this->GetSQLExpr()." LIKE $sQValue";
  3572. }
  3573. }
  3574. }
  3575. ?>