attributedef.class.inc.php 118 KB

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