form.inc 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799
  1. <?php
  2. /**
  3. * @file
  4. * Functions for form and batch generation and processing.
  5. */
  6. /**
  7. * @defgroup forms Form builder functions
  8. * @{
  9. * Functions that build an abstract representation of a HTML form.
  10. *
  11. * All modules should declare their form builder functions to be in this
  12. * group and each builder function should reference its validate and submit
  13. * functions using \@see. Conversely, validate and submit functions should
  14. * reference the form builder function using \@see. For examples, of this see
  15. * system_modules_uninstall() or user_pass(), the latter of which has the
  16. * following in its doxygen documentation:
  17. * - \@ingroup forms
  18. * - \@see user_pass_validate()
  19. * - \@see user_pass_submit()
  20. *
  21. * @}
  22. */
  23. /**
  24. * @defgroup form_api Form generation
  25. * @{
  26. * Functions to enable the processing and display of HTML forms.
  27. *
  28. * Drupal uses these functions to achieve consistency in its form processing and
  29. * presentation, while simplifying code and reducing the amount of HTML that
  30. * must be explicitly generated by modules.
  31. *
  32. * The primary function used with forms is drupal_get_form(), which is
  33. * used for forms presented interactively to a user. Forms can also be built and
  34. * submitted programmatically without any user input using the
  35. * drupal_form_submit() function.
  36. *
  37. * drupal_get_form() handles retrieving, processing, and displaying a rendered
  38. * HTML form for modules automatically.
  39. *
  40. * Here is an example of how to use drupal_get_form() and a form builder
  41. * function:
  42. * @code
  43. * $form = drupal_get_form('my_module_example_form');
  44. * ...
  45. * function my_module_example_form($form, &$form_state) {
  46. * $form['submit'] = array(
  47. * '#type' => 'submit',
  48. * '#value' => t('Submit'),
  49. * );
  50. * return $form;
  51. * }
  52. * function my_module_example_form_validate($form, &$form_state) {
  53. * // Validation logic.
  54. * }
  55. * function my_module_example_form_submit($form, &$form_state) {
  56. * // Submission logic.
  57. * }
  58. * @endcode
  59. *
  60. * Or with any number of additional arguments:
  61. * @code
  62. * $extra = "extra";
  63. * $form = drupal_get_form('my_module_example_form', $extra);
  64. * ...
  65. * function my_module_example_form($form, &$form_state, $extra) {
  66. * $form['submit'] = array(
  67. * '#type' => 'submit',
  68. * '#value' => $extra,
  69. * );
  70. * return $form;
  71. * }
  72. * @endcode
  73. *
  74. * The $form argument to form-related functions is a structured array containing
  75. * the elements and properties of the form. For information on the array
  76. * components and format, and more detailed explanations of the Form API
  77. * workflow, see the
  78. * @link forms_api_reference.html Form API reference @endlink
  79. * and the
  80. * @link http://drupal.org/node/37775 Form API documentation section. @endlink
  81. * In addition, there is a set of Form API tutorials in
  82. * @link form_example_tutorial.inc the Form Example Tutorial @endlink which
  83. * provide basics all the way up through multistep forms.
  84. *
  85. * In the form builder, validation, submission, and other form functions,
  86. * $form_state is the primary influence on the processing of the form and is
  87. * passed by reference to most functions, so they use it to communicate with
  88. * the form system and each other.
  89. *
  90. * See drupal_build_form() for documentation of $form_state keys.
  91. */
  92. /**
  93. * Returns a renderable form array for a given form ID.
  94. *
  95. * This function should be used instead of drupal_build_form() when $form_state
  96. * is not needed (i.e., when initially rendering the form) and is often
  97. * used as a menu callback.
  98. *
  99. * @param $form_id
  100. * The unique string identifying the desired form. If a function with that
  101. * name exists, it is called to build the form array. Modules that need to
  102. * generate the same form (or very similar forms) using different $form_ids
  103. * can implement hook_forms(), which maps different $form_id values to the
  104. * proper form constructor function. Examples may be found in node_forms(),
  105. * and search_forms().
  106. * @param ...
  107. * Any additional arguments are passed on to the functions called by
  108. * drupal_get_form(), including the unique form constructor function. For
  109. * example, the node_edit form requires that a node object is passed in here
  110. * when it is called. These are available to implementations of
  111. * hook_form_alter() and hook_form_FORM_ID_alter() as the array
  112. * $form_state['build_info']['args'].
  113. *
  114. * @return
  115. * The form array.
  116. *
  117. * @see drupal_build_form()
  118. */
  119. function drupal_get_form($form_id) {
  120. $form_state = array();
  121. $args = func_get_args();
  122. // Remove $form_id from the arguments.
  123. array_shift($args);
  124. $form_state['build_info']['args'] = $args;
  125. return drupal_build_form($form_id, $form_state);
  126. }
  127. /**
  128. * Builds and process a form based on a form id.
  129. *
  130. * The form may also be retrieved from the cache if the form was built in a
  131. * previous page-load. The form is then passed on for processing, validation
  132. * and submission if there is proper input.
  133. *
  134. * @param $form_id
  135. * The unique string identifying the desired form. If a function with that
  136. * name exists, it is called to build the form array. Modules that need to
  137. * generate the same form (or very similar forms) using different $form_ids
  138. * can implement hook_forms(), which maps different $form_id values to the
  139. * proper form constructor function. Examples may be found in node_forms(),
  140. * and search_forms().
  141. * @param $form_state
  142. * An array which stores information about the form. This is passed as a
  143. * reference so that the caller can use it to examine what in the form changed
  144. * when the form submission process is complete. Furthermore, it may be used
  145. * to store information related to the processed data in the form, which will
  146. * persist across page requests when the 'cache' or 'rebuild' flag is set.
  147. * The following parameters may be set in $form_state to affect how the form
  148. * is rendered:
  149. * - build_info: Internal. An associative array of information stored by Form
  150. * API that is necessary to build and rebuild the form from cache when the
  151. * original context may no longer be available:
  152. * - args: A list of arguments to pass to the form constructor.
  153. * - files: An optional array defining include files that need to be loaded
  154. * for building the form. Each array entry may be the path to a file or
  155. * another array containing values for the parameters 'type', 'module' and
  156. * 'name' as needed by module_load_include(). The files listed here are
  157. * automatically loaded by form_get_cache(). By default the current menu
  158. * router item's 'file' definition is added, if any. Use
  159. * form_load_include() to add include files from a form constructor.
  160. * - form_id: Identification of the primary form being constructed and
  161. * processed.
  162. * - base_form_id: Identification for a base form, as declared in a
  163. * hook_forms() implementation.
  164. * - immutable: If this flag is set to TRUE, a new form build id is
  165. * generated when the form is loaded from the cache. If it is subsequently
  166. * saved to the cache again, it will have another cache id and therefore
  167. * the original form and form-state will remain unaltered. This is
  168. * important when page caching is enabled in order to prevent form state
  169. * from leaking between anonymous users.
  170. * - rebuild_info: Internal. Similar to 'build_info', but pertaining to
  171. * drupal_rebuild_form().
  172. * - rebuild: Normally, after the entire form processing is completed and
  173. * submit handlers have run, a form is considered to be done and
  174. * drupal_redirect_form() will redirect the user to a new page using a GET
  175. * request (so a browser refresh does not re-submit the form). However, if
  176. * 'rebuild' has been set to TRUE, then a new copy of the form is
  177. * immediately built and sent to the browser, instead of a redirect. This is
  178. * used for multi-step forms, such as wizards and confirmation forms.
  179. * Normally, $form_state['rebuild'] is set by a submit handler, since it is
  180. * usually logic within a submit handler that determines whether a form is
  181. * done or requires another step. However, a validation handler may already
  182. * set $form_state['rebuild'] to cause the form processing to bypass submit
  183. * handlers and rebuild the form instead, even if there are no validation
  184. * errors.
  185. * - redirect: Used to redirect the form on submission. It may either be a
  186. * string containing the destination URL, or an array of arguments
  187. * compatible with drupal_goto(). See drupal_redirect_form() for complete
  188. * information.
  189. * - no_redirect: If set to TRUE the form will NOT perform a drupal_goto(),
  190. * even if 'redirect' is set.
  191. * - method: The HTTP form method to use for finding the input for this form.
  192. * May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method
  193. * forms do not use form ids so are always considered to be submitted, which
  194. * can have unexpected effects. The 'get' method should only be used on
  195. * forms that do not change data, as that is exclusively the domain of
  196. * 'post.'
  197. * - cache: If set to TRUE the original, unprocessed form structure will be
  198. * cached, which allows the entire form to be rebuilt from cache. A typical
  199. * form workflow involves two page requests; first, a form is built and
  200. * rendered for the user to fill in. Then, the user fills the form in and
  201. * submits it, triggering a second page request in which the form must be
  202. * built and processed. By default, $form and $form_state are built from
  203. * scratch during each of these page requests. Often, it is necessary or
  204. * desired to persist the $form and $form_state variables from the initial
  205. * page request to the one that processes the submission. 'cache' can be set
  206. * to TRUE to do this. A prominent example is an Ajax-enabled form, in which
  207. * ajax_process_form() enables form caching for all forms that include an
  208. * element with the #ajax property. (The Ajax handler has no way to build
  209. * the form itself, so must rely on the cached version.) Note that the
  210. * persistence of $form and $form_state happens automatically for
  211. * (multi-step) forms having the 'rebuild' flag set, regardless of the value
  212. * for 'cache'.
  213. * - no_cache: If set to TRUE the form will NOT be cached, even if 'cache' is
  214. * set.
  215. * - values: An associative array of values submitted to the form. The
  216. * validation functions and submit functions use this array for nearly all
  217. * their decision making. (Note that #tree determines whether the values are
  218. * a flat array or an array whose structure parallels the $form array. See
  219. * @link forms_api_reference.html Form API reference @endlink for more
  220. * information.) These are raw and unvalidated, so should not be used
  221. * without a thorough understanding of security implications. In almost all
  222. * cases, code should use the data in the 'values' array exclusively. The
  223. * most common use of this key is for multi-step forms that need to clear
  224. * some of the user input when setting 'rebuild'. The values correspond to
  225. * $_POST or $_GET, depending on the 'method' chosen.
  226. * - always_process: If TRUE and the method is GET, a form_id is not
  227. * necessary. This should only be used on RESTful GET forms that do NOT
  228. * write data, as this could lead to security issues. It is useful so that
  229. * searches do not need to have a form_id in their query arguments to
  230. * trigger the search.
  231. * - must_validate: Ordinarily, a form is only validated once, but there are
  232. * times when a form is resubmitted internally and should be validated
  233. * again. Setting this to TRUE will force that to happen. This is most
  234. * likely to occur during Ajax operations.
  235. * - programmed: If TRUE, the form was submitted programmatically, usually
  236. * invoked via drupal_form_submit(). Defaults to FALSE.
  237. * - programmed_bypass_access_check: If TRUE, programmatic form submissions
  238. * are processed without taking #access into account. Set this to FALSE
  239. * when submitting a form programmatically with values that may have been
  240. * input by the user executing the current request; this will cause #access
  241. * to be respected as it would on a normal form submission. Defaults to
  242. * TRUE.
  243. * - process_input: Boolean flag. TRUE signifies correct form submission.
  244. * This is always TRUE for programmed forms coming from drupal_form_submit()
  245. * (see 'programmed' key), or if the form_id coming from the $_POST data is
  246. * set and matches the current form_id.
  247. * - submitted: If TRUE, the form has been submitted. Defaults to FALSE.
  248. * - executed: If TRUE, the form was submitted and has been processed and
  249. * executed. Defaults to FALSE.
  250. * - triggering_element: (read-only) The form element that triggered
  251. * submission. This is the same as the deprecated
  252. * $form_state['clicked_button']. It is the element that caused submission,
  253. * which may or may not be a button (in the case of Ajax forms). This key is
  254. * often used to distinguish between various buttons in a submit handler,
  255. * and is also used in Ajax handlers.
  256. * - clicked_button: Deprecated. Use triggering_element instead.
  257. * - has_file_element: Internal. If TRUE, there is a file element and Form API
  258. * will set the appropriate 'enctype' HTML attribute on the form.
  259. * - groups: Internal. An array containing references to fieldsets to render
  260. * them within vertical tabs.
  261. * - storage: $form_state['storage'] is not a special key, and no specific
  262. * support is provided for it in the Form API. By tradition it was
  263. * the location where application-specific data was stored for communication
  264. * between the submit, validation, and form builder functions, especially
  265. * in a multi-step-style form. Form implementations may use any key(s)
  266. * within $form_state (other than the keys listed here and other reserved
  267. * ones used by Form API internals) for this kind of storage. The
  268. * recommended way to ensure that the chosen key doesn't conflict with ones
  269. * used by the Form API or other modules is to use the module name as the
  270. * key name or a prefix for the key name. For example, the Node module uses
  271. * $form_state['node'] in node editing forms to store information about the
  272. * node being edited, and this information stays available across successive
  273. * clicks of the "Preview" button as well as when the "Save" button is
  274. * finally clicked.
  275. * - buttons: A list containing copies of all submit and button elements in
  276. * the form.
  277. * - complete form: A reference to the $form variable containing the complete
  278. * form structure. #process, #after_build, #element_validate, and other
  279. * handlers being invoked on a form element may use this reference to access
  280. * other information in the form the element is contained in.
  281. * - temporary: An array holding temporary data accessible during the current
  282. * page request only. All $form_state properties that are not reserved keys
  283. * (see form_state_keys_no_cache()) persist throughout a multistep form
  284. * sequence. Form API provides this key for modules to communicate
  285. * information across form-related functions during a single page request.
  286. * It may be used to temporarily save data that does not need to or should
  287. * not be cached during the whole form workflow; e.g., data that needs to be
  288. * accessed during the current form build process only. There is no use-case
  289. * for this functionality in Drupal core.
  290. * - wrapper_callback: Modules that wish to pre-populate certain forms with
  291. * common elements, such as back/next/save buttons in multi-step form
  292. * wizards, may define a form builder function name that returns a form
  293. * structure, which is passed on to the actual form builder function.
  294. * Such implementations may either define the 'wrapper_callback' via
  295. * hook_forms() or have to invoke drupal_build_form() (instead of
  296. * drupal_get_form()) on their own in a custom menu callback to prepare
  297. * $form_state accordingly.
  298. * Information on how certain $form_state properties control redirection
  299. * behavior after form submission may be found in drupal_redirect_form().
  300. *
  301. * @return
  302. * The rendered form. This function may also perform a redirect and hence may
  303. * not return at all, depending upon the $form_state flags that were set.
  304. *
  305. * @see drupal_redirect_form()
  306. */
  307. function drupal_build_form($form_id, &$form_state) {
  308. // Ensure some defaults; if already set they will not be overridden.
  309. $form_state += form_state_defaults();
  310. if (!isset($form_state['input'])) {
  311. $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
  312. }
  313. if (isset($_SESSION['batch_form_state'])) {
  314. // We've been redirected here after a batch processing. The form has
  315. // already been processed, but needs to be rebuilt. See _batch_finished().
  316. $form_state = $_SESSION['batch_form_state'];
  317. unset($_SESSION['batch_form_state']);
  318. return drupal_rebuild_form($form_id, $form_state);
  319. }
  320. // If the incoming input contains a form_build_id, we'll check the cache for a
  321. // copy of the form in question. If it's there, we don't have to rebuild the
  322. // form to proceed. In addition, if there is stored form_state data from a
  323. // previous step, we'll retrieve it so it can be passed on to the form
  324. // processing code.
  325. $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  326. if ($check_cache) {
  327. $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  328. }
  329. // If the previous bit of code didn't result in a populated $form object, we
  330. // are hitting the form for the first time and we need to build it from
  331. // scratch.
  332. if (!isset($form)) {
  333. // If we attempted to serve the form from cache, uncacheable $form_state
  334. // keys need to be removed after retrieving and preparing the form, except
  335. // any that were already set prior to retrieving the form.
  336. if ($check_cache) {
  337. $form_state_before_retrieval = $form_state;
  338. }
  339. $form = drupal_retrieve_form($form_id, $form_state);
  340. drupal_prepare_form($form_id, $form, $form_state);
  341. // form_set_cache() removes uncacheable $form_state keys defined in
  342. // form_state_keys_no_cache() in order for multi-step forms to work
  343. // properly. This means that form processing logic for single-step forms
  344. // using $form_state['cache'] may depend on data stored in those keys
  345. // during drupal_retrieve_form()/drupal_prepare_form(), but form
  346. // processing should not depend on whether the form is cached or not, so
  347. // $form_state is adjusted to match what it would be after a
  348. // form_set_cache()/form_get_cache() sequence. These exceptions are
  349. // allowed to survive here:
  350. // - always_process: Does not make sense in conjunction with form caching
  351. // in the first place, since passing form_build_id as a GET parameter is
  352. // not desired.
  353. // - temporary: Any assigned data is expected to survives within the same
  354. // page request.
  355. if ($check_cache) {
  356. $uncacheable_keys = array_flip(array_diff(form_state_keys_no_cache(), array('always_process', 'temporary')));
  357. $form_state = array_diff_key($form_state, $uncacheable_keys);
  358. $form_state += $form_state_before_retrieval;
  359. }
  360. }
  361. // Now that we have a constructed form, process it. This is where:
  362. // - Element #process functions get called to further refine $form.
  363. // - User input, if any, gets incorporated in the #value property of the
  364. // corresponding elements and into $form_state['values'].
  365. // - Validation and submission handlers are called.
  366. // - If this submission is part of a multistep workflow, the form is rebuilt
  367. // to contain the information of the next step.
  368. // - If necessary, the form and form state are cached or re-cached, so that
  369. // appropriate information persists to the next page request.
  370. // All of the handlers in the pipeline receive $form_state by reference and
  371. // can use it to know or update information about the state of the form.
  372. drupal_process_form($form_id, $form, $form_state);
  373. // If this was a successful submission of a single-step form or the last step
  374. // of a multi-step form, then drupal_process_form() issued a redirect to
  375. // another page, or back to this page, but as a new request. Therefore, if
  376. // we're here, it means that this is either a form being viewed initially
  377. // before any user input, or there was a validation error requiring the form
  378. // to be re-displayed, or we're in a multi-step workflow and need to display
  379. // the form's next step. In any case, we have what we need in $form, and can
  380. // return it for rendering.
  381. return $form;
  382. }
  383. /**
  384. * Retrieves default values for the $form_state array.
  385. */
  386. function form_state_defaults() {
  387. return array(
  388. 'rebuild' => FALSE,
  389. 'rebuild_info' => array(),
  390. 'redirect' => NULL,
  391. // @todo 'args' is usually set, so no other default 'build_info' keys are
  392. // appended via += form_state_defaults().
  393. 'build_info' => array(
  394. 'args' => array(),
  395. 'files' => array(),
  396. ),
  397. 'temporary' => array(),
  398. 'submitted' => FALSE,
  399. 'executed' => FALSE,
  400. 'programmed' => FALSE,
  401. 'programmed_bypass_access_check' => TRUE,
  402. 'cache'=> FALSE,
  403. 'method' => 'post',
  404. 'groups' => array(),
  405. 'buttons' => array(),
  406. );
  407. }
  408. /**
  409. * Constructs a new $form from the information in $form_state.
  410. *
  411. * This is the key function for making multi-step forms advance from step to
  412. * step. It is called by drupal_process_form() when all user input processing,
  413. * including calling validation and submission handlers, for the request is
  414. * finished. If a validate or submit handler set $form_state['rebuild'] to TRUE,
  415. * and if other conditions don't preempt a rebuild from happening, then this
  416. * function is called to generate a new $form, the next step in the form
  417. * workflow, to be returned for rendering.
  418. *
  419. * Ajax form submissions are almost always multi-step workflows, so that is one
  420. * common use-case during which form rebuilding occurs. See ajax_form_callback()
  421. * for more information about creating Ajax-enabled forms.
  422. *
  423. * @param $form_id
  424. * The unique string identifying the desired form. If a function
  425. * with that name exists, it is called to build the form array.
  426. * Modules that need to generate the same form (or very similar forms)
  427. * using different $form_ids can implement hook_forms(), which maps
  428. * different $form_id values to the proper form constructor function. Examples
  429. * may be found in node_forms() and search_forms().
  430. * @param $form_state
  431. * A keyed array containing the current state of the form.
  432. * @param $old_form
  433. * (optional) A previously built $form. Used to retain the #build_id and
  434. * #action properties in Ajax callbacks and similar partial form rebuilds. The
  435. * only properties copied from $old_form are the ones which both exist in
  436. * $old_form and for which $form_state['rebuild_info']['copy'][PROPERTY] is
  437. * TRUE. If $old_form is not passed, the entire $form is rebuilt freshly.
  438. * 'rebuild_info' needs to be a separate top-level property next to
  439. * 'build_info', since the contained data must not be cached.
  440. *
  441. * @return
  442. * The newly built form.
  443. *
  444. * @see drupal_process_form()
  445. * @see ajax_form_callback()
  446. */
  447. function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
  448. $form = drupal_retrieve_form($form_id, $form_state);
  449. // If only parts of the form will be returned to the browser (e.g., Ajax or
  450. // RIA clients), or if the form already had a new build ID regenerated when it
  451. // was retrieved from the form cache, reuse the existing #build_id.
  452. // Otherwise, a new #build_id is generated, to not clobber the previous
  453. // build's data in the form cache; also allowing the user to go back to an
  454. // earlier build, make changes, and re-submit.
  455. // @see drupal_prepare_form()
  456. $enforce_old_build_id = isset($old_form['#build_id']) && !empty($form_state['rebuild_info']['copy']['#build_id']);
  457. $old_form_is_mutable_copy = isset($old_form['#build_id_old']);
  458. if ($enforce_old_build_id || $old_form_is_mutable_copy) {
  459. $form['#build_id'] = $old_form['#build_id'];
  460. if ($old_form_is_mutable_copy) {
  461. $form['#build_id_old'] = $old_form['#build_id_old'];
  462. }
  463. }
  464. else {
  465. if (isset($old_form['#build_id'])) {
  466. $form['#build_id_old'] = $old_form['#build_id'];
  467. }
  468. $form['#build_id'] = 'form-' . drupal_random_key();
  469. }
  470. // #action defaults to request_uri(), but in case of Ajax and other partial
  471. // rebuilds, the form is submitted to an alternate URL, and the original
  472. // #action needs to be retained.
  473. if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
  474. $form['#action'] = $old_form['#action'];
  475. }
  476. drupal_prepare_form($form_id, $form, $form_state);
  477. // Caching is normally done in drupal_process_form(), but what needs to be
  478. // cached is the $form structure before it passes through form_builder(),
  479. // so we need to do it here.
  480. // @todo For Drupal 8, find a way to avoid this code duplication.
  481. if (empty($form_state['no_cache'])) {
  482. form_set_cache($form['#build_id'], $form, $form_state);
  483. }
  484. // Clear out all group associations as these might be different when
  485. // re-rendering the form.
  486. $form_state['groups'] = array();
  487. // Return a fully built form that is ready for rendering.
  488. return form_builder($form_id, $form, $form_state);
  489. }
  490. /**
  491. * Fetches a form from cache.
  492. */
  493. function form_get_cache($form_build_id, &$form_state) {
  494. if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
  495. $form = $cached->data;
  496. global $user;
  497. if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
  498. if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
  499. // Re-populate $form_state for subsequent rebuilds.
  500. $form_state = $cached->data + $form_state;
  501. // If the original form is contained in include files, load the files.
  502. // @see form_load_include()
  503. $form_state['build_info'] += array('files' => array());
  504. foreach ($form_state['build_info']['files'] as $file) {
  505. if (is_array($file)) {
  506. $file += array('type' => 'inc', 'name' => $file['module']);
  507. module_load_include($file['type'], $file['module'], $file['name']);
  508. }
  509. elseif (file_exists($file)) {
  510. require_once DRUPAL_ROOT . '/' . $file;
  511. }
  512. }
  513. }
  514. // Generate a new #build_id if the cached form was rendered on a cacheable
  515. // page.
  516. if (!empty($form_state['build_info']['immutable'])) {
  517. $form['#build_id_old'] = $form['#build_id'];
  518. $form['#build_id'] = 'form-' . drupal_random_key();
  519. $form['form_build_id']['#value'] = $form['#build_id'];
  520. $form['form_build_id']['#id'] = $form['#build_id'];
  521. unset($form_state['build_info']['immutable']);
  522. }
  523. return $form;
  524. }
  525. }
  526. }
  527. /**
  528. * Stores a form in the cache.
  529. */
  530. function form_set_cache($form_build_id, $form, $form_state) {
  531. // 6 hours cache life time for forms should be plenty.
  532. $expire = 21600;
  533. // Ensure that the form build_id embedded in the form structure is the same as
  534. // the one passed in as a parameter. This is an additional safety measure to
  535. // prevent legacy code operating directly with form_get_cache and
  536. // form_set_cache from accidentally overwriting immutable form state.
  537. if ($form['#build_id'] != $form_build_id) {
  538. watchdog('form', 'Form build-id mismatch detected while attempting to store a form in the cache.', array(), WATCHDOG_ERROR);
  539. return;
  540. }
  541. // Cache form structure.
  542. if (isset($form)) {
  543. if ($GLOBALS['user']->uid) {
  544. $form['#cache_token'] = drupal_get_token();
  545. }
  546. unset($form['#build_id_old']);
  547. cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
  548. }
  549. // Cache form state.
  550. if (variable_get('cache', 0) && drupal_page_is_cacheable()) {
  551. $form_state['build_info']['immutable'] = TRUE;
  552. }
  553. if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
  554. cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
  555. }
  556. }
  557. /**
  558. * Returns an array of $form_state keys that shouldn't be cached.
  559. */
  560. function form_state_keys_no_cache() {
  561. return array(
  562. // Public properties defined by form constructors and form handlers.
  563. 'always_process',
  564. 'must_validate',
  565. 'rebuild',
  566. 'rebuild_info',
  567. 'redirect',
  568. 'no_redirect',
  569. 'temporary',
  570. // Internal properties defined by form processing.
  571. 'buttons',
  572. 'triggering_element',
  573. 'clicked_button',
  574. 'complete form',
  575. 'groups',
  576. 'input',
  577. 'method',
  578. 'submit_handlers',
  579. 'submitted',
  580. 'executed',
  581. 'validate_handlers',
  582. 'values',
  583. );
  584. }
  585. /**
  586. * Ensures an include file is loaded whenever the form is processed.
  587. *
  588. * Example:
  589. * @code
  590. * // Load node.admin.inc from Node module.
  591. * form_load_include($form_state, 'inc', 'node', 'node.admin');
  592. * @endcode
  593. *
  594. * Use this function instead of module_load_include() from inside a form
  595. * constructor or any form processing logic as it ensures that the include file
  596. * is loaded whenever the form is processed. In contrast to using
  597. * module_load_include() directly, form_load_include() makes sure the include
  598. * file is correctly loaded also if the form is cached.
  599. *
  600. * @param $form_state
  601. * The current state of the form.
  602. * @param $type
  603. * The include file's type (file extension).
  604. * @param $module
  605. * The module to which the include file belongs.
  606. * @param $name
  607. * (optional) The base file name (without the $type extension). If omitted,
  608. * $module is used; i.e., resulting in "$module.$type" by default.
  609. *
  610. * @return
  611. * The filepath of the loaded include file, or FALSE if the include file was
  612. * not found or has been loaded already.
  613. *
  614. * @see module_load_include()
  615. */
  616. function form_load_include(&$form_state, $type, $module, $name = NULL) {
  617. if (!isset($name)) {
  618. $name = $module;
  619. }
  620. if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
  621. // Only add successfully included files to the form state.
  622. if ($result = module_load_include($type, $module, $name)) {
  623. $form_state['build_info']['files']["$module:$name.$type"] = array(
  624. 'type' => $type,
  625. 'module' => $module,
  626. 'name' => $name,
  627. );
  628. return $result;
  629. }
  630. }
  631. return FALSE;
  632. }
  633. /**
  634. * Retrieves, populates, and processes a form.
  635. *
  636. * This function allows you to supply values for form elements and submit a
  637. * form for processing. Compare to drupal_get_form(), which also builds and
  638. * processes a form, but does not allow you to supply values.
  639. *
  640. * There is no return value, but you can check to see if there are errors
  641. * by calling form_get_errors().
  642. *
  643. * @param $form_id
  644. * The unique string identifying the desired form. If a function
  645. * with that name exists, it is called to build the form array.
  646. * Modules that need to generate the same form (or very similar forms)
  647. * using different $form_ids can implement hook_forms(), which maps
  648. * different $form_id values to the proper form constructor function. Examples
  649. * may be found in node_forms() and search_forms().
  650. * @param $form_state
  651. * A keyed array containing the current state of the form. Most important is
  652. * the $form_state['values'] collection, a tree of data used to simulate the
  653. * incoming $_POST information from a user's form submission. If a key is not
  654. * filled in $form_state['values'], then the default value of the respective
  655. * element is used. To submit an unchecked checkbox or other control that
  656. * browsers submit by not having a $_POST entry, include the key, but set the
  657. * value to NULL.
  658. * @param ...
  659. * Any additional arguments are passed on to the functions called by
  660. * drupal_form_submit(), including the unique form constructor function.
  661. * For example, the node_edit form requires that a node object be passed
  662. * in here when it is called. Arguments that need to be passed by reference
  663. * should not be included here, but rather placed directly in the $form_state
  664. * build info array so that the reference can be preserved. For example, a
  665. * form builder function with the following signature:
  666. * @code
  667. * function mymodule_form($form, &$form_state, &$object) {
  668. * }
  669. * @endcode
  670. * would be called via drupal_form_submit() as follows:
  671. * @code
  672. * $form_state['values'] = $my_form_values;
  673. * $form_state['build_info']['args'] = array(&$object);
  674. * drupal_form_submit('mymodule_form', $form_state);
  675. * @endcode
  676. * For example:
  677. * @code
  678. * // register a new user
  679. * $form_state = array();
  680. * $form_state['values']['name'] = 'robo-user';
  681. * $form_state['values']['mail'] = 'robouser@example.com';
  682. * $form_state['values']['pass']['pass1'] = 'password';
  683. * $form_state['values']['pass']['pass2'] = 'password';
  684. * $form_state['values']['op'] = t('Create new account');
  685. * drupal_form_submit('user_register_form', $form_state);
  686. * @endcode
  687. */
  688. function drupal_form_submit($form_id, &$form_state) {
  689. if (!isset($form_state['build_info']['args'])) {
  690. $args = func_get_args();
  691. array_shift($args);
  692. array_shift($args);
  693. $form_state['build_info']['args'] = $args;
  694. }
  695. // Merge in default values.
  696. $form_state += form_state_defaults();
  697. // Populate $form_state['input'] with the submitted values before retrieving
  698. // the form, to be consistent with what drupal_build_form() does for
  699. // non-programmatic submissions (form builder functions may expect it to be
  700. // there).
  701. $form_state['input'] = $form_state['values'];
  702. $form_state['programmed'] = TRUE;
  703. $form = drupal_retrieve_form($form_id, $form_state);
  704. // Programmed forms are always submitted.
  705. $form_state['submitted'] = TRUE;
  706. // Reset form validation.
  707. $form_state['must_validate'] = TRUE;
  708. form_clear_error();
  709. drupal_prepare_form($form_id, $form, $form_state);
  710. drupal_process_form($form_id, $form, $form_state);
  711. }
  712. /**
  713. * Retrieves the structured array that defines a given form.
  714. *
  715. * @param $form_id
  716. * The unique string identifying the desired form. If a function
  717. * with that name exists, it is called to build the form array.
  718. * Modules that need to generate the same form (or very similar forms)
  719. * using different $form_ids can implement hook_forms(), which maps
  720. * different $form_id values to the proper form constructor function.
  721. * @param $form_state
  722. * A keyed array containing the current state of the form, including the
  723. * additional arguments to drupal_get_form() or drupal_form_submit() in the
  724. * 'args' component of the array.
  725. */
  726. function drupal_retrieve_form($form_id, &$form_state) {
  727. $forms = &drupal_static(__FUNCTION__);
  728. // Record the $form_id.
  729. $form_state['build_info']['form_id'] = $form_id;
  730. // Record the filepath of the include file containing the original form, so
  731. // the form builder callbacks can be loaded when the form is being rebuilt
  732. // from cache on a different path (such as 'system/ajax'). See
  733. // form_get_cache(). Don't do this in maintenance mode as Drupal may not be
  734. // fully bootstrapped (i.e. during installation) in which case
  735. // menu_get_item() is not available.
  736. if (!isset($form_state['build_info']['files']['menu']) && !defined('MAINTENANCE_MODE')) {
  737. $item = menu_get_item();
  738. if (!empty($item['include_file'])) {
  739. // Do not use form_load_include() here, as the file is already loaded.
  740. // Anyway, form_get_cache() is able to handle filepaths too.
  741. $form_state['build_info']['files']['menu'] = $item['include_file'];
  742. }
  743. }
  744. // We save two copies of the incoming arguments: one for modules to use
  745. // when mapping form ids to constructor functions, and another to pass to
  746. // the constructor function itself.
  747. $args = $form_state['build_info']['args'];
  748. // We first check to see if there's a function named after the $form_id.
  749. // If there is, we simply pass the arguments on to it to get the form.
  750. if (!function_exists($form_id)) {
  751. // In cases where many form_ids need to share a central constructor function,
  752. // such as the node editing form, modules can implement hook_forms(). It
  753. // maps one or more form_ids to the correct constructor functions.
  754. //
  755. // We cache the results of that hook to save time, but that only works
  756. // for modules that know all their form_ids in advance. (A module that
  757. // adds a small 'rate this comment' form to each comment in a list
  758. // would need a unique form_id for each one, for example.)
  759. //
  760. // So, we call the hook if $forms isn't yet populated, OR if it doesn't
  761. // yet have an entry for the requested form_id.
  762. if (!isset($forms) || !isset($forms[$form_id])) {
  763. $forms = module_invoke_all('forms', $form_id, $args);
  764. }
  765. $form_definition = $forms[$form_id];
  766. if (isset($form_definition['callback arguments'])) {
  767. $args = array_merge($form_definition['callback arguments'], $args);
  768. }
  769. if (isset($form_definition['callback'])) {
  770. $callback = $form_definition['callback'];
  771. $form_state['build_info']['base_form_id'] = $callback;
  772. }
  773. // In case $form_state['wrapper_callback'] is not defined already, we also
  774. // allow hook_forms() to define one.
  775. if (!isset($form_state['wrapper_callback']) && isset($form_definition['wrapper_callback'])) {
  776. $form_state['wrapper_callback'] = $form_definition['wrapper_callback'];
  777. }
  778. }
  779. $form = array();
  780. // We need to pass $form_state by reference in order for forms to modify it,
  781. // since call_user_func_array() requires that referenced variables are passed
  782. // explicitly.
  783. $args = array_merge(array($form, &$form_state), $args);
  784. // When the passed $form_state (not using drupal_get_form()) defines a
  785. // 'wrapper_callback', then it requests to invoke a separate (wrapping) form
  786. // builder function to pre-populate the $form array with form elements, which
  787. // the actual form builder function ($callback) expects. This allows for
  788. // pre-populating a form with common elements for certain forms, such as
  789. // back/next/save buttons in multi-step form wizards. See drupal_build_form().
  790. if (isset($form_state['wrapper_callback']) && function_exists($form_state['wrapper_callback'])) {
  791. $form = call_user_func_array($form_state['wrapper_callback'], $args);
  792. // Put the prepopulated $form into $args.
  793. $args[0] = $form;
  794. }
  795. // If $callback was returned by a hook_forms() implementation, call it.
  796. // Otherwise, call the function named after the form id.
  797. $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
  798. $form['#form_id'] = $form_id;
  799. return $form;
  800. }
  801. /**
  802. * Processes a form submission.
  803. *
  804. * This function is the heart of form API. The form gets built, validated and in
  805. * appropriate cases, submitted and rebuilt.
  806. *
  807. * @param $form_id
  808. * The unique string identifying the current form.
  809. * @param $form
  810. * An associative array containing the structure of the form.
  811. * @param $form_state
  812. * A keyed array containing the current state of the form. This
  813. * includes the current persistent storage data for the form, and
  814. * any data passed along by earlier steps when displaying a
  815. * multi-step form. Additional information, like the sanitized $_POST
  816. * data, is also accumulated here.
  817. */
  818. function drupal_process_form($form_id, &$form, &$form_state) {
  819. $form_state['values'] = array();
  820. // With $_GET, these forms are always submitted if requested.
  821. if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
  822. if (!isset($form_state['input']['form_build_id'])) {
  823. $form_state['input']['form_build_id'] = $form['#build_id'];
  824. }
  825. if (!isset($form_state['input']['form_id'])) {
  826. $form_state['input']['form_id'] = $form_id;
  827. }
  828. if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
  829. $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  830. }
  831. }
  832. // form_builder() finishes building the form by calling element #process
  833. // functions and mapping user input, if any, to #value properties, and also
  834. // storing the values in $form_state['values']. We need to retain the
  835. // unprocessed $form in case it needs to be cached.
  836. $unprocessed_form = $form;
  837. $form = form_builder($form_id, $form, $form_state);
  838. // Only process the input if we have a correct form submission.
  839. if ($form_state['process_input']) {
  840. drupal_validate_form($form_id, $form, $form_state);
  841. // drupal_html_id() maintains a cache of element IDs it has seen,
  842. // so it can prevent duplicates. We want to be sure we reset that
  843. // cache when a form is processed, so scenarios that result in
  844. // the form being built behind the scenes and again for the
  845. // browser don't increment all the element IDs needlessly.
  846. if (!form_get_errors()) {
  847. // In case of errors, do not break HTML IDs of other forms.
  848. drupal_static_reset('drupal_html_id');
  849. }
  850. if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  851. // Execute form submit handlers.
  852. form_execute_handlers('submit', $form, $form_state);
  853. // We'll clear out the cached copies of the form and its stored data
  854. // here, as we've finished with them. The in-memory copies are still
  855. // here, though.
  856. if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
  857. cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
  858. cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
  859. }
  860. // If batches were set in the submit handlers, we process them now,
  861. // possibly ending execution. We make sure we do not react to the batch
  862. // that is already being processed (if a batch operation performs a
  863. // drupal_form_submit).
  864. if ($batch =& batch_get() && !isset($batch['current_set'])) {
  865. // Store $form_state information in the batch definition.
  866. // We need the full $form_state when either:
  867. // - Some submit handlers were saved to be called during batch
  868. // processing. See form_execute_handlers().
  869. // - The form is multistep.
  870. // In other cases, we only need the information expected by
  871. // drupal_redirect_form().
  872. if ($batch['has_form_submits'] || !empty($form_state['rebuild'])) {
  873. $batch['form_state'] = $form_state;
  874. }
  875. else {
  876. $batch['form_state'] = array_intersect_key($form_state, array_flip(array('programmed', 'rebuild', 'storage', 'no_redirect', 'redirect')));
  877. }
  878. $batch['progressive'] = !$form_state['programmed'];
  879. batch_process();
  880. // Execution continues only for programmatic forms.
  881. // For 'regular' forms, we get redirected to the batch processing
  882. // page. Form redirection will be handled in _batch_finished(),
  883. // after the batch is processed.
  884. }
  885. // Set a flag to indicate that the form has been processed and executed.
  886. $form_state['executed'] = TRUE;
  887. // Redirect the form based on values in $form_state.
  888. drupal_redirect_form($form_state);
  889. }
  890. // Don't rebuild or cache form submissions invoked via drupal_form_submit().
  891. if (!empty($form_state['programmed'])) {
  892. return;
  893. }
  894. // If $form_state['rebuild'] has been set and input has been processed
  895. // without validation errors, we are in a multi-step workflow that is not
  896. // yet complete. A new $form needs to be constructed based on the changes
  897. // made to $form_state during this request. Normally, a submit handler sets
  898. // $form_state['rebuild'] if a fully executed form requires another step.
  899. // However, for forms that have not been fully executed (e.g., Ajax
  900. // submissions triggered by non-buttons), there is no submit handler to set
  901. // $form_state['rebuild']. It would not make sense to redisplay the
  902. // identical form without an error for the user to correct, so we also
  903. // rebuild error-free non-executed forms, regardless of
  904. // $form_state['rebuild'].
  905. // @todo D8: Simplify this logic; considering Ajax and non-HTML front-ends,
  906. // along with element-level #submit properties, it makes no sense to have
  907. // divergent form execution based on whether the triggering element has
  908. // #executes_submit_callback set to TRUE.
  909. if (($form_state['rebuild'] || !$form_state['executed']) && !form_get_errors()) {
  910. // Form building functions (e.g., _form_builder_handle_input_element())
  911. // may use $form_state['rebuild'] to determine if they are running in the
  912. // context of a rebuild, so ensure it is set.
  913. $form_state['rebuild'] = TRUE;
  914. $form = drupal_rebuild_form($form_id, $form_state, $form);
  915. }
  916. }
  917. // After processing the form, the form builder or a #process callback may
  918. // have set $form_state['cache'] to indicate that the form and form state
  919. // shall be cached. But the form may only be cached if the 'no_cache' property
  920. // is not set to TRUE. Only cache $form as it was prior to form_builder(),
  921. // because form_builder() must run for each request to accommodate new user
  922. // input. Rebuilt forms are not cached here, because drupal_rebuild_form()
  923. // already takes care of that.
  924. if (!$form_state['rebuild'] && $form_state['cache'] && empty($form_state['no_cache'])) {
  925. form_set_cache($form['#build_id'], $unprocessed_form, $form_state);
  926. }
  927. }
  928. /**
  929. * Prepares a structured form array.
  930. *
  931. * Adds required elements, executes any hook_form_alter functions, and
  932. * optionally inserts a validation token to prevent tampering.
  933. *
  934. * @param $form_id
  935. * A unique string identifying the form for validation, submission,
  936. * theming, and hook_form_alter functions.
  937. * @param $form
  938. * An associative array containing the structure of the form.
  939. * @param $form_state
  940. * A keyed array containing the current state of the form. Passed
  941. * in here so that hook_form_alter() calls can use it, as well.
  942. */
  943. function drupal_prepare_form($form_id, &$form, &$form_state) {
  944. global $user;
  945. $form['#type'] = 'form';
  946. $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
  947. // Fix the form method, if it is 'get' in $form_state, but not in $form.
  948. if ($form_state['method'] == 'get' && !isset($form['#method'])) {
  949. $form['#method'] = 'get';
  950. }
  951. // Generate a new #build_id for this form, if none has been set already. The
  952. // form_build_id is used as key to cache a particular build of the form. For
  953. // multi-step forms, this allows the user to go back to an earlier build, make
  954. // changes, and re-submit.
  955. // @see drupal_build_form()
  956. // @see drupal_rebuild_form()
  957. if (!isset($form['#build_id'])) {
  958. $form['#build_id'] = 'form-' . drupal_random_key();
  959. }
  960. $form['form_build_id'] = array(
  961. '#type' => 'hidden',
  962. '#value' => $form['#build_id'],
  963. '#id' => $form['#build_id'],
  964. '#name' => 'form_build_id',
  965. // Form processing and validation requires this value, so ensure the
  966. // submitted form value appears literally, regardless of custom #tree
  967. // and #parents being set elsewhere.
  968. '#parents' => array('form_build_id'),
  969. );
  970. // Add a token, based on either #token or form_id, to any form displayed to
  971. // authenticated users. This ensures that any submitted form was actually
  972. // requested previously by the user and protects against cross site request
  973. // forgeries.
  974. // This does not apply to programmatically submitted forms. Furthermore, since
  975. // tokens are session-bound and forms displayed to anonymous users are very
  976. // likely cached, we cannot assign a token for them.
  977. // During installation, there is no $user yet.
  978. if (!empty($user->uid) && !$form_state['programmed']) {
  979. // Form constructors may explicitly set #token to FALSE when cross site
  980. // request forgery is irrelevant to the form, such as search forms.
  981. if (isset($form['#token']) && $form['#token'] === FALSE) {
  982. unset($form['#token']);
  983. }
  984. // Otherwise, generate a public token based on the form id.
  985. else {
  986. $form['#token'] = $form_id;
  987. $form['form_token'] = array(
  988. '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
  989. '#type' => 'token',
  990. '#default_value' => drupal_get_token($form['#token']),
  991. // Form processing and validation requires this value, so ensure the
  992. // submitted form value appears literally, regardless of custom #tree
  993. // and #parents being set elsewhere.
  994. '#parents' => array('form_token'),
  995. );
  996. }
  997. }
  998. if (isset($form_id)) {
  999. $form['form_id'] = array(
  1000. '#type' => 'hidden',
  1001. '#value' => $form_id,
  1002. '#id' => drupal_html_id("edit-$form_id"),
  1003. // Form processing and validation requires this value, so ensure the
  1004. // submitted form value appears literally, regardless of custom #tree
  1005. // and #parents being set elsewhere.
  1006. '#parents' => array('form_id'),
  1007. );
  1008. }
  1009. if (!isset($form['#id'])) {
  1010. $form['#id'] = drupal_html_id($form_id);
  1011. }
  1012. $form += element_info('form');
  1013. $form += array('#tree' => FALSE, '#parents' => array());
  1014. if (!isset($form['#validate'])) {
  1015. // Ensure that modules can rely on #validate being set.
  1016. $form['#validate'] = array();
  1017. // Check for a handler specific to $form_id.
  1018. if (function_exists($form_id . '_validate')) {
  1019. $form['#validate'][] = $form_id . '_validate';
  1020. }
  1021. // Otherwise check whether this is a shared form and whether there is a
  1022. // handler for the shared $form_id.
  1023. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_validate')) {
  1024. $form['#validate'][] = $form_state['build_info']['base_form_id'] . '_validate';
  1025. }
  1026. }
  1027. if (!isset($form['#submit'])) {
  1028. // Ensure that modules can rely on #submit being set.
  1029. $form['#submit'] = array();
  1030. // Check for a handler specific to $form_id.
  1031. if (function_exists($form_id . '_submit')) {
  1032. $form['#submit'][] = $form_id . '_submit';
  1033. }
  1034. // Otherwise check whether this is a shared form and whether there is a
  1035. // handler for the shared $form_id.
  1036. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  1037. $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
  1038. }
  1039. }
  1040. // If no #theme has been set, automatically apply theme suggestions.
  1041. // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
  1042. // #theme function only has to care for rendering the inner form elements,
  1043. // not the form itself.
  1044. if (!isset($form['#theme'])) {
  1045. $form['#theme'] = array($form_id);
  1046. if (isset($form_state['build_info']['base_form_id'])) {
  1047. $form['#theme'][] = $form_state['build_info']['base_form_id'];
  1048. }
  1049. }
  1050. // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
  1051. // hook_form_FORM_ID_alter() implementations.
  1052. $hooks = array('form');
  1053. if (isset($form_state['build_info']['base_form_id'])) {
  1054. $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
  1055. }
  1056. $hooks[] = 'form_' . $form_id;
  1057. drupal_alter($hooks, $form, $form_state, $form_id);
  1058. }
  1059. /**
  1060. * Helper function to call form_set_error() if there is a token error.
  1061. */
  1062. function _drupal_invalid_token_set_form_error() {
  1063. $path = current_path();
  1064. $query = drupal_get_query_parameters();
  1065. $url = url($path, array('query' => $query));
  1066. // Setting this error will cause the form to fail validation.
  1067. form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
  1068. }
  1069. /**
  1070. * Validates user-submitted form data in the $form_state array.
  1071. *
  1072. * @param $form_id
  1073. * A unique string identifying the form for validation, submission,
  1074. * theming, and hook_form_alter functions.
  1075. * @param $form
  1076. * An associative array containing the structure of the form, which is passed
  1077. * by reference. Form validation handlers are able to alter the form structure
  1078. * (like #process and #after_build callbacks during form building) in case of
  1079. * a validation error. If a validation handler alters the form structure, it
  1080. * is responsible for validating the values of changed form elements in
  1081. * $form_state['values'] to prevent form submit handlers from receiving
  1082. * unvalidated values.
  1083. * @param $form_state
  1084. * A keyed array containing the current state of the form. The current
  1085. * user-submitted data is stored in $form_state['values'], though
  1086. * form validation functions are passed an explicit copy of the
  1087. * values for the sake of simplicity. Validation handlers can also use
  1088. * $form_state to pass information on to submit handlers. For example:
  1089. * $form_state['data_for_submission'] = $data;
  1090. * This technique is useful when validation requires file parsing,
  1091. * web service requests, or other expensive requests that should
  1092. * not be repeated in the submission step.
  1093. */
  1094. function drupal_validate_form($form_id, &$form, &$form_state) {
  1095. $validated_forms = &drupal_static(__FUNCTION__, array());
  1096. if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
  1097. return;
  1098. }
  1099. // If the session token was set by drupal_prepare_form(), ensure that it
  1100. // matches the current user's session. This is duplicate to code in
  1101. // form_builder() but left to protect any custom form handling code.
  1102. if (isset($form['#token'])) {
  1103. if (!drupal_valid_token($form_state['values']['form_token'], $form['#token']) || !empty($form_state['invalid_token'])) {
  1104. _drupal_invalid_token_set_form_error();
  1105. // Stop here and don't run any further validation handlers, because they
  1106. // could invoke non-safe operations which opens the door for CSRF
  1107. // vulnerabilities.
  1108. $validated_forms[$form_id] = TRUE;
  1109. return;
  1110. }
  1111. }
  1112. _form_validate($form, $form_state, $form_id);
  1113. $validated_forms[$form_id] = TRUE;
  1114. // If validation errors are limited then remove any non validated form values,
  1115. // so that only values that passed validation are left for submit callbacks.
  1116. if (isset($form_state['triggering_element']['#limit_validation_errors']) && $form_state['triggering_element']['#limit_validation_errors'] !== FALSE) {
  1117. $values = array();
  1118. foreach ($form_state['triggering_element']['#limit_validation_errors'] as $section) {
  1119. // If the section exists within $form_state['values'], even if the value
  1120. // is NULL, copy it to $values.
  1121. $section_exists = NULL;
  1122. $value = drupal_array_get_nested_value($form_state['values'], $section, $section_exists);
  1123. if ($section_exists) {
  1124. drupal_array_set_nested_value($values, $section, $value);
  1125. }
  1126. }
  1127. // A button's #value does not require validation, so for convenience we
  1128. // allow the value of the clicked button to be retained in its normal
  1129. // $form_state['values'] locations, even if these locations are not included
  1130. // in #limit_validation_errors.
  1131. if (isset($form_state['triggering_element']['#button_type'])) {
  1132. $button_value = $form_state['triggering_element']['#value'];
  1133. // Like all input controls, the button value may be in the location
  1134. // dictated by #parents. If it is, copy it to $values, but do not override
  1135. // what may already be in $values.
  1136. $parents = $form_state['triggering_element']['#parents'];
  1137. if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
  1138. drupal_array_set_nested_value($values, $parents, $button_value);
  1139. }
  1140. // Additionally, form_builder() places the button value in
  1141. // $form_state['values'][BUTTON_NAME]. If it's still there, after
  1142. // validation handlers have run, copy it to $values, but do not override
  1143. // what may already be in $values.
  1144. $name = $form_state['triggering_element']['#name'];
  1145. if (!isset($values[$name]) && isset($form_state['values'][$name]) && $form_state['values'][$name] === $button_value) {
  1146. $values[$name] = $button_value;
  1147. }
  1148. }
  1149. $form_state['values'] = $values;
  1150. }
  1151. }
  1152. /**
  1153. * Redirects the user to a URL after a form has been processed.
  1154. *
  1155. * After a form is submitted and processed, normally the user should be
  1156. * redirected to a new destination page. This function figures out what that
  1157. * destination should be, based on the $form_state array and the 'destination'
  1158. * query string in the request URL, and redirects the user there.
  1159. *
  1160. * Usually (for exceptions, see below) $form_state['redirect'] determines where
  1161. * to redirect the user. This can be set either to a string (the path to
  1162. * redirect to), or an array of arguments for drupal_goto(). If
  1163. * $form_state['redirect'] is missing, the user is usually (again, see below for
  1164. * exceptions) redirected back to the page they came from, where they should see
  1165. * a fresh, unpopulated copy of the form.
  1166. *
  1167. * Here is an example of how to set up a form to redirect to the path 'node':
  1168. * @code
  1169. * $form_state['redirect'] = 'node';
  1170. * @endcode
  1171. * And here is an example of how to redirect to 'node/123?foo=bar#baz':
  1172. * @code
  1173. * $form_state['redirect'] = array(
  1174. * 'node/123',
  1175. * array(
  1176. * 'query' => array(
  1177. * 'foo' => 'bar',
  1178. * ),
  1179. * 'fragment' => 'baz',
  1180. * ),
  1181. * );
  1182. * @endcode
  1183. *
  1184. * There are several exceptions to the "usual" behavior described above:
  1185. * - If $form_state['programmed'] is TRUE, the form submission was usually
  1186. * invoked via drupal_form_submit(), so any redirection would break the script
  1187. * that invoked drupal_form_submit() and no redirection is done.
  1188. * - If $form_state['rebuild'] is TRUE, the form is being rebuilt, and no
  1189. * redirection is done.
  1190. * - If $form_state['no_redirect'] is TRUE, redirection is disabled. This is
  1191. * set, for instance, by ajax_get_form() to prevent redirection in Ajax
  1192. * callbacks. $form_state['no_redirect'] should never be set or altered by
  1193. * form builder functions or form validation/submit handlers.
  1194. * - If $form_state['redirect'] is set to FALSE, redirection is disabled.
  1195. * - If none of the above conditions has prevented redirection, then the
  1196. * redirect is accomplished by calling drupal_goto(), passing in the value of
  1197. * $form_state['redirect'] if it is set, or the current path if it is
  1198. * not. drupal_goto() preferentially uses the value of $_GET['destination']
  1199. * (the 'destination' URL query string) if it is present, so this will
  1200. * override any values set by $form_state['redirect']. Note that during
  1201. * installation, install_goto() is called in place of drupal_goto().
  1202. *
  1203. * @param $form_state
  1204. * An associative array containing the current state of the form.
  1205. *
  1206. * @see drupal_process_form()
  1207. * @see drupal_build_form()
  1208. */
  1209. function drupal_redirect_form($form_state) {
  1210. // Skip redirection for form submissions invoked via drupal_form_submit().
  1211. if (!empty($form_state['programmed'])) {
  1212. return;
  1213. }
  1214. // Skip redirection if rebuild is activated.
  1215. if (!empty($form_state['rebuild'])) {
  1216. return;
  1217. }
  1218. // Skip redirection if it was explicitly disallowed.
  1219. if (!empty($form_state['no_redirect'])) {
  1220. return;
  1221. }
  1222. // Only invoke drupal_goto() if redirect value was not set to FALSE.
  1223. if (!isset($form_state['redirect']) || $form_state['redirect'] !== FALSE) {
  1224. if (isset($form_state['redirect'])) {
  1225. if (is_array($form_state['redirect'])) {
  1226. call_user_func_array('drupal_goto', $form_state['redirect']);
  1227. }
  1228. else {
  1229. // This function can be called from the installer, which guarantees
  1230. // that $redirect will always be a string, so catch that case here
  1231. // and use the appropriate redirect function.
  1232. $function = drupal_installation_attempted() ? 'install_goto' : 'drupal_goto';
  1233. $function($form_state['redirect']);
  1234. }
  1235. }
  1236. drupal_goto(current_path(), array('query' => drupal_get_query_parameters()));
  1237. }
  1238. }
  1239. /**
  1240. * Performs validation on form elements.
  1241. *
  1242. * First ensures required fields are completed, #maxlength is not exceeded, and
  1243. * selected options were in the list of options given to the user. Then calls
  1244. * user-defined validators.
  1245. *
  1246. * @param $elements
  1247. * An associative array containing the structure of the form.
  1248. * @param $form_state
  1249. * A keyed array containing the current state of the form. The current
  1250. * user-submitted data is stored in $form_state['values'], though
  1251. * form validation functions are passed an explicit copy of the
  1252. * values for the sake of simplicity. Validation handlers can also
  1253. * $form_state to pass information on to submit handlers. For example:
  1254. * $form_state['data_for_submission'] = $data;
  1255. * This technique is useful when validation requires file parsing,
  1256. * web service requests, or other expensive requests that should
  1257. * not be repeated in the submission step.
  1258. * @param $form_id
  1259. * A unique string identifying the form for validation, submission,
  1260. * theming, and hook_form_alter functions.
  1261. */
  1262. function _form_validate(&$elements, &$form_state, $form_id = NULL) {
  1263. // Also used in the installer, pre-database setup.
  1264. $t = get_t();
  1265. // Recurse through all children.
  1266. foreach (element_children($elements) as $key) {
  1267. if (isset($elements[$key]) && $elements[$key]) {
  1268. _form_validate($elements[$key], $form_state);
  1269. }
  1270. }
  1271. // Validate the current input.
  1272. if (!isset($elements['#validated']) || !$elements['#validated']) {
  1273. // The following errors are always shown.
  1274. if (isset($elements['#needs_validation'])) {
  1275. // Verify that the value is not longer than #maxlength.
  1276. if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
  1277. form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
  1278. }
  1279. if (isset($elements['#options']) && isset($elements['#value'])) {
  1280. if ($elements['#type'] == 'select') {
  1281. $options = form_options_flatten($elements['#options']);
  1282. }
  1283. else {
  1284. $options = $elements['#options'];
  1285. }
  1286. if (is_array($elements['#value'])) {
  1287. $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
  1288. foreach ($value as $v) {
  1289. if (!isset($options[$v])) {
  1290. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1291. watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1292. }
  1293. }
  1294. }
  1295. // Non-multiple select fields always have a value in HTML. If the user
  1296. // does not change the form, it will be the value of the first option.
  1297. // Because of this, form validation for the field will almost always
  1298. // pass, even if the user did not select anything. To work around this
  1299. // browser behavior, required select fields without a #default_value get
  1300. // an additional, first empty option. In case the submitted value is
  1301. // identical to the empty option's value, we reset the element's value
  1302. // to NULL to trigger the regular #required handling below.
  1303. // @see form_process_select()
  1304. elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
  1305. $elements['#value'] = NULL;
  1306. form_set_value($elements, NULL, $form_state);
  1307. }
  1308. elseif (!isset($options[$elements['#value']])) {
  1309. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1310. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1311. }
  1312. }
  1313. }
  1314. // While this element is being validated, it may be desired that some calls
  1315. // to form_set_error() be suppressed and not result in a form error, so
  1316. // that a button that implements low-risk functionality (such as "Previous"
  1317. // or "Add more") that doesn't require all user input to be valid can still
  1318. // have its submit handlers triggered. The triggering element's
  1319. // #limit_validation_errors property contains the information for which
  1320. // errors are needed, and all other errors are to be suppressed. The
  1321. // #limit_validation_errors property is ignored if submit handlers will run,
  1322. // but the element doesn't have a #submit property, because it's too large a
  1323. // security risk to have any invalid user input when executing form-level
  1324. // submit handlers.
  1325. if (isset($form_state['triggering_element']['#limit_validation_errors']) && ($form_state['triggering_element']['#limit_validation_errors'] !== FALSE) && !($form_state['submitted'] && !isset($form_state['triggering_element']['#submit']))) {
  1326. form_set_error(NULL, '', $form_state['triggering_element']['#limit_validation_errors']);
  1327. }
  1328. // If submit handlers won't run (due to the submission having been triggered
  1329. // by an element whose #executes_submit_callback property isn't TRUE), then
  1330. // it's safe to suppress all validation errors, and we do so by default,
  1331. // which is particularly useful during an Ajax submission triggered by a
  1332. // non-button. An element can override this default by setting the
  1333. // #limit_validation_errors property. For button element types,
  1334. // #limit_validation_errors defaults to FALSE (via system_element_info()),
  1335. // so that full validation is their default behavior.
  1336. elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) {
  1337. form_set_error(NULL, '', array());
  1338. }
  1339. // As an extra security measure, explicitly turn off error suppression if
  1340. // one of the above conditions wasn't met. Since this is also done at the
  1341. // end of this function, doing it here is only to handle the rare edge case
  1342. // where a validate handler invokes form processing of another form.
  1343. else {
  1344. drupal_static_reset('form_set_error:limit_validation_errors');
  1345. }
  1346. // Make sure a value is passed when the field is required.
  1347. if (isset($elements['#needs_validation']) && $elements['#required']) {
  1348. // A simple call to empty() will not cut it here as some fields, like
  1349. // checkboxes, can return a valid value of '0'. Instead, check the
  1350. // length if it's a string, and the item count if it's an array.
  1351. // An unchecked checkbox has a #value of integer 0, different than string
  1352. // '0', which could be a valid value.
  1353. $is_empty_multiple = (!count($elements['#value']));
  1354. $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
  1355. $is_empty_value = ($elements['#value'] === 0);
  1356. if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
  1357. // Although discouraged, a #title is not mandatory for form elements. In
  1358. // case there is no #title, we cannot set a form error message.
  1359. // Instead of setting no #title, form constructors are encouraged to set
  1360. // #title_display to 'invisible' to improve accessibility.
  1361. if (isset($elements['#title'])) {
  1362. form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
  1363. }
  1364. else {
  1365. form_error($elements);
  1366. }
  1367. }
  1368. }
  1369. // Call user-defined form level validators.
  1370. if (isset($form_id)) {
  1371. form_execute_handlers('validate', $elements, $form_state);
  1372. }
  1373. // Call any element-specific validators. These must act on the element
  1374. // #value data.
  1375. elseif (isset($elements['#element_validate'])) {
  1376. foreach ($elements['#element_validate'] as $function) {
  1377. $function($elements, $form_state, $form_state['complete form']);
  1378. }
  1379. }
  1380. $elements['#validated'] = TRUE;
  1381. }
  1382. // Done validating this element, so turn off error suppression.
  1383. // _form_validate() turns it on again when starting on the next element, if
  1384. // it's still appropriate to do so.
  1385. drupal_static_reset('form_set_error:limit_validation_errors');
  1386. }
  1387. /**
  1388. * Executes custom validation and submission handlers for a given form.
  1389. *
  1390. * Button-specific handlers are checked first. If none exist, the function
  1391. * falls back to form-level handlers.
  1392. *
  1393. * @param $type
  1394. * The type of handler to execute. 'validate' or 'submit' are the
  1395. * defaults used by Form API.
  1396. * @param $form
  1397. * An associative array containing the structure of the form.
  1398. * @param $form_state
  1399. * A keyed array containing the current state of the form. If the user
  1400. * submitted the form by clicking a button with custom handler functions
  1401. * defined, those handlers will be stored here.
  1402. */
  1403. function form_execute_handlers($type, &$form, &$form_state) {
  1404. $return = FALSE;
  1405. // If there was a button pressed, use its handlers.
  1406. if (isset($form_state[$type . '_handlers'])) {
  1407. $handlers = $form_state[$type . '_handlers'];
  1408. }
  1409. // Otherwise, check for a form-level handler.
  1410. elseif (isset($form['#' . $type])) {
  1411. $handlers = $form['#' . $type];
  1412. }
  1413. else {
  1414. $handlers = array();
  1415. }
  1416. foreach ($handlers as $function) {
  1417. // Check if a previous _submit handler has set a batch, but make sure we
  1418. // do not react to a batch that is already being processed (for instance
  1419. // if a batch operation performs a drupal_form_submit()).
  1420. if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['id'])) {
  1421. // Some previous submit handler has set a batch. To ensure correct
  1422. // execution order, store the call in a special 'control' batch set.
  1423. // See _batch_next_set().
  1424. $batch['sets'][] = array('form_submit' => $function);
  1425. $batch['has_form_submits'] = TRUE;
  1426. }
  1427. else {
  1428. $function($form, $form_state);
  1429. }
  1430. $return = TRUE;
  1431. }
  1432. return $return;
  1433. }
  1434. /**
  1435. * Files an error against a form element.
  1436. *
  1437. * When a validation error is detected, the validator calls form_set_error() to
  1438. * indicate which element needs to be changed and provide an error message. This
  1439. * causes the Form API to not execute the form submit handlers, and instead to
  1440. * re-display the form to the user with the corresponding elements rendered with
  1441. * an 'error' CSS class (shown as red by default).
  1442. *
  1443. * The standard form_set_error() behavior can be changed if a button provides
  1444. * the #limit_validation_errors property. Multistep forms not wanting to
  1445. * validate the whole form can set #limit_validation_errors on buttons to
  1446. * limit validation errors to only certain elements. For example, pressing the
  1447. * "Previous" button in a multistep form should not fire validation errors just
  1448. * because the current step has invalid values. If #limit_validation_errors is
  1449. * set on a clicked button, the button must also define a #submit property
  1450. * (may be set to an empty array). Any #submit handlers will be executed even if
  1451. * there is invalid input, so extreme care should be taken with respect to any
  1452. * actions taken by them. This is typically not a problem with buttons like
  1453. * "Previous" or "Add more" that do not invoke persistent storage of the
  1454. * submitted form values. Do not use the #limit_validation_errors property on
  1455. * buttons that trigger saving of form values to the database.
  1456. *
  1457. * The #limit_validation_errors property is a list of "sections" within
  1458. * $form_state['values'] that must contain valid values. Each "section" is an
  1459. * array with the ordered set of keys needed to reach that part of
  1460. * $form_state['values'] (i.e., the #parents property of the element).
  1461. *
  1462. * Example 1: Allow the "Previous" button to function, regardless of whether any
  1463. * user input is valid.
  1464. *
  1465. * @code
  1466. * $form['actions']['previous'] = array(
  1467. * '#type' => 'submit',
  1468. * '#value' => t('Previous'),
  1469. * '#limit_validation_errors' => array(), // No validation.
  1470. * '#submit' => array('some_submit_function'), // #submit required.
  1471. * );
  1472. * @endcode
  1473. *
  1474. * Example 2: Require some, but not all, user input to be valid to process the
  1475. * submission of a "Previous" button.
  1476. *
  1477. * @code
  1478. * $form['actions']['previous'] = array(
  1479. * '#type' => 'submit',
  1480. * '#value' => t('Previous'),
  1481. * '#limit_validation_errors' => array(
  1482. * array('step1'), // Validate $form_state['values']['step1'].
  1483. * array('foo', 'bar'), // Validate $form_state['values']['foo']['bar'].
  1484. * ),
  1485. * '#submit' => array('some_submit_function'), // #submit required.
  1486. * );
  1487. * @endcode
  1488. *
  1489. * This will require $form_state['values']['step1'] and everything within it
  1490. * (for example, $form_state['values']['step1']['choice']) to be valid, so
  1491. * calls to form_set_error('step1', $message) or
  1492. * form_set_error('step1][choice', $message) will prevent the submit handlers
  1493. * from running, and result in the error message being displayed to the user.
  1494. * However, calls to form_set_error('step2', $message) and
  1495. * form_set_error('step2][groupX][choiceY', $message) will be suppressed,
  1496. * resulting in the message not being displayed to the user, and the submit
  1497. * handlers will run despite $form_state['values']['step2'] and
  1498. * $form_state['values']['step2']['groupX']['choiceY'] containing invalid
  1499. * values. Errors for an invalid $form_state['values']['foo'] will be
  1500. * suppressed, but errors flagging invalid values for
  1501. * $form_state['values']['foo']['bar'] and everything within it will be
  1502. * flagged and submission prevented.
  1503. *
  1504. * Partial form validation is implemented by suppressing errors rather than by
  1505. * skipping the input processing and validation steps entirely, because some
  1506. * forms have button-level submit handlers that call Drupal API functions that
  1507. * assume that certain data exists within $form_state['values'], and while not
  1508. * doing anything with that data that requires it to be valid, PHP errors
  1509. * would be triggered if the input processing and validation steps were fully
  1510. * skipped.
  1511. *
  1512. * @param $name
  1513. * The name of the form element. If the #parents property of your form
  1514. * element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
  1515. * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
  1516. * element where the #parents array starts with 'foo'.
  1517. * @param $message
  1518. * The error message to present to the user.
  1519. * @param $limit_validation_errors
  1520. * Internal use only. The #limit_validation_errors property of the clicked
  1521. * button, if it exists.
  1522. *
  1523. * @return
  1524. * Return value is for internal use only. To get a list of errors, use
  1525. * form_get_errors() or form_get_error().
  1526. *
  1527. * @see http://drupal.org/node/370537
  1528. * @see http://drupal.org/node/763376
  1529. */
  1530. function form_set_error($name = NULL, $message = '', $limit_validation_errors = NULL) {
  1531. $form = &drupal_static(__FUNCTION__, array());
  1532. $sections = &drupal_static(__FUNCTION__ . ':limit_validation_errors');
  1533. if (isset($limit_validation_errors)) {
  1534. $sections = $limit_validation_errors;
  1535. }
  1536. if (isset($name) && !isset($form[$name])) {
  1537. $record = TRUE;
  1538. if (isset($sections)) {
  1539. // #limit_validation_errors is an array of "sections" within which user
  1540. // input must be valid. If the element is within one of these sections,
  1541. // the error must be recorded. Otherwise, it can be suppressed.
  1542. // #limit_validation_errors can be an empty array, in which case all
  1543. // errors are suppressed. For example, a "Previous" button might want its
  1544. // submit action to be triggered even if none of the submitted values are
  1545. // valid.
  1546. $record = FALSE;
  1547. foreach ($sections as $section) {
  1548. // Exploding by '][' reconstructs the element's #parents. If the
  1549. // reconstructed #parents begin with the same keys as the specified
  1550. // section, then the element's values are within the part of
  1551. // $form_state['values'] that the clicked button requires to be valid,
  1552. // so errors for this element must be recorded. As the exploded array
  1553. // will all be strings, we need to cast every value of the section
  1554. // array to string.
  1555. if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
  1556. $record = TRUE;
  1557. break;
  1558. }
  1559. }
  1560. }
  1561. if ($record) {
  1562. $form[$name] = $message;
  1563. if ($message) {
  1564. drupal_set_message($message, 'error');
  1565. }
  1566. }
  1567. }
  1568. return $form;
  1569. }
  1570. /**
  1571. * Clears all errors against all form elements made by form_set_error().
  1572. */
  1573. function form_clear_error() {
  1574. drupal_static_reset('form_set_error');
  1575. }
  1576. /**
  1577. * Returns an associative array of all errors.
  1578. */
  1579. function form_get_errors() {
  1580. $form = form_set_error();
  1581. if (!empty($form)) {
  1582. return $form;
  1583. }
  1584. }
  1585. /**
  1586. * Returns the error message filed against the given form element.
  1587. *
  1588. * Form errors higher up in the form structure override deeper errors as well as
  1589. * errors on the element itself.
  1590. */
  1591. function form_get_error($element) {
  1592. $form = form_set_error();
  1593. $parents = array();
  1594. foreach ($element['#parents'] as $parent) {
  1595. $parents[] = $parent;
  1596. $key = implode('][', $parents);
  1597. if (isset($form[$key])) {
  1598. return $form[$key];
  1599. }
  1600. }
  1601. }
  1602. /**
  1603. * Flags an element as having an error.
  1604. */
  1605. function form_error(&$element, $message = '') {
  1606. form_set_error(implode('][', $element['#parents']), $message);
  1607. }
  1608. /**
  1609. * Builds and processes all elements in the structured form array.
  1610. *
  1611. * Adds any required properties to each element, maps the incoming input data
  1612. * to the proper elements, and executes any #process handlers attached to a
  1613. * specific element.
  1614. *
  1615. * This is one of the three primary functions that recursively iterates a form
  1616. * array. This one does it for completing the form building process. The other
  1617. * two are _form_validate() (invoked via drupal_validate_form() and used to
  1618. * invoke validation logic for each element) and drupal_render() (for rendering
  1619. * each element). Each of these three pipelines provides ample opportunity for
  1620. * modules to customize what happens. For example, during this function's life
  1621. * cycle, the following functions get called for each element:
  1622. * - $element['#value_callback']: A function that implements how user input is
  1623. * mapped to an element's #value property. This defaults to a function named
  1624. * 'form_type_TYPE_value' where TYPE is $element['#type'].
  1625. * - $element['#process']: An array of functions called after user input has
  1626. * been mapped to the element's #value property. These functions can be used
  1627. * to dynamically add child elements: for example, for the 'date' element
  1628. * type, one of the functions in this array is form_process_date(), which adds
  1629. * the individual 'year', 'month', 'day', etc. child elements. These functions
  1630. * can also be used to set additional properties or implement special logic
  1631. * other than adding child elements: for example, for the 'fieldset' element
  1632. * type, one of the functions in this array is form_process_fieldset(), which
  1633. * adds the attributes and JavaScript needed to make the fieldset collapsible
  1634. * if the #collapsible property is set. The #process functions are called in
  1635. * preorder traversal, meaning they are called for the parent element first,
  1636. * then for the child elements.
  1637. * - $element['#after_build']: An array of functions called after form_builder()
  1638. * is done with its processing of the element. These are called in postorder
  1639. * traversal, meaning they are called for the child elements first, then for
  1640. * the parent element.
  1641. * There are similar properties containing callback functions invoked by
  1642. * _form_validate() and drupal_render(), appropriate for those operations.
  1643. *
  1644. * Developers are strongly encouraged to integrate the functionality needed by
  1645. * their form or module within one of these three pipelines, using the
  1646. * appropriate callback property, rather than implementing their own recursive
  1647. * traversal of a form array. This facilitates proper integration between
  1648. * multiple modules. For example, module developers are familiar with the
  1649. * relative order in which hook_form_alter() implementations and #process
  1650. * functions run. A custom traversal function that affects the building of a
  1651. * form is likely to not integrate with hook_form_alter() and #process in the
  1652. * expected way. Also, deep recursion within PHP is both slow and memory
  1653. * intensive, so it is best to minimize how often it's done.
  1654. *
  1655. * As stated above, each element's #process functions are executed after its
  1656. * #value has been set. This enables those functions to execute conditional
  1657. * logic based on the current value. However, all of form_builder() runs before
  1658. * drupal_validate_form() is called, so during #process function execution, the
  1659. * element's #value has not yet been validated, so any code that requires
  1660. * validated values must reside within a submit handler.
  1661. *
  1662. * As a security measure, user input is used for an element's #value only if the
  1663. * element exists within $form, is not disabled (as per the #disabled property),
  1664. * and can be accessed (as per the #access property, except that forms submitted
  1665. * using drupal_form_submit() bypass #access restrictions). When user input is
  1666. * ignored due to #disabled and #access restrictions, the element's default
  1667. * value is used.
  1668. *
  1669. * Because of the preorder traversal, where #process functions of an element run
  1670. * before user input for its child elements is processed, and because of the
  1671. * Form API security of user input processing with respect to #access and
  1672. * #disabled described above, this generally means that #process functions
  1673. * should not use an element's (unvalidated) #value to affect the #disabled or
  1674. * #access of child elements. Use-cases where a developer may be tempted to
  1675. * implement such conditional logic usually fall into one of two categories:
  1676. * - Where user input from the current submission must affect the structure of a
  1677. * form, including properties like #access and #disabled that affect how the
  1678. * next submission needs to be processed, a multi-step workflow is needed.
  1679. * This is most commonly implemented with a submit handler setting persistent
  1680. * data within $form_state based on *validated* values in
  1681. * $form_state['values'] and setting $form_state['rebuild']. The form building
  1682. * functions must then be implemented to use the $form_state data to rebuild
  1683. * the form with the structure appropriate for the new state.
  1684. * - Where user input must affect the rendering of the form without affecting
  1685. * its structure, the necessary conditional rendering logic should reside
  1686. * within functions that run during the rendering phase (#pre_render, #theme,
  1687. * #theme_wrappers, and #post_render).
  1688. *
  1689. * @param $form_id
  1690. * A unique string identifying the form for validation, submission,
  1691. * theming, and hook_form_alter functions.
  1692. * @param $element
  1693. * An associative array containing the structure of the current element.
  1694. * @param $form_state
  1695. * A keyed array containing the current state of the form. In this
  1696. * context, it is used to accumulate information about which button
  1697. * was clicked when the form was submitted, as well as the sanitized
  1698. * $_POST data.
  1699. */
  1700. function form_builder($form_id, &$element, &$form_state) {
  1701. // Initialize as unprocessed.
  1702. $element['#processed'] = FALSE;
  1703. // Use element defaults.
  1704. if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
  1705. // Overlay $info onto $element, retaining preexisting keys in $element.
  1706. $element += $info;
  1707. $element['#defaults_loaded'] = TRUE;
  1708. }
  1709. // Assign basic defaults common for all form elements.
  1710. $element += array(
  1711. '#required' => FALSE,
  1712. '#attributes' => array(),
  1713. '#title_display' => 'before',
  1714. );
  1715. // Special handling if we're on the top level form element.
  1716. if (isset($element['#type']) && $element['#type'] == 'form') {
  1717. if (!empty($element['#https']) && variable_get('https', FALSE) &&
  1718. !url_is_external($element['#action'])) {
  1719. global $base_root;
  1720. // Not an external URL so ensure that it is secure.
  1721. $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
  1722. }
  1723. // Store a reference to the complete form in $form_state prior to building
  1724. // the form. This allows advanced #process and #after_build callbacks to
  1725. // perform changes elsewhere in the form.
  1726. $form_state['complete form'] = &$element;
  1727. // Set a flag if we have a correct form submission. This is always TRUE for
  1728. // programmed forms coming from drupal_form_submit(), or if the form_id coming
  1729. // from the POST data is set and matches the current form_id.
  1730. if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  1731. $form_state['process_input'] = TRUE;
  1732. // If the session token was set by drupal_prepare_form(), ensure that it
  1733. // matches the current user's session.
  1734. $form_state['invalid_token'] = FALSE;
  1735. if (isset($element['#token'])) {
  1736. if (empty($form_state['input']['form_token']) || !drupal_valid_token($form_state['input']['form_token'], $element['#token'])) {
  1737. // Set an early form error to block certain input processing since that
  1738. // opens the door for CSRF vulnerabilities.
  1739. _drupal_invalid_token_set_form_error();
  1740. // This value is checked in _form_builder_handle_input_element().
  1741. $form_state['invalid_token'] = TRUE;
  1742. // Make sure file uploads do not get processed.
  1743. $_FILES = array();
  1744. }
  1745. }
  1746. }
  1747. else {
  1748. $form_state['process_input'] = FALSE;
  1749. }
  1750. // All form elements should have an #array_parents property.
  1751. $element['#array_parents'] = array();
  1752. }
  1753. if (!isset($element['#id'])) {
  1754. $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
  1755. }
  1756. // Handle input elements.
  1757. if (!empty($element['#input'])) {
  1758. _form_builder_handle_input_element($form_id, $element, $form_state);
  1759. }
  1760. // Allow for elements to expand to multiple elements, e.g., radios,
  1761. // checkboxes and files.
  1762. if (isset($element['#process']) && !$element['#processed']) {
  1763. foreach ($element['#process'] as $process) {
  1764. $element = $process($element, $form_state, $form_state['complete form']);
  1765. }
  1766. $element['#processed'] = TRUE;
  1767. }
  1768. // We start off assuming all form elements are in the correct order.
  1769. $element['#sorted'] = TRUE;
  1770. // Recurse through all child elements.
  1771. $count = 0;
  1772. foreach (element_children($element) as $key) {
  1773. // Prior to checking properties of child elements, their default properties
  1774. // need to be loaded.
  1775. if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
  1776. $element[$key] += $info;
  1777. $element[$key]['#defaults_loaded'] = TRUE;
  1778. }
  1779. // Don't squash an existing tree value.
  1780. if (!isset($element[$key]['#tree'])) {
  1781. $element[$key]['#tree'] = $element['#tree'];
  1782. }
  1783. // Deny access to child elements if parent is denied.
  1784. if (isset($element['#access']) && !$element['#access']) {
  1785. $element[$key]['#access'] = FALSE;
  1786. }
  1787. // Make child elements inherit their parent's #disabled and #allow_focus
  1788. // values unless they specify their own.
  1789. foreach (array('#disabled', '#allow_focus') as $property) {
  1790. if (isset($element[$property]) && !isset($element[$key][$property])) {
  1791. $element[$key][$property] = $element[$property];
  1792. }
  1793. }
  1794. // Don't squash existing parents value.
  1795. if (!isset($element[$key]['#parents'])) {
  1796. // Check to see if a tree of child elements is present. If so,
  1797. // continue down the tree if required.
  1798. $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], array($key)) : array($key);
  1799. }
  1800. // Ensure #array_parents follows the actual form structure.
  1801. $array_parents = $element['#array_parents'];
  1802. $array_parents[] = $key;
  1803. $element[$key]['#array_parents'] = $array_parents;
  1804. // Assign a decimal placeholder weight to preserve original array order.
  1805. if (!isset($element[$key]['#weight'])) {
  1806. $element[$key]['#weight'] = $count/1000;
  1807. }
  1808. else {
  1809. // If one of the child elements has a weight then we will need to sort
  1810. // later.
  1811. unset($element['#sorted']);
  1812. }
  1813. $element[$key] = form_builder($form_id, $element[$key], $form_state);
  1814. $count++;
  1815. }
  1816. // The #after_build flag allows any piece of a form to be altered
  1817. // after normal input parsing has been completed.
  1818. if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
  1819. foreach ($element['#after_build'] as $function) {
  1820. $element = $function($element, $form_state);
  1821. }
  1822. $element['#after_build_done'] = TRUE;
  1823. }
  1824. // If there is a file element, we need to flip a flag so later the
  1825. // form encoding can be set.
  1826. if (isset($element['#type']) && $element['#type'] == 'file') {
  1827. $form_state['has_file_element'] = TRUE;
  1828. }
  1829. // Final tasks for the form element after form_builder() has run for all other
  1830. // elements.
  1831. if (isset($element['#type']) && $element['#type'] == 'form') {
  1832. // If there is a file element, we set the form encoding.
  1833. if (isset($form_state['has_file_element'])) {
  1834. $element['#attributes']['enctype'] = 'multipart/form-data';
  1835. }
  1836. // Allow Ajax submissions to the form action to bypass verification. This is
  1837. // especially useful for multipart forms, which cannot be verified via a
  1838. // response header.
  1839. $element['#attached']['js'][] = array(
  1840. 'type' => 'setting',
  1841. 'data' => array(
  1842. 'urlIsAjaxTrusted' => array(
  1843. $element['#action'] => TRUE,
  1844. ),
  1845. ),
  1846. );
  1847. // If a form contains a single textfield, and the ENTER key is pressed
  1848. // within it, Internet Explorer submits the form with no POST data
  1849. // identifying any submit button. Other browsers submit POST data as though
  1850. // the user clicked the first button. Therefore, to be as consistent as we
  1851. // can be across browsers, if no 'triggering_element' has been identified
  1852. // yet, default it to the first button.
  1853. if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
  1854. $form_state['triggering_element'] = $form_state['buttons'][0];
  1855. }
  1856. // If the triggering element specifies "button-level" validation and submit
  1857. // handlers to run instead of the default form-level ones, then add those to
  1858. // the form state.
  1859. foreach (array('validate', 'submit') as $type) {
  1860. if (isset($form_state['triggering_element']['#' . $type])) {
  1861. $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
  1862. }
  1863. }
  1864. // If the triggering element executes submit handlers, then set the form
  1865. // state key that's needed for those handlers to run.
  1866. if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
  1867. $form_state['submitted'] = TRUE;
  1868. }
  1869. // Special processing if the triggering element is a button.
  1870. if (isset($form_state['triggering_element']['#button_type'])) {
  1871. // Because there are several ways in which the triggering element could
  1872. // have been determined (including from input variables set by JavaScript
  1873. // or fallback behavior implemented for IE), and because buttons often
  1874. // have their #name property not derived from their #parents property, we
  1875. // can't assume that input processing that's happened up until here has
  1876. // resulted in $form_state['values'][BUTTON_NAME] being set. But it's
  1877. // common for forms to have several buttons named 'op' and switch on
  1878. // $form_state['values']['op'] during submit handler execution.
  1879. $form_state['values'][$form_state['triggering_element']['#name']] = $form_state['triggering_element']['#value'];
  1880. // @todo Legacy support. Remove in Drupal 8.
  1881. $form_state['clicked_button'] = $form_state['triggering_element'];
  1882. }
  1883. }
  1884. return $element;
  1885. }
  1886. /**
  1887. * Adds the #name and #value properties of an input element before rendering.
  1888. */
  1889. function _form_builder_handle_input_element($form_id, &$element, &$form_state) {
  1890. static $safe_core_value_callbacks = array(
  1891. 'form_type_token_value',
  1892. 'form_type_textarea_value',
  1893. 'form_type_textfield_value',
  1894. 'form_type_checkbox_value',
  1895. 'form_type_checkboxes_value',
  1896. 'form_type_radios_value',
  1897. 'form_type_password_confirm_value',
  1898. 'form_type_select_value',
  1899. 'form_type_tableselect_value',
  1900. 'list_boolean_allowed_values_callback',
  1901. );
  1902. if (!isset($element['#name'])) {
  1903. $name = array_shift($element['#parents']);
  1904. $element['#name'] = $name;
  1905. if ($element['#type'] == 'file') {
  1906. // To make it easier to handle $_FILES in file.inc, we place all
  1907. // file fields in the 'files' array. Also, we do not support
  1908. // nested file names.
  1909. $element['#name'] = 'files[' . $element['#name'] . ']';
  1910. }
  1911. elseif (count($element['#parents'])) {
  1912. $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
  1913. }
  1914. array_unshift($element['#parents'], $name);
  1915. }
  1916. // Setting #disabled to TRUE results in user input being ignored, regardless
  1917. // of how the element is themed or whether JavaScript is used to change the
  1918. // control's attributes. However, it's good UI to let the user know that input
  1919. // is not wanted for the control. HTML supports two attributes for this:
  1920. // http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form wants
  1921. // to start a control off with one of these attributes for UI purposes only,
  1922. // but still allow input to be processed if it's sumitted, it can set the
  1923. // desired attribute in #attributes directly rather than using #disabled.
  1924. // However, developers should think carefully about the accessibility
  1925. // implications of doing so: if the form expects input to be enterable under
  1926. // some condition triggered by JavaScript, how would someone who has
  1927. // JavaScript disabled trigger that condition? Instead, developers should
  1928. // consider whether a multi-step form would be more appropriate (#disabled can
  1929. // be changed from step to step). If one still decides to use JavaScript to
  1930. // affect when a control is enabled, then it is best for accessibility for the
  1931. // control to be enabled in the HTML, and disabled by JavaScript on document
  1932. // ready.
  1933. if (!empty($element['#disabled'])) {
  1934. if (!empty($element['#allow_focus'])) {
  1935. $element['#attributes']['readonly'] = 'readonly';
  1936. }
  1937. else {
  1938. $element['#attributes']['disabled'] = 'disabled';
  1939. }
  1940. }
  1941. // With JavaScript or other easy hacking, input can be submitted even for
  1942. // elements with #access=FALSE or #disabled=TRUE. For security, these must
  1943. // not be processed. Forms that set #disabled=TRUE on an element do not
  1944. // expect input for the element, and even forms submitted with
  1945. // drupal_form_submit() must not be able to get around this. Forms that set
  1946. // #access=FALSE on an element usually allow access for some users, so forms
  1947. // submitted with drupal_form_submit() may bypass access restriction and be
  1948. // treated as high-privilege users instead.
  1949. $process_input = empty($element['#disabled']) && (($form_state['programmed'] && $form_state['programmed_bypass_access_check']) || ($form_state['process_input'] && (!isset($element['#access']) || $element['#access'])));
  1950. // Set the element's #value property.
  1951. if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
  1952. $value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
  1953. if ($process_input) {
  1954. // Get the input for the current element. NULL values in the input need to
  1955. // be explicitly distinguished from missing input. (see below)
  1956. $input_exists = NULL;
  1957. $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
  1958. // For browser-submitted forms, the submitted values do not contain values
  1959. // for certain elements (empty multiple select, unchecked checkbox).
  1960. // During initial form processing, we add explicit NULL values for such
  1961. // elements in $form_state['input']. When rebuilding the form, we can
  1962. // distinguish elements having NULL input from elements that were not part
  1963. // of the initially submitted form and can therefore use default values
  1964. // for the latter, if required. Programmatically submitted forms can
  1965. // submit explicit NULL values when calling drupal_form_submit(), so we do
  1966. // not modify $form_state['input'] for them.
  1967. if (!$input_exists && !$form_state['rebuild'] && !$form_state['programmed']) {
  1968. // Add the necessary parent keys to $form_state['input'] and sets the
  1969. // element's input value to NULL.
  1970. drupal_array_set_nested_value($form_state['input'], $element['#parents'], NULL);
  1971. $input_exists = TRUE;
  1972. }
  1973. // If we have input for the current element, assign it to the #value
  1974. // property, optionally filtered through $value_callback.
  1975. if ($input_exists) {
  1976. if (function_exists($value_callback)) {
  1977. // Skip all value callbacks except safe ones like text if the CSRF
  1978. // token was invalid.
  1979. if (empty($form_state['invalid_token']) || in_array($value_callback, $safe_core_value_callbacks)) {
  1980. $element['#value'] = $value_callback($element, $input, $form_state);
  1981. }
  1982. else {
  1983. $input = NULL;
  1984. }
  1985. }
  1986. if (!isset($element['#value']) && isset($input)) {
  1987. $element['#value'] = $input;
  1988. }
  1989. }
  1990. // Mark all posted values for validation.
  1991. if (isset($element['#value']) || (!empty($element['#required']))) {
  1992. $element['#needs_validation'] = TRUE;
  1993. }
  1994. }
  1995. // Load defaults.
  1996. if (!isset($element['#value'])) {
  1997. // Call #type_value without a second argument to request default_value handling.
  1998. if (function_exists($value_callback)) {
  1999. $element['#value'] = $value_callback($element, FALSE, $form_state);
  2000. }
  2001. // Final catch. If we haven't set a value yet, use the explicit default value.
  2002. // Avoid image buttons (which come with garbage value), so we only get value
  2003. // for the button actually clicked.
  2004. if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
  2005. $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  2006. }
  2007. }
  2008. }
  2009. // Determine which element (if any) triggered the submission of the form and
  2010. // keep track of all the clickable buttons in the form for
  2011. // form_state_values_clean(). Enforce the same input processing restrictions
  2012. // as above.
  2013. if ($process_input) {
  2014. // Detect if the element triggered the submission via Ajax.
  2015. if (_form_element_triggered_scripted_submission($element, $form_state)) {
  2016. $form_state['triggering_element'] = $element;
  2017. }
  2018. // If the form was submitted by the browser rather than via Ajax, then it
  2019. // can only have been triggered by a button, and we need to determine which
  2020. // button within the constraints of how browsers provide this information.
  2021. if (isset($element['#button_type'])) {
  2022. // All buttons in the form need to be tracked for
  2023. // form_state_values_clean() and for the form_builder() code that handles
  2024. // a form submission containing no button information in $_POST.
  2025. $form_state['buttons'][] = $element;
  2026. if (_form_button_was_clicked($element, $form_state)) {
  2027. $form_state['triggering_element'] = $element;
  2028. }
  2029. }
  2030. }
  2031. // Set the element's value in $form_state['values'], but only, if its key
  2032. // does not exist yet (a #value_callback may have already populated it).
  2033. if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  2034. form_set_value($element, $element['#value'], $form_state);
  2035. }
  2036. }
  2037. /**
  2038. * Detects if an element triggered the form submission via Ajax.
  2039. *
  2040. * This detects button or non-button controls that trigger a form submission via
  2041. * Ajax or some other scriptable environment. These environments can set the
  2042. * special input key '_triggering_element_name' to identify the triggering
  2043. * element. If the name alone doesn't identify the element uniquely, the input
  2044. * key '_triggering_element_value' may also be set to require a match on element
  2045. * value. An example where this is needed is if there are several buttons all
  2046. * named 'op', and only differing in their value.
  2047. */
  2048. function _form_element_triggered_scripted_submission($element, &$form_state) {
  2049. if (!empty($form_state['input']['_triggering_element_name']) && $element['#name'] == $form_state['input']['_triggering_element_name']) {
  2050. if (empty($form_state['input']['_triggering_element_value']) || $form_state['input']['_triggering_element_value'] == $element['#value']) {
  2051. return TRUE;
  2052. }
  2053. }
  2054. return FALSE;
  2055. }
  2056. /**
  2057. * Determines if a given button triggered the form submission.
  2058. *
  2059. * This detects button controls that trigger a form submission by being clicked
  2060. * and having the click processed by the browser rather than being captured by
  2061. * JavaScript. Essentially, it detects if the button's name and value are part
  2062. * of the POST data, but with extra code to deal with the convoluted way in
  2063. * which browsers submit data for image button clicks.
  2064. *
  2065. * This does not detect button clicks processed by Ajax (that is done in
  2066. * _form_element_triggered_scripted_submission()) and it does not detect form
  2067. * submissions from Internet Explorer in response to an ENTER key pressed in a
  2068. * textfield (form_builder() has extra code for that).
  2069. *
  2070. * Because this function contains only part of the logic needed to determine
  2071. * $form_state['triggering_element'], it should not be called from anywhere
  2072. * other than within the Form API. Form validation and submit handlers needing
  2073. * to know which button was clicked should get that information from
  2074. * $form_state['triggering_element'].
  2075. */
  2076. function _form_button_was_clicked($element, &$form_state) {
  2077. // First detect normal 'vanilla' button clicks. Traditionally, all
  2078. // standard buttons on a form share the same name (usually 'op'),
  2079. // and the specific return value is used to determine which was
  2080. // clicked. This ONLY works as long as $form['#name'] puts the
  2081. // value at the top level of the tree of $_POST data.
  2082. if (isset($form_state['input'][$element['#name']]) && $form_state['input'][$element['#name']] == $element['#value']) {
  2083. return TRUE;
  2084. }
  2085. // When image buttons are clicked, browsers do NOT pass the form element
  2086. // value in $_POST. Instead they pass an integer representing the
  2087. // coordinates of the click on the button image. This means that image
  2088. // buttons MUST have unique $form['#name'] values, but the details of
  2089. // their $_POST data should be ignored.
  2090. elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
  2091. return TRUE;
  2092. }
  2093. return FALSE;
  2094. }
  2095. /**
  2096. * Removes internal Form API elements and buttons from submitted form values.
  2097. *
  2098. * This function can be used when a module wants to store all submitted form
  2099. * values, for example, by serializing them into a single database column. In
  2100. * such cases, all internal Form API values and all form button elements should
  2101. * not be contained, and this function allows to remove them before the module
  2102. * proceeds to storage. Next to button elements, the following internal values
  2103. * are removed:
  2104. * - form_id
  2105. * - form_token
  2106. * - form_build_id
  2107. * - op
  2108. *
  2109. * @param $form_state
  2110. * A keyed array containing the current state of the form, including
  2111. * submitted form values; altered by reference.
  2112. */
  2113. function form_state_values_clean(&$form_state) {
  2114. // Remove internal Form API values.
  2115. unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);
  2116. // Remove button values.
  2117. // form_builder() collects all button elements in a form. We remove the button
  2118. // value separately for each button element.
  2119. foreach ($form_state['buttons'] as $button) {
  2120. // Remove this button's value from the submitted form values by finding
  2121. // the value corresponding to this button.
  2122. // We iterate over the #parents of this button and move a reference to
  2123. // each parent in $form_state['values']. For example, if #parents is:
  2124. // array('foo', 'bar', 'baz')
  2125. // then the corresponding $form_state['values'] part will look like this:
  2126. // array(
  2127. // 'foo' => array(
  2128. // 'bar' => array(
  2129. // 'baz' => 'button_value',
  2130. // ),
  2131. // ),
  2132. // )
  2133. // We start by (re)moving 'baz' to $last_parent, so we are able unset it
  2134. // at the end of the iteration. Initially, $values will contain a
  2135. // reference to $form_state['values'], but in the iteration we move the
  2136. // reference to $form_state['values']['foo'], and finally to
  2137. // $form_state['values']['foo']['bar'], which is the level where we can
  2138. // unset 'baz' (that is stored in $last_parent).
  2139. $parents = $button['#parents'];
  2140. $last_parent = array_pop($parents);
  2141. $key_exists = NULL;
  2142. $values = &drupal_array_get_nested_value($form_state['values'], $parents, $key_exists);
  2143. if ($key_exists && is_array($values)) {
  2144. unset($values[$last_parent]);
  2145. }
  2146. }
  2147. }
  2148. /**
  2149. * Determines the value for an image button form element.
  2150. *
  2151. * @param $form
  2152. * The form element whose value is being populated.
  2153. * @param $input
  2154. * The incoming input to populate the form element. If this is FALSE,
  2155. * the element's default value should be returned.
  2156. * @param $form_state
  2157. * A keyed array containing the current state of the form.
  2158. *
  2159. * @return
  2160. * The data that will appear in the $form_state['values'] collection
  2161. * for this element. Return nothing to use the default.
  2162. */
  2163. function form_type_image_button_value($form, $input, $form_state) {
  2164. if ($input !== FALSE) {
  2165. if (!empty($input)) {
  2166. // If we're dealing with Mozilla or Opera, we're lucky. It will
  2167. // return a proper value, and we can get on with things.
  2168. return $form['#return_value'];
  2169. }
  2170. else {
  2171. // Unfortunately, in IE we never get back a proper value for THIS
  2172. // form element. Instead, we get back two split values: one for the
  2173. // X and one for the Y coordinates on which the user clicked the
  2174. // button. We'll find this element in the #post data, and search
  2175. // in the same spot for its name, with '_x'.
  2176. $input = $form_state['input'];
  2177. foreach (explode('[', $form['#name']) as $element_name) {
  2178. // chop off the ] that may exist.
  2179. if (substr($element_name, -1) == ']') {
  2180. $element_name = substr($element_name, 0, -1);
  2181. }
  2182. if (!isset($input[$element_name])) {
  2183. if (isset($input[$element_name . '_x'])) {
  2184. return $form['#return_value'];
  2185. }
  2186. return NULL;
  2187. }
  2188. $input = $input[$element_name];
  2189. }
  2190. return $form['#return_value'];
  2191. }
  2192. }
  2193. }
  2194. /**
  2195. * Determines the value for a checkbox form element.
  2196. *
  2197. * @param $form
  2198. * The form element whose value is being populated.
  2199. * @param $input
  2200. * The incoming input to populate the form element. If this is FALSE,
  2201. * the element's default value should be returned.
  2202. *
  2203. * @return
  2204. * The data that will appear in the $element_state['values'] collection
  2205. * for this element. Return nothing to use the default.
  2206. */
  2207. function form_type_checkbox_value($element, $input = FALSE) {
  2208. if ($input === FALSE) {
  2209. // Use #default_value as the default value of a checkbox, except change
  2210. // NULL to 0, because _form_builder_handle_input_element() would otherwise
  2211. // replace NULL with empty string, but an empty string is a potentially
  2212. // valid value for a checked checkbox.
  2213. return isset($element['#default_value']) ? $element['#default_value'] : 0;
  2214. }
  2215. else {
  2216. // Checked checkboxes are submitted with a value (possibly '0' or ''):
  2217. // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
  2218. // For checked checkboxes, browsers submit the string version of
  2219. // #return_value, but we return the original #return_value. For unchecked
  2220. // checkboxes, browsers submit nothing at all, but
  2221. // _form_builder_handle_input_element() detects this, and calls this
  2222. // function with $input=NULL. Returning NULL from a value callback means to
  2223. // use the default value, which is not what is wanted when an unchecked
  2224. // checkbox is submitted, so we use integer 0 as the value indicating an
  2225. // unchecked checkbox. Therefore, modules must not use integer 0 as a
  2226. // #return_value, as doing so results in the checkbox always being treated
  2227. // as unchecked. The string '0' is allowed for #return_value. The most
  2228. // common use-case for setting #return_value to either 0 or '0' is for the
  2229. // first option within a 0-indexed array of checkboxes, and for this,
  2230. // form_process_checkboxes() uses the string rather than the integer.
  2231. return isset($input) ? $element['#return_value'] : 0;
  2232. }
  2233. }
  2234. /**
  2235. * Determines the value for a checkboxes form element.
  2236. *
  2237. * @param $element
  2238. * The form element whose value is being populated.
  2239. * @param $input
  2240. * The incoming input to populate the form element. If this is FALSE,
  2241. * the element's default value should be returned.
  2242. *
  2243. * @return
  2244. * The data that will appear in the $element_state['values'] collection
  2245. * for this element. Return nothing to use the default.
  2246. */
  2247. function form_type_checkboxes_value($element, $input = FALSE) {
  2248. if ($input === FALSE) {
  2249. $value = array();
  2250. $element += array('#default_value' => array());
  2251. foreach ($element['#default_value'] as $key) {
  2252. $value[$key] = $key;
  2253. }
  2254. return $value;
  2255. }
  2256. elseif (is_array($input)) {
  2257. // Programmatic form submissions use NULL to indicate that a checkbox
  2258. // should be unchecked; see drupal_form_submit(). We therefore remove all
  2259. // NULL elements from the array before constructing the return value, to
  2260. // simulate the behavior of web browsers (which do not send unchecked
  2261. // checkboxes to the server at all). This will not affect non-programmatic
  2262. // form submissions, since all values in $_POST are strings.
  2263. foreach ($input as $key => $value) {
  2264. if (!isset($value)) {
  2265. unset($input[$key]);
  2266. }
  2267. }
  2268. return drupal_map_assoc($input);
  2269. }
  2270. else {
  2271. return array();
  2272. }
  2273. }
  2274. /**
  2275. * Determines the value for a tableselect form element.
  2276. *
  2277. * @param $element
  2278. * The form element whose value is being populated.
  2279. * @param $input
  2280. * The incoming input to populate the form element. If this is FALSE,
  2281. * the element's default value should be returned.
  2282. *
  2283. * @return
  2284. * The data that will appear in the $element_state['values'] collection
  2285. * for this element. Return nothing to use the default.
  2286. */
  2287. function form_type_tableselect_value($element, $input = FALSE) {
  2288. // If $element['#multiple'] == FALSE, then radio buttons are displayed and
  2289. // the default value handling is used.
  2290. if (isset($element['#multiple']) && $element['#multiple']) {
  2291. // Checkboxes are being displayed with the default value coming from the
  2292. // keys of the #default_value property. This differs from the checkboxes
  2293. // element which uses the array values.
  2294. if ($input === FALSE) {
  2295. $value = array();
  2296. $element += array('#default_value' => array());
  2297. foreach ($element['#default_value'] as $key => $flag) {
  2298. if ($flag) {
  2299. $value[$key] = $key;
  2300. }
  2301. }
  2302. return $value;
  2303. }
  2304. else {
  2305. return is_array($input) ? drupal_map_assoc($input) : array();
  2306. }
  2307. }
  2308. }
  2309. /**
  2310. * Form value callback: Determines the value for a #type radios form element.
  2311. *
  2312. * @param $element
  2313. * The form element whose value is being populated.
  2314. * @param $input
  2315. * (optional) The incoming input to populate the form element. If FALSE, the
  2316. * element's default value is returned. Defaults to FALSE.
  2317. *
  2318. * @return
  2319. * The data that will appear in the $element_state['values'] collection for
  2320. * this element.
  2321. */
  2322. function form_type_radios_value(&$element, $input = FALSE) {
  2323. if ($input !== FALSE) {
  2324. // When there's user input (including NULL), return it as the value.
  2325. // However, if NULL is submitted, _form_builder_handle_input_element() will
  2326. // apply the default value, and we want that validated against #options
  2327. // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
  2328. // be used to indicate that no radio button is selected by default.)
  2329. if (!isset($input) && !empty($element['#default_value'])) {
  2330. $element['#needs_validation'] = TRUE;
  2331. }
  2332. return $input;
  2333. }
  2334. else {
  2335. // For default value handling, simply return #default_value. Additionally,
  2336. // for a NULL default value, set #has_garbage_value to prevent
  2337. // _form_builder_handle_input_element() converting the NULL to an empty
  2338. // string, so that code can distinguish between nothing selected and the
  2339. // selection of a radio button whose value is an empty string.
  2340. $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
  2341. if (!isset($value)) {
  2342. $element['#has_garbage_value'] = TRUE;
  2343. }
  2344. return $value;
  2345. }
  2346. }
  2347. /**
  2348. * Determines the value for a password_confirm form element.
  2349. *
  2350. * @param $element
  2351. * The form element whose value is being populated.
  2352. * @param $input
  2353. * The incoming input to populate the form element. If this is FALSE,
  2354. * the element's default value should be returned.
  2355. *
  2356. * @return
  2357. * The data that will appear in the $element_state['values'] collection
  2358. * for this element. Return nothing to use the default.
  2359. */
  2360. function form_type_password_confirm_value($element, $input = FALSE) {
  2361. if ($input === FALSE) {
  2362. $element += array('#default_value' => array());
  2363. return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
  2364. }
  2365. $value = array('pass1' => '', 'pass2' => '');
  2366. // Throw out all invalid array keys; we only allow pass1 and pass2.
  2367. foreach ($value as $allowed_key => $default) {
  2368. // These should be strings, but allow other scalars since they might be
  2369. // valid input in programmatic form submissions. Any nested array values
  2370. // are ignored.
  2371. if (isset($input[$allowed_key]) && is_scalar($input[$allowed_key])) {
  2372. $value[$allowed_key] = (string) $input[$allowed_key];
  2373. }
  2374. }
  2375. return $value;
  2376. }
  2377. /**
  2378. * Determines the value for a select form element.
  2379. *
  2380. * @param $element
  2381. * The form element whose value is being populated.
  2382. * @param $input
  2383. * The incoming input to populate the form element. If this is FALSE,
  2384. * the element's default value should be returned.
  2385. *
  2386. * @return
  2387. * The data that will appear in the $element_state['values'] collection
  2388. * for this element. Return nothing to use the default.
  2389. */
  2390. function form_type_select_value($element, $input = FALSE) {
  2391. if ($input !== FALSE) {
  2392. if (isset($element['#multiple']) && $element['#multiple']) {
  2393. // If an enabled multi-select submits NULL, it means all items are
  2394. // unselected. A disabled multi-select always submits NULL, and the
  2395. // default value should be used.
  2396. if (empty($element['#disabled'])) {
  2397. return (is_array($input)) ? drupal_map_assoc($input) : array();
  2398. }
  2399. else {
  2400. return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
  2401. }
  2402. }
  2403. // Non-multiple select elements may have an empty option preprended to them
  2404. // (see form_process_select()). When this occurs, usually #empty_value is
  2405. // an empty string, but some forms set #empty_value to integer 0 or some
  2406. // other non-string constant. PHP receives all submitted form input as
  2407. // strings, but if the empty option is selected, set the value to match the
  2408. // empty value exactly.
  2409. elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
  2410. return $element['#empty_value'];
  2411. }
  2412. else {
  2413. return $input;
  2414. }
  2415. }
  2416. }
  2417. /**
  2418. * Determines the value for a textarea form element.
  2419. *
  2420. * @param array $element
  2421. * The form element whose value is being populated.
  2422. * @param mixed $input
  2423. * The incoming input to populate the form element. If this is FALSE,
  2424. * the element's default value should be returned.
  2425. *
  2426. * @return string
  2427. * The data that will appear in the $element_state['values'] collection
  2428. * for this element. Return nothing to use the default.
  2429. */
  2430. function form_type_textarea_value($element, $input = FALSE) {
  2431. if ($input !== FALSE) {
  2432. // This should be a string, but allow other scalars since they might be
  2433. // valid input in programmatic form submissions.
  2434. return is_scalar($input) ? (string) $input : '';
  2435. }
  2436. }
  2437. /**
  2438. * Determines the value for a textfield form element.
  2439. *
  2440. * @param $element
  2441. * The form element whose value is being populated.
  2442. * @param $input
  2443. * The incoming input to populate the form element. If this is FALSE,
  2444. * the element's default value should be returned.
  2445. *
  2446. * @return
  2447. * The data that will appear in the $element_state['values'] collection
  2448. * for this element. Return nothing to use the default.
  2449. */
  2450. function form_type_textfield_value($element, $input = FALSE) {
  2451. if ($input !== FALSE && $input !== NULL) {
  2452. // This should be a string, but allow other scalars since they might be
  2453. // valid input in programmatic form submissions.
  2454. if (!is_scalar($input)) {
  2455. $input = '';
  2456. }
  2457. return str_replace(array("\r", "\n"), '', (string) $input);
  2458. }
  2459. }
  2460. /**
  2461. * Determines the value for form's token value.
  2462. *
  2463. * @param $element
  2464. * The form element whose value is being populated.
  2465. * @param $input
  2466. * The incoming input to populate the form element. If this is FALSE,
  2467. * the element's default value should be returned.
  2468. *
  2469. * @return
  2470. * The data that will appear in the $element_state['values'] collection
  2471. * for this element. Return nothing to use the default.
  2472. */
  2473. function form_type_token_value($element, $input = FALSE) {
  2474. if ($input !== FALSE) {
  2475. return (string) $input;
  2476. }
  2477. }
  2478. /**
  2479. * Changes submitted form values during form validation.
  2480. *
  2481. * Use this function to change the submitted value of a form element in a form
  2482. * validation function, so that the changed value persists in $form_state
  2483. * through the remaining validation and submission handlers. It does not change
  2484. * the value in $element['#value'], only in $form_state['values'], which is
  2485. * where submitted values are always stored.
  2486. *
  2487. * Note that form validation functions are specified in the '#validate'
  2488. * component of the form array (the value of $form['#validate'] is an array of
  2489. * validation function names). If the form does not originate in your module,
  2490. * you can implement hook_form_FORM_ID_alter() to add a validation function
  2491. * to $form['#validate'].
  2492. *
  2493. * @param $element
  2494. * The form element that should have its value updated; in most cases you can
  2495. * just pass in the element from the $form array, although the only component
  2496. * that is actually used is '#parents'. If constructing yourself, set
  2497. * $element['#parents'] to be an array giving the path through the form
  2498. * array's keys to the element whose value you want to update. For instance,
  2499. * if you want to update the value of $form['elem1']['elem2'], which should be
  2500. * stored in $form_state['values']['elem1']['elem2'], you would set
  2501. * $element['#parents'] = array('elem1','elem2').
  2502. * @param $value
  2503. * The new value for the form element.
  2504. * @param $form_state
  2505. * Form state array where the value change should be recorded.
  2506. */
  2507. function form_set_value($element, $value, &$form_state) {
  2508. drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
  2509. }
  2510. /**
  2511. * Allows PHP array processing of multiple select options with the same value.
  2512. *
  2513. * Used for form select elements which need to validate HTML option groups
  2514. * and multiple options which may return the same value. Associative PHP arrays
  2515. * cannot handle these structures, since they share a common key.
  2516. *
  2517. * @param $array
  2518. * The form options array to process.
  2519. *
  2520. * @return
  2521. * An array with all hierarchical elements flattened to a single array.
  2522. */
  2523. function form_options_flatten($array) {
  2524. // Always reset static var when first entering the recursion.
  2525. drupal_static_reset('_form_options_flatten');
  2526. return _form_options_flatten($array);
  2527. }
  2528. /**
  2529. * Iterates over an array and returns a flat array with duplicate keys removed.
  2530. *
  2531. * This function also handles cases where objects are passed as array values.
  2532. */
  2533. function _form_options_flatten($array) {
  2534. $return = &drupal_static(__FUNCTION__);
  2535. foreach ($array as $key => $value) {
  2536. if (is_object($value)) {
  2537. _form_options_flatten($value->option);
  2538. }
  2539. elseif (is_array($value)) {
  2540. _form_options_flatten($value);
  2541. }
  2542. else {
  2543. $return[$key] = 1;
  2544. }
  2545. }
  2546. return $return;
  2547. }
  2548. /**
  2549. * Processes a select list form element.
  2550. *
  2551. * This process callback is mandatory for select fields, since all user agents
  2552. * automatically preselect the first available option of single (non-multiple)
  2553. * select lists.
  2554. *
  2555. * @param $element
  2556. * The form element to process. Properties used:
  2557. * - #multiple: (optional) Indicates whether one or more options can be
  2558. * selected. Defaults to FALSE.
  2559. * - #default_value: Must be NULL or not set in case there is no value for the
  2560. * element yet, in which case a first default option is inserted by default.
  2561. * Whether this first option is a valid option depends on whether the field
  2562. * is #required or not.
  2563. * - #required: (optional) Whether the user needs to select an option (TRUE)
  2564. * or not (FALSE). Defaults to FALSE.
  2565. * - #empty_option: (optional) The label to show for the first default option.
  2566. * By default, the label is automatically set to "- Select -" for a required
  2567. * field and "- None -" for an optional field.
  2568. * - #empty_value: (optional) The value for the first default option, which is
  2569. * used to determine whether the user submitted a value or not.
  2570. * - If #required is TRUE, this defaults to '' (an empty string).
  2571. * - If #required is not TRUE and this value isn't set, then no extra option
  2572. * is added to the select control, leaving the control in a slightly
  2573. * illogical state, because there's no way for the user to select nothing,
  2574. * since all user agents automatically preselect the first available
  2575. * option. But people are used to this being the behavior of select
  2576. * controls.
  2577. * @todo Address the above issue in Drupal 8.
  2578. * - If #required is not TRUE and this value is set (most commonly to an
  2579. * empty string), then an extra option (see #empty_option above)
  2580. * representing a "non-selection" is added with this as its value.
  2581. *
  2582. * @see _form_validate()
  2583. */
  2584. function form_process_select($element) {
  2585. // #multiple select fields need a special #name.
  2586. if ($element['#multiple']) {
  2587. $element['#attributes']['multiple'] = 'multiple';
  2588. $element['#attributes']['name'] = $element['#name'] . '[]';
  2589. }
  2590. // A non-#multiple select needs special handling to prevent user agents from
  2591. // preselecting the first option without intention. #multiple select lists do
  2592. // not get an empty option, as it would not make sense, user interface-wise.
  2593. else {
  2594. $required = $element['#required'];
  2595. // If the element is required and there is no #default_value, then add an
  2596. // empty option that will fail validation, so that the user is required to
  2597. // make a choice. Also, if there's a value for #empty_value or
  2598. // #empty_option, then add an option that represents emptiness.
  2599. if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  2600. $element += array(
  2601. '#empty_value' => '',
  2602. '#empty_option' => $required ? t('- Select -') : t('- None -'),
  2603. );
  2604. // The empty option is prepended to #options and purposively not merged
  2605. // to prevent another option in #options mistakenly using the same value
  2606. // as #empty_value.
  2607. $empty_option = array($element['#empty_value'] => $element['#empty_option']);
  2608. $element['#options'] = $empty_option + $element['#options'];
  2609. }
  2610. }
  2611. return $element;
  2612. }
  2613. /**
  2614. * Returns HTML for a select form element.
  2615. *
  2616. * It is possible to group options together; to do this, change the format of
  2617. * $options to an associative array in which the keys are group labels, and the
  2618. * values are associative arrays in the normal $options format.
  2619. *
  2620. * @param $variables
  2621. * An associative array containing:
  2622. * - element: An associative array containing the properties of the element.
  2623. * Properties used: #title, #value, #options, #description, #extra,
  2624. * #multiple, #required, #name, #attributes, #size.
  2625. *
  2626. * @ingroup themeable
  2627. */
  2628. function theme_select($variables) {
  2629. $element = $variables['element'];
  2630. element_set_attributes($element, array('id', 'name', 'size'));
  2631. _form_set_class($element, array('form-select'));
  2632. return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
  2633. }
  2634. /**
  2635. * Converts an array of options into HTML, for use in select list form elements.
  2636. *
  2637. * This function calls itself recursively to obtain the values for each optgroup
  2638. * within the list of options and when the function encounters an object with
  2639. * an 'options' property inside $element['#options'].
  2640. *
  2641. * @param array $element
  2642. * An associative array containing the following key-value pairs:
  2643. * - #multiple: Optional Boolean indicating if the user may select more than
  2644. * one item.
  2645. * - #options: An associative array of options to render as HTML. Each array
  2646. * value can be a string, an array, or an object with an 'option' property:
  2647. * - A string or integer key whose value is a translated string is
  2648. * interpreted as a single HTML option element. Do not use placeholders
  2649. * that sanitize data: doing so will lead to double-escaping. Note that
  2650. * the key will be visible in the HTML and could be modified by malicious
  2651. * users, so don't put sensitive information in it.
  2652. * - A translated string key whose value is an array indicates a group of
  2653. * options. The translated string is used as the label attribute for the
  2654. * optgroup. Do not use placeholders to sanitize data: doing so will lead
  2655. * to double-escaping. The array should contain the options you wish to
  2656. * group and should follow the syntax of $element['#options'].
  2657. * - If the function encounters a string or integer key whose value is an
  2658. * object with an 'option' property, the key is ignored, the contents of
  2659. * the option property are interpreted as $element['#options'], and the
  2660. * resulting HTML is added to the output.
  2661. * - #value: Optional integer, string, or array representing which option(s)
  2662. * to pre-select when the list is first displayed. The integer or string
  2663. * must match the key of an option in the '#options' list. If '#multiple' is
  2664. * TRUE, this can be an array of integers or strings.
  2665. * @param array|null $choices
  2666. * (optional) Either an associative array of options in the same format as
  2667. * $element['#options'] above, or NULL. This parameter is only used internally
  2668. * and is not intended to be passed in to the initial function call.
  2669. *
  2670. * @return string
  2671. * An HTML string of options and optgroups for use in a select form element.
  2672. */
  2673. function form_select_options($element, $choices = NULL) {
  2674. if (!isset($choices)) {
  2675. $choices = $element['#options'];
  2676. }
  2677. // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  2678. // isset() fails in this situation.
  2679. $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  2680. $value_is_array = $value_valid && is_array($element['#value']);
  2681. $options = '';
  2682. foreach ($choices as $key => $choice) {
  2683. if (is_array($choice)) {
  2684. $options .= '<optgroup label="' . check_plain($key) . '">';
  2685. $options .= form_select_options($element, $choice);
  2686. $options .= '</optgroup>';
  2687. }
  2688. elseif (is_object($choice)) {
  2689. $options .= form_select_options($element, $choice->option);
  2690. }
  2691. else {
  2692. $key = (string) $key;
  2693. if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
  2694. $selected = ' selected="selected"';
  2695. }
  2696. else {
  2697. $selected = '';
  2698. }
  2699. $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
  2700. }
  2701. }
  2702. return $options;
  2703. }
  2704. /**
  2705. * Returns the indexes of a select element's options matching a given key.
  2706. *
  2707. * This function is useful if you need to modify the options that are
  2708. * already in a form element; for example, to remove choices which are
  2709. * not valid because of additional filters imposed by another module.
  2710. * One example might be altering the choices in a taxonomy selector.
  2711. * To correctly handle the case of a multiple hierarchy taxonomy,
  2712. * #options arrays can now hold an array of objects, instead of a
  2713. * direct mapping of keys to labels, so that multiple choices in the
  2714. * selector can have the same key (and label). This makes it difficult
  2715. * to manipulate directly, which is why this helper function exists.
  2716. *
  2717. * This function does not support optgroups (when the elements of the
  2718. * #options array are themselves arrays), and will return FALSE if
  2719. * arrays are found. The caller must either flatten/restore or
  2720. * manually do their manipulations in this case, since returning the
  2721. * index is not sufficient, and supporting this would make the
  2722. * "helper" too complicated and cumbersome to be of any help.
  2723. *
  2724. * As usual with functions that can return array() or FALSE, do not
  2725. * forget to use === and !== if needed.
  2726. *
  2727. * @param $element
  2728. * The select element to search.
  2729. * @param $key
  2730. * The key to look for.
  2731. *
  2732. * @return
  2733. * An array of indexes that match the given $key. Array will be
  2734. * empty if no elements were found. FALSE if optgroups were found.
  2735. */
  2736. function form_get_options($element, $key) {
  2737. $keys = array();
  2738. foreach ($element['#options'] as $index => $choice) {
  2739. if (is_array($choice)) {
  2740. return FALSE;
  2741. }
  2742. elseif (is_object($choice)) {
  2743. if (isset($choice->option[$key])) {
  2744. $keys[] = $index;
  2745. }
  2746. }
  2747. elseif ($index == $key) {
  2748. $keys[] = $index;
  2749. }
  2750. }
  2751. return $keys;
  2752. }
  2753. /**
  2754. * Returns HTML for a fieldset form element and its children.
  2755. *
  2756. * @param $variables
  2757. * An associative array containing:
  2758. * - element: An associative array containing the properties of the element.
  2759. * Properties used: #attributes, #children, #collapsed, #collapsible,
  2760. * #description, #id, #title, #value.
  2761. *
  2762. * @ingroup themeable
  2763. */
  2764. function theme_fieldset($variables) {
  2765. $element = $variables['element'];
  2766. element_set_attributes($element, array('id'));
  2767. _form_set_class($element, array('form-wrapper'));
  2768. $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  2769. if (!empty($element['#title'])) {
  2770. // Always wrap fieldset legends in a SPAN for CSS positioning.
  2771. $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  2772. }
  2773. $output .= '<div class="fieldset-wrapper">';
  2774. if (!empty($element['#description'])) {
  2775. $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  2776. }
  2777. $output .= $element['#children'];
  2778. if (isset($element['#value'])) {
  2779. $output .= $element['#value'];
  2780. }
  2781. $output .= '</div>';
  2782. $output .= "</fieldset>\n";
  2783. return $output;
  2784. }
  2785. /**
  2786. * Returns HTML for a radio button form element.
  2787. *
  2788. * Note: The input "name" attribute needs to be sanitized before output, which
  2789. * is currently done by passing all attributes to drupal_attributes().
  2790. *
  2791. * @param $variables
  2792. * An associative array containing:
  2793. * - element: An associative array containing the properties of the element.
  2794. * Properties used: #required, #return_value, #value, #attributes, #title,
  2795. * #description
  2796. *
  2797. * @ingroup themeable
  2798. */
  2799. function theme_radio($variables) {
  2800. $element = $variables['element'];
  2801. $element['#attributes']['type'] = 'radio';
  2802. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  2803. if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
  2804. $element['#attributes']['checked'] = 'checked';
  2805. }
  2806. _form_set_class($element, array('form-radio'));
  2807. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  2808. }
  2809. /**
  2810. * Returns HTML for a set of radio button form elements.
  2811. *
  2812. * @param $variables
  2813. * An associative array containing:
  2814. * - element: An associative array containing the properties of the element.
  2815. * Properties used: #title, #value, #options, #description, #required,
  2816. * #attributes, #children.
  2817. *
  2818. * @ingroup themeable
  2819. */
  2820. function theme_radios($variables) {
  2821. $element = $variables['element'];
  2822. $attributes = array();
  2823. if (isset($element['#id'])) {
  2824. $attributes['id'] = $element['#id'];
  2825. }
  2826. $attributes['class'] = 'form-radios';
  2827. if (!empty($element['#attributes']['class'])) {
  2828. $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  2829. }
  2830. if (isset($element['#attributes']['title'])) {
  2831. $attributes['title'] = $element['#attributes']['title'];
  2832. }
  2833. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  2834. }
  2835. /**
  2836. * Expand a password_confirm field into two text boxes.
  2837. */
  2838. function form_process_password_confirm($element) {
  2839. $element['pass1'] = array(
  2840. '#type' => 'password',
  2841. '#title' => t('Password'),
  2842. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
  2843. '#required' => $element['#required'],
  2844. '#attributes' => array('class' => array('password-field')),
  2845. );
  2846. $element['pass2'] = array(
  2847. '#type' => 'password',
  2848. '#title' => t('Confirm password'),
  2849. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
  2850. '#required' => $element['#required'],
  2851. '#attributes' => array('class' => array('password-confirm')),
  2852. );
  2853. $element['#element_validate'] = array('password_confirm_validate');
  2854. $element['#tree'] = TRUE;
  2855. if (isset($element['#size'])) {
  2856. $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  2857. }
  2858. return $element;
  2859. }
  2860. /**
  2861. * Validates a password_confirm element.
  2862. */
  2863. function password_confirm_validate($element, &$element_state) {
  2864. $pass1 = trim($element['pass1']['#value']);
  2865. $pass2 = trim($element['pass2']['#value']);
  2866. if (!empty($pass1) || !empty($pass2)) {
  2867. if (strcmp($pass1, $pass2)) {
  2868. form_error($element, t('The specified passwords do not match.'));
  2869. }
  2870. }
  2871. elseif ($element['#required'] && !empty($element_state['input'])) {
  2872. form_error($element, t('Password field is required.'));
  2873. }
  2874. // Password field must be converted from a two-element array into a single
  2875. // string regardless of validation results.
  2876. form_set_value($element['pass1'], NULL, $element_state);
  2877. form_set_value($element['pass2'], NULL, $element_state);
  2878. form_set_value($element, $pass1, $element_state);
  2879. return $element;
  2880. }
  2881. /**
  2882. * Returns HTML for a date selection form element.
  2883. *
  2884. * @param $variables
  2885. * An associative array containing:
  2886. * - element: An associative array containing the properties of the element.
  2887. * Properties used: #title, #value, #options, #description, #required,
  2888. * #attributes.
  2889. *
  2890. * @ingroup themeable
  2891. */
  2892. function theme_date($variables) {
  2893. $element = $variables['element'];
  2894. $attributes = array();
  2895. if (isset($element['#id'])) {
  2896. $attributes['id'] = $element['#id'];
  2897. }
  2898. if (!empty($element['#attributes']['class'])) {
  2899. $attributes['class'] = (array) $element['#attributes']['class'];
  2900. }
  2901. $attributes['class'][] = 'container-inline';
  2902. return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
  2903. }
  2904. /**
  2905. * Expands a date element into year, month, and day select elements.
  2906. */
  2907. function form_process_date($element) {
  2908. // Default to current date
  2909. if (empty($element['#value'])) {
  2910. $element['#value'] = array(
  2911. 'day' => format_date(REQUEST_TIME, 'custom', 'j'),
  2912. 'month' => format_date(REQUEST_TIME, 'custom', 'n'),
  2913. 'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
  2914. );
  2915. }
  2916. $element['#tree'] = TRUE;
  2917. // Determine the order of day, month, year in the site's chosen date format.
  2918. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  2919. $sort = array();
  2920. $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
  2921. $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
  2922. $sort['year'] = strpos($format, 'Y');
  2923. asort($sort);
  2924. $order = array_keys($sort);
  2925. // Output multi-selector for date.
  2926. foreach ($order as $type) {
  2927. switch ($type) {
  2928. case 'day':
  2929. $options = drupal_map_assoc(range(1, 31));
  2930. $title = t('Day');
  2931. break;
  2932. case 'month':
  2933. $options = drupal_map_assoc(range(1, 12), 'map_month');
  2934. $title = t('Month');
  2935. break;
  2936. case 'year':
  2937. $options = drupal_map_assoc(range(1900, 2050));
  2938. $title = t('Year');
  2939. break;
  2940. }
  2941. $element[$type] = array(
  2942. '#type' => 'select',
  2943. '#title' => $title,
  2944. '#title_display' => 'invisible',
  2945. '#value' => $element['#value'][$type],
  2946. '#attributes' => $element['#attributes'],
  2947. '#options' => $options,
  2948. );
  2949. }
  2950. return $element;
  2951. }
  2952. /**
  2953. * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
  2954. */
  2955. function date_validate($element) {
  2956. if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
  2957. form_error($element, t('The specified date is invalid.'));
  2958. }
  2959. }
  2960. /**
  2961. * Helper function for usage with drupal_map_assoc to display month names.
  2962. */
  2963. function map_month($month) {
  2964. $months = &drupal_static(__FUNCTION__, array(
  2965. 1 => 'Jan',
  2966. 2 => 'Feb',
  2967. 3 => 'Mar',
  2968. 4 => 'Apr',
  2969. 5 => 'May',
  2970. 6 => 'Jun',
  2971. 7 => 'Jul',
  2972. 8 => 'Aug',
  2973. 9 => 'Sep',
  2974. 10 => 'Oct',
  2975. 11 => 'Nov',
  2976. 12 => 'Dec',
  2977. ));
  2978. return t($months[$month]);
  2979. }
  2980. /**
  2981. * Sets the value for a weight element, with zero as a default.
  2982. */
  2983. function weight_value(&$form) {
  2984. if (isset($form['#default_value'])) {
  2985. $form['#value'] = $form['#default_value'];
  2986. }
  2987. else {
  2988. $form['#value'] = 0;
  2989. }
  2990. }
  2991. /**
  2992. * Expands a radios element into individual radio elements.
  2993. */
  2994. function form_process_radios($element) {
  2995. if (count($element['#options']) > 0) {
  2996. $weight = 0;
  2997. foreach ($element['#options'] as $key => $choice) {
  2998. // Maintain order of options as defined in #options, in case the element
  2999. // defines custom option sub-elements, but does not define all option
  3000. // sub-elements.
  3001. $weight += 0.001;
  3002. $element += array($key => array());
  3003. // Generate the parents as the autogenerator does, so we will have a
  3004. // unique id for each radio button.
  3005. $parents_for_id = array_merge($element['#parents'], array($key));
  3006. $element[$key] += array(
  3007. '#type' => 'radio',
  3008. '#title' => $choice,
  3009. // The key is sanitized in drupal_attributes() during output from the
  3010. // theme function.
  3011. '#return_value' => $key,
  3012. // Use default or FALSE. A value of FALSE means that the radio button is
  3013. // not 'checked'.
  3014. '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
  3015. '#attributes' => $element['#attributes'],
  3016. '#parents' => $element['#parents'],
  3017. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  3018. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3019. '#weight' => $weight,
  3020. );
  3021. }
  3022. }
  3023. return $element;
  3024. }
  3025. /**
  3026. * Returns HTML for a checkbox form element.
  3027. *
  3028. * @param $variables
  3029. * An associative array containing:
  3030. * - element: An associative array containing the properties of the element.
  3031. * Properties used: #id, #name, #attributes, #checked, #return_value.
  3032. *
  3033. * @ingroup themeable
  3034. */
  3035. function theme_checkbox($variables) {
  3036. $element = $variables['element'];
  3037. $element['#attributes']['type'] = 'checkbox';
  3038. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  3039. // Unchecked checkbox has #value of integer 0.
  3040. if (!empty($element['#checked'])) {
  3041. $element['#attributes']['checked'] = 'checked';
  3042. }
  3043. _form_set_class($element, array('form-checkbox'));
  3044. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3045. }
  3046. /**
  3047. * Returns HTML for a set of checkbox form elements.
  3048. *
  3049. * @param $variables
  3050. * An associative array containing:
  3051. * - element: An associative array containing the properties of the element.
  3052. * Properties used: #children, #attributes.
  3053. *
  3054. * @ingroup themeable
  3055. */
  3056. function theme_checkboxes($variables) {
  3057. $element = $variables['element'];
  3058. $attributes = array();
  3059. if (isset($element['#id'])) {
  3060. $attributes['id'] = $element['#id'];
  3061. }
  3062. $attributes['class'][] = 'form-checkboxes';
  3063. if (!empty($element['#attributes']['class'])) {
  3064. $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  3065. }
  3066. if (isset($element['#attributes']['title'])) {
  3067. $attributes['title'] = $element['#attributes']['title'];
  3068. }
  3069. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  3070. }
  3071. /**
  3072. * Adds form element theming to an element if its title or description is set.
  3073. *
  3074. * This is used as a pre render function for checkboxes and radios.
  3075. */
  3076. function form_pre_render_conditional_form_element($element) {
  3077. $t = get_t();
  3078. // Set the element's title attribute to show #title as a tooltip, if needed.
  3079. if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
  3080. $element['#attributes']['title'] = $element['#title'];
  3081. if (!empty($element['#required'])) {
  3082. // Append an indication that this field is required.
  3083. $element['#attributes']['title'] .= ' (' . $t('Required') . ')';
  3084. }
  3085. }
  3086. if (isset($element['#title']) || isset($element['#description'])) {
  3087. $element['#theme_wrappers'][] = 'form_element';
  3088. }
  3089. return $element;
  3090. }
  3091. /**
  3092. * Sets the #checked property of a checkbox element.
  3093. */
  3094. function form_process_checkbox($element, $form_state) {
  3095. $value = $element['#value'];
  3096. $return_value = $element['#return_value'];
  3097. // On form submission, the #value of an available and enabled checked
  3098. // checkbox is #return_value, and the #value of an available and enabled
  3099. // unchecked checkbox is integer 0. On not submitted forms, and for
  3100. // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
  3101. // #default_value (integer 0 if #default_value is NULL). Most of the time,
  3102. // a string comparison of #value and #return_value is sufficient for
  3103. // determining the "checked" state, but a value of TRUE always means checked
  3104. // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
  3105. // means unchecked (even if #return_value is '' or '0').
  3106. if ($value === TRUE || $value === FALSE || $value === 0) {
  3107. $element['#checked'] = (bool) $value;
  3108. }
  3109. else {
  3110. // Compare as strings, so that 15 is not considered equal to '15foo', but 1
  3111. // is considered equal to '1'. This cast does not imply that either #value
  3112. // or #return_value is expected to be a string.
  3113. $element['#checked'] = ((string) $value === (string) $return_value);
  3114. }
  3115. return $element;
  3116. }
  3117. /**
  3118. * Processes a checkboxes form element.
  3119. */
  3120. function form_process_checkboxes($element) {
  3121. $value = is_array($element['#value']) ? $element['#value'] : array();
  3122. $element['#tree'] = TRUE;
  3123. if (count($element['#options']) > 0) {
  3124. if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
  3125. $element['#default_value'] = array();
  3126. }
  3127. $weight = 0;
  3128. foreach ($element['#options'] as $key => $choice) {
  3129. // Integer 0 is not a valid #return_value, so use '0' instead.
  3130. // @see form_type_checkbox_value().
  3131. // @todo For Drupal 8, cast all integer keys to strings for consistency
  3132. // with form_process_radios().
  3133. if ($key === 0) {
  3134. $key = '0';
  3135. }
  3136. // Maintain order of options as defined in #options, in case the element
  3137. // defines custom option sub-elements, but does not define all option
  3138. // sub-elements.
  3139. $weight += 0.001;
  3140. $element += array($key => array());
  3141. $element[$key] += array(
  3142. '#type' => 'checkbox',
  3143. '#title' => $choice,
  3144. '#return_value' => $key,
  3145. '#default_value' => isset($value[$key]) ? $key : NULL,
  3146. '#attributes' => $element['#attributes'],
  3147. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3148. '#weight' => $weight,
  3149. );
  3150. }
  3151. }
  3152. return $element;
  3153. }
  3154. /**
  3155. * Processes a form actions container element.
  3156. *
  3157. * @param $element
  3158. * An associative array containing the properties and children of the
  3159. * form actions container.
  3160. * @param $form_state
  3161. * The $form_state array for the form this element belongs to.
  3162. *
  3163. * @return
  3164. * The processed element.
  3165. */
  3166. function form_process_actions($element, &$form_state) {
  3167. $element['#attributes']['class'][] = 'form-actions';
  3168. return $element;
  3169. }
  3170. /**
  3171. * Processes a container element.
  3172. *
  3173. * @param $element
  3174. * An associative array containing the properties and children of the
  3175. * container.
  3176. * @param $form_state
  3177. * The $form_state array for the form this element belongs to.
  3178. *
  3179. * @return
  3180. * The processed element.
  3181. */
  3182. function form_process_container($element, &$form_state) {
  3183. // Generate the ID of the element if it's not explicitly given.
  3184. if (!isset($element['#id'])) {
  3185. $element['#id'] = drupal_html_id(implode('-', $element['#parents']) . '-wrapper');
  3186. }
  3187. return $element;
  3188. }
  3189. /**
  3190. * Returns HTML to wrap child elements in a container.
  3191. *
  3192. * Used for grouped form items. Can also be used as a theme wrapper for any
  3193. * renderable element, to surround it with a <div> and add attributes such as
  3194. * classes or an HTML ID.
  3195. *
  3196. * See the @link forms_api_reference.html Form API reference @endlink for more
  3197. * information on the #theme_wrappers render array property.
  3198. *
  3199. * @param $variables
  3200. * An associative array containing:
  3201. * - element: An associative array containing the properties of the element.
  3202. * Properties used: #id, #attributes, #children.
  3203. *
  3204. * @ingroup themeable
  3205. */
  3206. function theme_container($variables) {
  3207. $element = $variables['element'];
  3208. // Ensure #attributes is set.
  3209. $element += array('#attributes' => array());
  3210. // Special handling for form elements.
  3211. if (isset($element['#array_parents'])) {
  3212. // Assign an html ID.
  3213. if (!isset($element['#attributes']['id'])) {
  3214. $element['#attributes']['id'] = $element['#id'];
  3215. }
  3216. // Add the 'form-wrapper' class.
  3217. $element['#attributes']['class'][] = 'form-wrapper';
  3218. }
  3219. return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
  3220. }
  3221. /**
  3222. * Returns HTML for a table with radio buttons or checkboxes.
  3223. *
  3224. * @param $variables
  3225. * An associative array containing:
  3226. * - element: An associative array containing the properties and children of
  3227. * the tableselect element. Properties used: #header, #options, #empty,
  3228. * and #js_select. The #options property is an array of selection options;
  3229. * each array element of #options is an array of properties. These
  3230. * properties can include #attributes, which is added to the
  3231. * table row's HTML attributes; see theme_table(). An example of per-row
  3232. * options:
  3233. * @code
  3234. * $options = array(
  3235. * array(
  3236. * 'title' => 'How to Learn Drupal',
  3237. * 'content_type' => 'Article',
  3238. * 'status' => 'published',
  3239. * '#attributes' => array('class' => array('article-row')),
  3240. * ),
  3241. * array(
  3242. * 'title' => 'Privacy Policy',
  3243. * 'content_type' => 'Page',
  3244. * 'status' => 'published',
  3245. * '#attributes' => array('class' => array('page-row')),
  3246. * ),
  3247. * );
  3248. * $header = array(
  3249. * 'title' => t('Title'),
  3250. * 'content_type' => t('Content type'),
  3251. * 'status' => t('Status'),
  3252. * );
  3253. * $form['table'] = array(
  3254. * '#type' => 'tableselect',
  3255. * '#header' => $header,
  3256. * '#options' => $options,
  3257. * '#empty' => t('No content available.'),
  3258. * );
  3259. * @endcode
  3260. *
  3261. * @ingroup themeable
  3262. */
  3263. function theme_tableselect($variables) {
  3264. $element = $variables['element'];
  3265. $rows = array();
  3266. $header = $element['#header'];
  3267. if (!empty($element['#options'])) {
  3268. // Generate a table row for each selectable item in #options.
  3269. foreach (element_children($element) as $key) {
  3270. $row = array();
  3271. $row['data'] = array();
  3272. if (isset($element['#options'][$key]['#attributes'])) {
  3273. $row += $element['#options'][$key]['#attributes'];
  3274. }
  3275. // Render the checkbox / radio element.
  3276. $row['data'][] = drupal_render($element[$key]);
  3277. // As theme_table only maps header and row columns by order, create the
  3278. // correct order by iterating over the header fields.
  3279. foreach ($element['#header'] as $fieldname => $title) {
  3280. $row['data'][] = $element['#options'][$key][$fieldname];
  3281. }
  3282. $rows[] = $row;
  3283. }
  3284. // Add an empty header or a "Select all" checkbox to provide room for the
  3285. // checkboxes/radios in the first table column.
  3286. if ($element['#js_select']) {
  3287. // Add a "Select all" checkbox.
  3288. drupal_add_js('misc/tableselect.js');
  3289. array_unshift($header, array('class' => array('select-all')));
  3290. }
  3291. else {
  3292. // Add an empty header when radio buttons are displayed or a "Select all"
  3293. // checkbox is not desired.
  3294. array_unshift($header, '');
  3295. }
  3296. }
  3297. return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes']));
  3298. }
  3299. /**
  3300. * Creates checkbox or radio elements to populate a tableselect table.
  3301. *
  3302. * @param $element
  3303. * An associative array containing the properties and children of the
  3304. * tableselect element.
  3305. *
  3306. * @return
  3307. * The processed element.
  3308. */
  3309. function form_process_tableselect($element) {
  3310. if ($element['#multiple']) {
  3311. $value = is_array($element['#value']) ? $element['#value'] : array();
  3312. }
  3313. else {
  3314. // Advanced selection behavior makes no sense for radios.
  3315. $element['#js_select'] = FALSE;
  3316. }
  3317. $element['#tree'] = TRUE;
  3318. if (count($element['#options']) > 0) {
  3319. if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
  3320. $element['#default_value'] = array();
  3321. }
  3322. // Create a checkbox or radio for each item in #options in such a way that
  3323. // the value of the tableselect element behaves as if it had been of type
  3324. // checkboxes or radios.
  3325. foreach ($element['#options'] as $key => $choice) {
  3326. // Do not overwrite manually created children.
  3327. if (!isset($element[$key])) {
  3328. if ($element['#multiple']) {
  3329. $title = '';
  3330. if (!empty($element['#options'][$key]['title']['data']['#title'])) {
  3331. $title = t('Update @title', array(
  3332. '@title' => $element['#options'][$key]['title']['data']['#title'],
  3333. ));
  3334. }
  3335. $element[$key] = array(
  3336. '#type' => 'checkbox',
  3337. '#title' => $title,
  3338. '#title_display' => 'invisible',
  3339. '#return_value' => $key,
  3340. '#default_value' => isset($value[$key]) ? $key : NULL,
  3341. '#attributes' => $element['#attributes'],
  3342. );
  3343. }
  3344. else {
  3345. // Generate the parents as the autogenerator does, so we will have a
  3346. // unique id for each radio button.
  3347. $parents_for_id = array_merge($element['#parents'], array($key));
  3348. $element[$key] = array(
  3349. '#type' => 'radio',
  3350. '#title' => '',
  3351. '#return_value' => $key,
  3352. '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
  3353. '#attributes' => $element['#attributes'],
  3354. '#parents' => $element['#parents'],
  3355. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  3356. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3357. );
  3358. }
  3359. if (isset($element['#options'][$key]['#weight'])) {
  3360. $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
  3361. }
  3362. }
  3363. }
  3364. }
  3365. else {
  3366. $element['#value'] = array();
  3367. }
  3368. return $element;
  3369. }
  3370. /**
  3371. * Processes a machine-readable name form element.
  3372. *
  3373. * @param $element
  3374. * The form element to process. Properties used:
  3375. * - #machine_name: An associative array containing:
  3376. * - exists: A function name to invoke for checking whether a submitted
  3377. * machine name value already exists. The submitted value is passed as
  3378. * argument. In most cases, an existing API or menu argument loader
  3379. * function can be re-used. The callback is only invoked, if the submitted
  3380. * value differs from the element's #default_value.
  3381. * - source: (optional) The #array_parents of the form element containing
  3382. * the human-readable name (i.e., as contained in the $form structure) to
  3383. * use as source for the machine name. Defaults to array('name').
  3384. * - label: (optional) A text to display as label for the machine name value
  3385. * after the human-readable name form element. Defaults to "Machine name".
  3386. * - replace_pattern: (optional) A regular expression (without delimiters)
  3387. * matching disallowed characters in the machine name. Defaults to
  3388. * '[^a-z0-9_]+'.
  3389. * - replace: (optional) A character to replace disallowed characters in the
  3390. * machine name via JavaScript. Defaults to '_' (underscore). When using a
  3391. * different character, 'replace_pattern' needs to be set accordingly.
  3392. * - error: (optional) A custom form error message string to show, if the
  3393. * machine name contains disallowed characters.
  3394. * - standalone: (optional) Whether the live preview should stay in its own
  3395. * form element rather than in the suffix of the source element. Defaults
  3396. * to FALSE.
  3397. * - #maxlength: (optional) Should be set to the maximum allowed length of the
  3398. * machine name. Defaults to 64.
  3399. * - #disabled: (optional) Should be set to TRUE in case an existing machine
  3400. * name must not be changed after initial creation.
  3401. */
  3402. function form_process_machine_name($element, &$form_state) {
  3403. // Apply default form element properties.
  3404. $element += array(
  3405. '#title' => t('Machine-readable name'),
  3406. '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
  3407. '#machine_name' => array(),
  3408. '#field_prefix' => '',
  3409. '#field_suffix' => '',
  3410. '#suffix' => '',
  3411. );
  3412. // A form element that only wants to set one #machine_name property (usually
  3413. // 'source' only) would leave all other properties undefined, if the defaults
  3414. // were defined in hook_element_info(). Therefore, we apply the defaults here.
  3415. $element['#machine_name'] += array(
  3416. 'source' => array('name'),
  3417. 'target' => '#' . $element['#id'],
  3418. 'label' => t('Machine name'),
  3419. 'replace_pattern' => '[^a-z0-9_]+',
  3420. 'replace' => '_',
  3421. 'standalone' => FALSE,
  3422. 'field_prefix' => $element['#field_prefix'],
  3423. 'field_suffix' => $element['#field_suffix'],
  3424. );
  3425. // By default, machine names are restricted to Latin alphanumeric characters.
  3426. // So, default to LTR directionality.
  3427. if (!isset($element['#attributes'])) {
  3428. $element['#attributes'] = array();
  3429. }
  3430. $element['#attributes'] += array('dir' => 'ltr');
  3431. // The source element defaults to array('name'), but may have been overidden.
  3432. if (empty($element['#machine_name']['source'])) {
  3433. return $element;
  3434. }
  3435. // Retrieve the form element containing the human-readable name from the
  3436. // complete form in $form_state. By reference, because we may need to append
  3437. // a #field_suffix that will hold the live preview.
  3438. $key_exists = NULL;
  3439. $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
  3440. if (!$key_exists) {
  3441. return $element;
  3442. }
  3443. $suffix_id = $source['#id'] . '-machine-name-suffix';
  3444. $element['#machine_name']['suffix'] = '#' . $suffix_id;
  3445. if ($element['#machine_name']['standalone']) {
  3446. $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3447. }
  3448. else {
  3449. // Append a field suffix to the source form element, which will contain
  3450. // the live preview of the machine name.
  3451. $source += array('#field_suffix' => '');
  3452. $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3453. $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
  3454. drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
  3455. }
  3456. $js_settings = array(
  3457. 'type' => 'setting',
  3458. 'data' => array(
  3459. 'machineName' => array(
  3460. '#' . $source['#id'] => $element['#machine_name'],
  3461. ),
  3462. ),
  3463. );
  3464. $element['#attached']['js'][] = 'misc/machine-name.js';
  3465. $element['#attached']['js'][] = $js_settings;
  3466. return $element;
  3467. }
  3468. /**
  3469. * Form element validation handler for machine_name elements.
  3470. *
  3471. * Note that #maxlength is validated by _form_validate() already.
  3472. */
  3473. function form_validate_machine_name(&$element, &$form_state) {
  3474. // Verify that the machine name not only consists of replacement tokens.
  3475. if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
  3476. form_error($element, t('The machine-readable name must contain unique characters.'));
  3477. }
  3478. // Verify that the machine name contains no disallowed characters.
  3479. if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
  3480. if (!isset($element['#machine_name']['error'])) {
  3481. // Since a hyphen is the most common alternative replacement character,
  3482. // a corresponding validation error message is supported here.
  3483. if ($element['#machine_name']['replace'] == '-') {
  3484. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
  3485. }
  3486. // Otherwise, we assume the default (underscore).
  3487. else {
  3488. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
  3489. }
  3490. }
  3491. else {
  3492. form_error($element, $element['#machine_name']['error']);
  3493. }
  3494. }
  3495. // Verify that the machine name is unique.
  3496. if ($element['#default_value'] !== $element['#value']) {
  3497. $function = $element['#machine_name']['exists'];
  3498. if ($function($element['#value'], $element, $form_state)) {
  3499. form_error($element, t('The machine-readable name is already in use. It must be unique.'));
  3500. }
  3501. }
  3502. }
  3503. /**
  3504. * Arranges fieldsets into groups.
  3505. *
  3506. * @param $element
  3507. * An associative array containing the properties and children of the
  3508. * fieldset. Note that $element must be taken by reference here, so processed
  3509. * child elements are taken over into $form_state.
  3510. * @param $form_state
  3511. * The $form_state array for the form this fieldset belongs to.
  3512. *
  3513. * @return
  3514. * The processed element.
  3515. */
  3516. function form_process_fieldset(&$element, &$form_state) {
  3517. $parents = implode('][', $element['#parents']);
  3518. // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
  3519. // injects a new fieldset.
  3520. $form_state['groups'][$parents]['#group_exists'] = TRUE;
  3521. $element['#groups'] = &$form_state['groups'];
  3522. // Process vertical tabs group member fieldsets.
  3523. if (isset($element['#group'])) {
  3524. // Add this fieldset to the defined group (by reference).
  3525. $group = $element['#group'];
  3526. $form_state['groups'][$group][] = &$element;
  3527. }
  3528. // Contains form element summary functionalities.
  3529. $element['#attached']['library'][] = array('system', 'drupal.form');
  3530. // The .form-wrapper class is required for #states to treat fieldsets like
  3531. // containers.
  3532. if (!isset($element['#attributes']['class'])) {
  3533. $element['#attributes']['class'] = array();
  3534. }
  3535. // Collapsible fieldsets
  3536. if (!empty($element['#collapsible'])) {
  3537. $element['#attached']['library'][] = array('system', 'drupal.collapse');
  3538. $element['#attributes']['class'][] = 'collapsible';
  3539. if (!empty($element['#collapsed'])) {
  3540. $element['#attributes']['class'][] = 'collapsed';
  3541. }
  3542. }
  3543. return $element;
  3544. }
  3545. /**
  3546. * Adds members of this group as actual elements for rendering.
  3547. *
  3548. * @param $element
  3549. * An associative array containing the properties and children of the
  3550. * fieldset.
  3551. *
  3552. * @return
  3553. * The modified element with all group members.
  3554. */
  3555. function form_pre_render_fieldset($element) {
  3556. // Fieldsets may be rendered outside of a Form API context.
  3557. if (!isset($element['#parents']) || !isset($element['#groups'])) {
  3558. return $element;
  3559. }
  3560. // Inject group member elements belonging to this group.
  3561. $parents = implode('][', $element['#parents']);
  3562. $children = element_children($element['#groups'][$parents]);
  3563. if (!empty($children)) {
  3564. foreach ($children as $key) {
  3565. // Break references and indicate that the element should be rendered as
  3566. // group member.
  3567. $child = (array) $element['#groups'][$parents][$key];
  3568. $child['#group_fieldset'] = TRUE;
  3569. // Inject the element as new child element.
  3570. $element[] = $child;
  3571. $sort = TRUE;
  3572. }
  3573. // Re-sort the element's children if we injected group member elements.
  3574. if (isset($sort)) {
  3575. $element['#sorted'] = FALSE;
  3576. }
  3577. }
  3578. if (isset($element['#group'])) {
  3579. $group = $element['#group'];
  3580. // If this element belongs to a group, but the group-holding element does
  3581. // not exist, we need to render it (at its original location).
  3582. if (!isset($element['#groups'][$group]['#group_exists'])) {
  3583. // Intentionally empty to clarify the flow; we simply return $element.
  3584. }
  3585. // If we injected this element into the group, then we want to render it.
  3586. elseif (!empty($element['#group_fieldset'])) {
  3587. // Intentionally empty to clarify the flow; we simply return $element.
  3588. }
  3589. // Otherwise, this element belongs to a group and the group exists, so we do
  3590. // not render it.
  3591. elseif (element_children($element['#groups'][$group])) {
  3592. $element['#printed'] = TRUE;
  3593. }
  3594. }
  3595. return $element;
  3596. }
  3597. /**
  3598. * Creates a group formatted as vertical tabs.
  3599. *
  3600. * @param $element
  3601. * An associative array containing the properties and children of the
  3602. * fieldset.
  3603. * @param $form_state
  3604. * The $form_state array for the form this vertical tab widget belongs to.
  3605. *
  3606. * @return
  3607. * The processed element.
  3608. */
  3609. function form_process_vertical_tabs($element, &$form_state) {
  3610. // Inject a new fieldset as child, so that form_process_fieldset() processes
  3611. // this fieldset like any other fieldset.
  3612. $element['group'] = array(
  3613. '#type' => 'fieldset',
  3614. '#theme_wrappers' => array(),
  3615. '#parents' => $element['#parents'],
  3616. );
  3617. // The JavaScript stores the currently selected tab in this hidden
  3618. // field so that the active tab can be restored the next time the
  3619. // form is rendered, e.g. on preview pages or when form validation
  3620. // fails.
  3621. $name = implode('__', $element['#parents']);
  3622. if (isset($form_state['values'][$name . '__active_tab'])) {
  3623. $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
  3624. }
  3625. $element[$name . '__active_tab'] = array(
  3626. '#type' => 'hidden',
  3627. '#default_value' => $element['#default_tab'],
  3628. '#attributes' => array('class' => array('vertical-tabs-active-tab')),
  3629. );
  3630. return $element;
  3631. }
  3632. /**
  3633. * Returns HTML for an element's children fieldsets as vertical tabs.
  3634. *
  3635. * @param $variables
  3636. * An associative array containing:
  3637. * - element: An associative array containing the properties and children of
  3638. * the fieldset. Properties used: #children.
  3639. *
  3640. * @ingroup themeable
  3641. */
  3642. function theme_vertical_tabs($variables) {
  3643. $element = $variables['element'];
  3644. // Add required JavaScript and Stylesheet.
  3645. drupal_add_library('system', 'drupal.vertical-tabs');
  3646. $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
  3647. $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
  3648. return $output;
  3649. }
  3650. /**
  3651. * Returns HTML for a submit button form element.
  3652. *
  3653. * @param $variables
  3654. * An associative array containing:
  3655. * - element: An associative array containing the properties of the element.
  3656. * Properties used: #attributes, #button_type, #name, #value.
  3657. *
  3658. * @ingroup themeable
  3659. */
  3660. function theme_submit($variables) {
  3661. return theme('button', $variables['element']);
  3662. }
  3663. /**
  3664. * Returns HTML for a button form element.
  3665. *
  3666. * @param $variables
  3667. * An associative array containing:
  3668. * - element: An associative array containing the properties of the element.
  3669. * Properties used: #attributes, #button_type, #name, #value.
  3670. *
  3671. * @ingroup themeable
  3672. */
  3673. function theme_button($variables) {
  3674. $element = $variables['element'];
  3675. $element['#attributes']['type'] = 'submit';
  3676. element_set_attributes($element, array('id', 'name', 'value'));
  3677. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3678. if (!empty($element['#attributes']['disabled'])) {
  3679. $element['#attributes']['class'][] = 'form-button-disabled';
  3680. }
  3681. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3682. }
  3683. /**
  3684. * Returns HTML for an image button form element.
  3685. *
  3686. * @param $variables
  3687. * An associative array containing:
  3688. * - element: An associative array containing the properties of the element.
  3689. * Properties used: #attributes, #button_type, #name, #value, #title, #src.
  3690. *
  3691. * @ingroup themeable
  3692. */
  3693. function theme_image_button($variables) {
  3694. $element = $variables['element'];
  3695. $element['#attributes']['type'] = 'image';
  3696. element_set_attributes($element, array('id', 'name', 'value'));
  3697. $element['#attributes']['src'] = file_create_url($element['#src']);
  3698. if (!empty($element['#title'])) {
  3699. $element['#attributes']['alt'] = $element['#title'];
  3700. $element['#attributes']['title'] = $element['#title'];
  3701. }
  3702. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3703. if (!empty($element['#attributes']['disabled'])) {
  3704. $element['#attributes']['class'][] = 'form-button-disabled';
  3705. }
  3706. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3707. }
  3708. /**
  3709. * Returns HTML for a hidden form element.
  3710. *
  3711. * @param $variables
  3712. * An associative array containing:
  3713. * - element: An associative array containing the properties of the element.
  3714. * Properties used: #name, #value, #attributes.
  3715. *
  3716. * @ingroup themeable
  3717. */
  3718. function theme_hidden($variables) {
  3719. $element = $variables['element'];
  3720. $element['#attributes']['type'] = 'hidden';
  3721. element_set_attributes($element, array('name', 'value'));
  3722. return '<input' . drupal_attributes($element['#attributes']) . " />\n";
  3723. }
  3724. /**
  3725. * Process function to prepare autocomplete data.
  3726. *
  3727. * @param $element
  3728. * A textfield or other element with a #autocomplete_path.
  3729. *
  3730. * @return array
  3731. * The processed form element.
  3732. */
  3733. function form_process_autocomplete($element) {
  3734. $element['#autocomplete_input'] = array();
  3735. if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
  3736. $element['#autocomplete_input']['#id'] = $element['#id'] .'-autocomplete';
  3737. // Force autocomplete to use non-clean URLs since this protects against the
  3738. // browser interpreting the path plus search string as an actual file.
  3739. $current_clean_url = isset($GLOBALS['conf']['clean_url']) ? $GLOBALS['conf']['clean_url'] : NULL;
  3740. $GLOBALS['conf']['clean_url'] = 0;
  3741. // Force the script path to 'index.php', in case the server is not
  3742. // configured to find it automatically. Normally it is the responsibility
  3743. // of the site to do this themselves using hook_url_outbound_alter() (see
  3744. // url()) but since this code is forcing non-clean URLs on sites that don't
  3745. // normally use them, it is done here instead.
  3746. $element['#autocomplete_input']['#url_value'] = url($element['#autocomplete_path'], array('absolute' => TRUE, 'script' => 'index.php'));
  3747. $GLOBALS['conf']['clean_url'] = $current_clean_url;
  3748. }
  3749. return $element;
  3750. }
  3751. /**
  3752. * Returns HTML for a textfield form element.
  3753. *
  3754. * @param $variables
  3755. * An associative array containing:
  3756. * - element: An associative array containing the properties of the element.
  3757. * Properties used: #title, #value, #description, #size, #maxlength,
  3758. * #required, #attributes, #autocomplete_path.
  3759. *
  3760. * @ingroup themeable
  3761. */
  3762. function theme_textfield($variables) {
  3763. $element = $variables['element'];
  3764. $element['#attributes']['type'] = 'text';
  3765. element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  3766. _form_set_class($element, array('form-text'));
  3767. $extra = '';
  3768. if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
  3769. drupal_add_library('system', 'drupal.autocomplete');
  3770. $element['#attributes']['class'][] = 'form-autocomplete';
  3771. $attributes = array();
  3772. $attributes['type'] = 'hidden';
  3773. $attributes['id'] = $element['#autocomplete_input']['#id'];
  3774. $attributes['value'] = $element['#autocomplete_input']['#url_value'];
  3775. $attributes['disabled'] = 'disabled';
  3776. $attributes['class'][] = 'autocomplete';
  3777. $extra = '<input' . drupal_attributes($attributes) . ' />';
  3778. }
  3779. $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
  3780. return $output . $extra;
  3781. }
  3782. /**
  3783. * Returns HTML for a form.
  3784. *
  3785. * @param $variables
  3786. * An associative array containing:
  3787. * - element: An associative array containing the properties of the element.
  3788. * Properties used: #action, #method, #attributes, #children
  3789. *
  3790. * @ingroup themeable
  3791. */
  3792. function theme_form($variables) {
  3793. $element = $variables['element'];
  3794. if (isset($element['#action'])) {
  3795. $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  3796. }
  3797. element_set_attributes($element, array('method', 'id'));
  3798. if (empty($element['#attributes']['accept-charset'])) {
  3799. $element['#attributes']['accept-charset'] = "UTF-8";
  3800. }
  3801. // Anonymous DIV to satisfy XHTML compliance.
  3802. return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
  3803. }
  3804. /**
  3805. * Returns HTML for a textarea form element.
  3806. *
  3807. * @param $variables
  3808. * An associative array containing:
  3809. * - element: An associative array containing the properties of the element.
  3810. * Properties used: #title, #value, #description, #rows, #cols, #required,
  3811. * #attributes
  3812. *
  3813. * @ingroup themeable
  3814. */
  3815. function theme_textarea($variables) {
  3816. $element = $variables['element'];
  3817. element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  3818. _form_set_class($element, array('form-textarea'));
  3819. $wrapper_attributes = array(
  3820. 'class' => array('form-textarea-wrapper'),
  3821. );
  3822. // Add resizable behavior.
  3823. if (!empty($element['#resizable'])) {
  3824. drupal_add_library('system', 'drupal.textarea');
  3825. $wrapper_attributes['class'][] = 'resizable';
  3826. }
  3827. $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  3828. $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
  3829. $output .= '</div>';
  3830. return $output;
  3831. }
  3832. /**
  3833. * Returns HTML for a password form element.
  3834. *
  3835. * @param $variables
  3836. * An associative array containing:
  3837. * - element: An associative array containing the properties of the element.
  3838. * Properties used: #title, #value, #description, #size, #maxlength,
  3839. * #required, #attributes.
  3840. *
  3841. * @ingroup themeable
  3842. */
  3843. function theme_password($variables) {
  3844. $element = $variables['element'];
  3845. $element['#attributes']['type'] = 'password';
  3846. element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
  3847. _form_set_class($element, array('form-text'));
  3848. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3849. }
  3850. /**
  3851. * Expands a weight element into a select element.
  3852. */
  3853. function form_process_weight($element) {
  3854. $element['#is_weight'] = TRUE;
  3855. // If the number of options is small enough, use a select field.
  3856. $max_elements = variable_get('drupal_weight_select_max', DRUPAL_WEIGHT_SELECT_MAX);
  3857. if ($element['#delta'] <= $max_elements) {
  3858. $element['#type'] = 'select';
  3859. for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
  3860. $weights[$n] = $n;
  3861. }
  3862. $element['#options'] = $weights;
  3863. $element += element_info('select');
  3864. }
  3865. // Otherwise, use a text field.
  3866. else {
  3867. $element['#type'] = 'textfield';
  3868. // Use a field big enough to fit most weights.
  3869. $element['#size'] = 10;
  3870. $element['#element_validate'] = array('element_validate_integer');
  3871. $element += element_info('textfield');
  3872. }
  3873. return $element;
  3874. }
  3875. /**
  3876. * Returns HTML for a file upload form element.
  3877. *
  3878. * For assistance with handling the uploaded file correctly, see the API
  3879. * provided by file.inc.
  3880. *
  3881. * @param $variables
  3882. * An associative array containing:
  3883. * - element: An associative array containing the properties of the element.
  3884. * Properties used: #title, #name, #size, #description, #required,
  3885. * #attributes.
  3886. *
  3887. * @ingroup themeable
  3888. */
  3889. function theme_file($variables) {
  3890. $element = $variables['element'];
  3891. $element['#attributes']['type'] = 'file';
  3892. element_set_attributes($element, array('id', 'name', 'size'));
  3893. _form_set_class($element, array('form-file'));
  3894. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3895. }
  3896. /**
  3897. * Returns HTML for a form element.
  3898. *
  3899. * Each form element is wrapped in a DIV container having the following CSS
  3900. * classes:
  3901. * - form-item: Generic for all form elements.
  3902. * - form-type-#type: The internal element #type.
  3903. * - form-item-#name: The internal form element #name (usually derived from the
  3904. * $form structure and set via form_builder()).
  3905. * - form-disabled: Only set if the form element is #disabled.
  3906. *
  3907. * In addition to the element itself, the DIV contains a label for the element
  3908. * based on the optional #title_display property, and an optional #description.
  3909. *
  3910. * The optional #title_display property can have these values:
  3911. * - before: The label is output before the element. This is the default.
  3912. * The label includes the #title and the required marker, if #required.
  3913. * - after: The label is output after the element. For example, this is used
  3914. * for radio and checkbox #type elements as set in system_element_info().
  3915. * If the #title is empty but the field is #required, the label will
  3916. * contain only the required marker.
  3917. * - invisible: Labels are critical for screen readers to enable them to
  3918. * properly navigate through forms but can be visually distracting. This
  3919. * property hides the label for everyone except screen readers.
  3920. * - attribute: Set the title attribute on the element to create a tooltip
  3921. * but output no label element. This is supported only for checkboxes
  3922. * and radios in form_pre_render_conditional_form_element(). It is used
  3923. * where a visual label is not needed, such as a table of checkboxes where
  3924. * the row and column provide the context. The tooltip will include the
  3925. * title and required marker.
  3926. *
  3927. * If the #title property is not set, then the label and any required marker
  3928. * will not be output, regardless of the #title_display or #required values.
  3929. * This can be useful in cases such as the password_confirm element, which
  3930. * creates children elements that have their own labels and required markers,
  3931. * but the parent element should have neither. Use this carefully because a
  3932. * field without an associated label can cause accessibility challenges.
  3933. *
  3934. * @param $variables
  3935. * An associative array containing:
  3936. * - element: An associative array containing the properties of the element.
  3937. * Properties used: #title, #title_display, #description, #id, #required,
  3938. * #children, #type, #name.
  3939. *
  3940. * @ingroup themeable
  3941. */
  3942. function theme_form_element($variables) {
  3943. $element = &$variables['element'];
  3944. // This function is invoked as theme wrapper, but the rendered form element
  3945. // may not necessarily have been processed by form_builder().
  3946. $element += array(
  3947. '#title_display' => 'before',
  3948. );
  3949. // Add element #id for #type 'item'.
  3950. if (isset($element['#markup']) && !empty($element['#id'])) {
  3951. $attributes['id'] = $element['#id'];
  3952. }
  3953. // Add element's #type and #name as class to aid with JS/CSS selectors.
  3954. $attributes['class'] = array('form-item');
  3955. if (!empty($element['#type'])) {
  3956. $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  3957. }
  3958. if (!empty($element['#name'])) {
  3959. $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3960. }
  3961. // Add a class for disabled elements to facilitate cross-browser styling.
  3962. if (!empty($element['#attributes']['disabled'])) {
  3963. $attributes['class'][] = 'form-disabled';
  3964. }
  3965. $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  3966. // If #title is not set, we don't display any label or required marker.
  3967. if (!isset($element['#title'])) {
  3968. $element['#title_display'] = 'none';
  3969. }
  3970. $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
  3971. $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
  3972. switch ($element['#title_display']) {
  3973. case 'before':
  3974. case 'invisible':
  3975. $output .= ' ' . theme('form_element_label', $variables);
  3976. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3977. break;
  3978. case 'after':
  3979. $output .= ' ' . $prefix . $element['#children'] . $suffix;
  3980. $output .= ' ' . theme('form_element_label', $variables) . "\n";
  3981. break;
  3982. case 'none':
  3983. case 'attribute':
  3984. // Output no label and no required marker, only the children.
  3985. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3986. break;
  3987. }
  3988. if (!empty($element['#description'])) {
  3989. $output .= '<div class="description">' . $element['#description'] . "</div>\n";
  3990. }
  3991. $output .= "</div>\n";
  3992. return $output;
  3993. }
  3994. /**
  3995. * Returns HTML for a marker for required form elements.
  3996. *
  3997. * @param $variables
  3998. * An associative array containing:
  3999. * - element: An associative array containing the properties of the element.
  4000. *
  4001. * @ingroup themeable
  4002. */
  4003. function theme_form_required_marker($variables) {
  4004. // This is also used in the installer, pre-database setup.
  4005. $t = get_t();
  4006. $attributes = array(
  4007. 'class' => 'form-required',
  4008. 'title' => $t('This field is required.'),
  4009. );
  4010. return '<span' . drupal_attributes($attributes) . '>*</span>';
  4011. }
  4012. /**
  4013. * Returns HTML for a form element label and required marker.
  4014. *
  4015. * Form element labels include the #title and a #required marker. The label is
  4016. * associated with the element itself by the element #id. Labels may appear
  4017. * before or after elements, depending on theme_form_element() and
  4018. * #title_display.
  4019. *
  4020. * This function will not be called for elements with no labels, depending on
  4021. * #title_display. For elements that have an empty #title and are not required,
  4022. * this function will output no label (''). For required elements that have an
  4023. * empty #title, this will output the required marker alone within the label.
  4024. * The label will use the #id to associate the marker with the field that is
  4025. * required. That is especially important for screenreader users to know
  4026. * which field is required.
  4027. *
  4028. * @param $variables
  4029. * An associative array containing:
  4030. * - element: An associative array containing the properties of the element.
  4031. * Properties used: #required, #title, #id, #value, #description.
  4032. *
  4033. * @ingroup themeable
  4034. */
  4035. function theme_form_element_label($variables) {
  4036. $element = $variables['element'];
  4037. // This is also used in the installer, pre-database setup.
  4038. $t = get_t();
  4039. // If title and required marker are both empty, output no label.
  4040. if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
  4041. return '';
  4042. }
  4043. // If the element is required, a required marker is appended to the label.
  4044. $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
  4045. $title = filter_xss_admin($element['#title']);
  4046. $attributes = array();
  4047. // Style the label as class option to display inline with the element.
  4048. if ($element['#title_display'] == 'after') {
  4049. $attributes['class'] = 'option';
  4050. }
  4051. // Show label only to screen readers to avoid disruption in visual flows.
  4052. elseif ($element['#title_display'] == 'invisible') {
  4053. $attributes['class'] = 'element-invisible';
  4054. }
  4055. if (!empty($element['#id'])) {
  4056. $attributes['for'] = $element['#id'];
  4057. }
  4058. // The leading whitespace helps visually separate fields from inline labels.
  4059. return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
  4060. }
  4061. /**
  4062. * Sets a form element's class attribute.
  4063. *
  4064. * Adds 'required' and 'error' classes as needed.
  4065. *
  4066. * @param $element
  4067. * The form element.
  4068. * @param $name
  4069. * Array of new class names to be added.
  4070. */
  4071. function _form_set_class(&$element, $class = array()) {
  4072. if (!empty($class)) {
  4073. if (!isset($element['#attributes']['class'])) {
  4074. $element['#attributes']['class'] = array();
  4075. }
  4076. $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
  4077. }
  4078. // This function is invoked from form element theme functions, but the
  4079. // rendered form element may not necessarily have been processed by
  4080. // form_builder().
  4081. if (!empty($element['#required'])) {
  4082. $element['#attributes']['class'][] = 'required';
  4083. }
  4084. if (isset($element['#parents']) && form_get_error($element) !== NULL && !empty($element['#validated'])) {
  4085. $element['#attributes']['class'][] = 'error';
  4086. }
  4087. }
  4088. /**
  4089. * Form element validation handler for integer elements.
  4090. */
  4091. function element_validate_integer($element, &$form_state) {
  4092. $value = $element['#value'];
  4093. if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
  4094. form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
  4095. }
  4096. }
  4097. /**
  4098. * Form element validation handler for integer elements that must be positive.
  4099. */
  4100. function element_validate_integer_positive($element, &$form_state) {
  4101. $value = $element['#value'];
  4102. if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
  4103. form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  4104. }
  4105. }
  4106. /**
  4107. * Form element validation handler for number elements.
  4108. */
  4109. function element_validate_number($element, &$form_state) {
  4110. $value = $element['#value'];
  4111. if ($value != '' && !is_numeric($value)) {
  4112. form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
  4113. }
  4114. }
  4115. /**
  4116. * @} End of "defgroup form_api".
  4117. */
  4118. /**
  4119. * @defgroup batch Batch operations
  4120. * @{
  4121. * Creates and processes batch operations.
  4122. *
  4123. * Functions allowing forms processing to be spread out over several page
  4124. * requests, thus ensuring that the processing does not get interrupted
  4125. * because of a PHP timeout, while allowing the user to receive feedback
  4126. * on the progress of the ongoing operations.
  4127. *
  4128. * The API is primarily designed to integrate nicely with the Form API
  4129. * workflow, but can also be used by non-Form API scripts (like update.php)
  4130. * or even simple page callbacks (which should probably be used sparingly).
  4131. *
  4132. * Example:
  4133. * @code
  4134. * $batch = array(
  4135. * 'title' => t('Exporting'),
  4136. * 'operations' => array(
  4137. * array('my_function_1', array($account->uid, 'story')),
  4138. * array('my_function_2', array()),
  4139. * ),
  4140. * 'finished' => 'my_finished_callback',
  4141. * 'file' => 'path_to_file_containing_myfunctions',
  4142. * );
  4143. * batch_set($batch);
  4144. * // Only needed if not inside a form _submit handler.
  4145. * // Setting redirect in batch_process.
  4146. * batch_process('node/1');
  4147. * @endcode
  4148. *
  4149. * Note: if the batch 'title', 'init_message', 'progress_message', or
  4150. * 'error_message' could contain any user input, it is the responsibility of
  4151. * the code calling batch_set() to sanitize them first with a function like
  4152. * check_plain() or filter_xss(). Furthermore, if the batch operation
  4153. * returns any user input in the 'results' or 'message' keys of $context,
  4154. * it must also sanitize them first.
  4155. *
  4156. * Sample callback_batch_operation():
  4157. * @code
  4158. * // Simple and artificial: load a node of a given type for a given user
  4159. * function my_function_1($uid, $type, &$context) {
  4160. * // The $context array gathers batch context information about the execution (read),
  4161. * // as well as 'return values' for the current operation (write)
  4162. * // The following keys are provided :
  4163. * // 'results' (read / write): The array of results gathered so far by
  4164. * // the batch processing, for the current operation to append its own.
  4165. * // 'message' (write): A text message displayed in the progress page.
  4166. * // The following keys allow for multi-step operations :
  4167. * // 'sandbox' (read / write): An array that can be freely used to
  4168. * // store persistent data between iterations. It is recommended to
  4169. * // use this instead of $_SESSION, which is unsafe if the user
  4170. * // continues browsing in a separate window while the batch is processing.
  4171. * // 'finished' (write): A float number between 0 and 1 informing
  4172. * // the processing engine of the completion level for the operation.
  4173. * // 1 (or no value explicitly set) means the operation is finished
  4174. * // and the batch processing can continue to the next operation.
  4175. *
  4176. * $node = node_load(array('uid' => $uid, 'type' => $type));
  4177. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  4178. * $context['message'] = check_plain($node->title);
  4179. * }
  4180. *
  4181. * // More advanced example: multi-step operation - load all nodes, five by five
  4182. * function my_function_2(&$context) {
  4183. * if (empty($context['sandbox'])) {
  4184. * $context['sandbox']['progress'] = 0;
  4185. * $context['sandbox']['current_node'] = 0;
  4186. * $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  4187. * }
  4188. * $limit = 5;
  4189. * $result = db_select('node')
  4190. * ->fields('node', array('nid'))
  4191. * ->condition('nid', $context['sandbox']['current_node'], '>')
  4192. * ->orderBy('nid')
  4193. * ->range(0, $limit)
  4194. * ->execute();
  4195. * foreach ($result as $row) {
  4196. * $node = node_load($row->nid, NULL, TRUE);
  4197. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  4198. * $context['sandbox']['progress']++;
  4199. * $context['sandbox']['current_node'] = $node->nid;
  4200. * $context['message'] = check_plain($node->title);
  4201. * }
  4202. * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  4203. * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  4204. * }
  4205. * }
  4206. * @endcode
  4207. *
  4208. * Sample callback_batch_finished():
  4209. * @code
  4210. * function my_finished_callback($success, $results, $operations) {
  4211. * // The 'success' parameter means no fatal PHP errors were detected. All
  4212. * // other error management should be handled using 'results'.
  4213. * if ($success) {
  4214. * $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  4215. * }
  4216. * else {
  4217. * $message = t('Finished with an error.');
  4218. * }
  4219. * drupal_set_message($message);
  4220. * // Providing data for the redirected page is done through $_SESSION.
  4221. * foreach ($results as $result) {
  4222. * $items[] = t('Loaded node %title.', array('%title' => $result));
  4223. * }
  4224. * $_SESSION['my_batch_results'] = $items;
  4225. * }
  4226. * @endcode
  4227. */
  4228. /**
  4229. * Adds a new batch.
  4230. *
  4231. * Batch operations are added as new batch sets. Batch sets are used to spread
  4232. * processing (primarily, but not exclusively, forms processing) over several
  4233. * page requests. This helps to ensure that the processing is not interrupted
  4234. * due to PHP timeouts, while users are still able to receive feedback on the
  4235. * progress of the ongoing operations. Combining related operations into
  4236. * distinct batch sets provides clean code independence for each batch set,
  4237. * ensuring that two or more batches, submitted independently, can be processed
  4238. * without mutual interference. Each batch set may specify its own set of
  4239. * operations and results, produce its own UI messages, and trigger its own
  4240. * 'finished' callback. Batch sets are processed sequentially, with the progress
  4241. * bar starting afresh for each new set.
  4242. *
  4243. * @param $batch_definition
  4244. * An associative array defining the batch, with the following elements (all
  4245. * are optional except as noted):
  4246. * - operations: (required) Array of operations to be performed, where each
  4247. * item is an array consisting of the name of an implementation of
  4248. * callback_batch_operation() and an array of parameter.
  4249. * Example:
  4250. * @code
  4251. * array(
  4252. * array('callback_batch_operation_1', array($arg1)),
  4253. * array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
  4254. * )
  4255. * @endcode
  4256. * - title: A safe, translated string to use as the title for the progress
  4257. * page. Defaults to t('Processing').
  4258. * - init_message: Message displayed while the processing is initialized.
  4259. * Defaults to t('Initializing.').
  4260. * - progress_message: Message displayed while processing the batch. Available
  4261. * placeholders are @current, @remaining, @total, @percentage, @estimate and
  4262. * @elapsed. Defaults to t('Completed @current of @total.').
  4263. * - error_message: Message displayed if an error occurred while processing
  4264. * the batch. Defaults to t('An error has occurred.').
  4265. * - finished: Name of an implementation of callback_batch_finished(). This is
  4266. * executed after the batch has completed. This should be used to perform
  4267. * any result massaging that may be needed, and possibly save data in
  4268. * $_SESSION for display after final page redirection.
  4269. * - file: Path to the file containing the definitions of the 'operations' and
  4270. * 'finished' functions, for instance if they don't reside in the main
  4271. * .module file. The path should be relative to base_path(), and thus should
  4272. * be built using drupal_get_path().
  4273. * - css: Array of paths to CSS files to be used on the progress page.
  4274. * - url_options: options passed to url() when constructing redirect URLs for
  4275. * the batch.
  4276. */
  4277. function batch_set($batch_definition) {
  4278. if ($batch_definition) {
  4279. $batch =& batch_get();
  4280. // Initialize the batch if needed.
  4281. if (empty($batch)) {
  4282. $batch = array(
  4283. 'sets' => array(),
  4284. 'has_form_submits' => FALSE,
  4285. );
  4286. }
  4287. // Base and default properties for the batch set.
  4288. // Use get_t() to allow batches during installation.
  4289. $t = get_t();
  4290. $init = array(
  4291. 'sandbox' => array(),
  4292. 'results' => array(),
  4293. 'success' => FALSE,
  4294. 'start' => 0,
  4295. 'elapsed' => 0,
  4296. );
  4297. $defaults = array(
  4298. 'title' => $t('Processing'),
  4299. 'init_message' => $t('Initializing.'),
  4300. 'progress_message' => $t('Completed @current of @total.'),
  4301. 'error_message' => $t('An error has occurred.'),
  4302. 'css' => array(),
  4303. );
  4304. $batch_set = $init + $batch_definition + $defaults;
  4305. // Tweak init_message to avoid the bottom of the page flickering down after
  4306. // init phase.
  4307. $batch_set['init_message'] .= '<br/>&nbsp;';
  4308. // The non-concurrent workflow of batch execution allows us to save
  4309. // numberOfItems() queries by handling our own counter.
  4310. $batch_set['total'] = count($batch_set['operations']);
  4311. $batch_set['count'] = $batch_set['total'];
  4312. // Add the set to the batch.
  4313. if (empty($batch['id'])) {
  4314. // The batch is not running yet. Simply add the new set.
  4315. $batch['sets'][] = $batch_set;
  4316. }
  4317. else {
  4318. // The set is being added while the batch is running. Insert the new set
  4319. // right after the current one to ensure execution order, and store its
  4320. // operations in a queue.
  4321. $index = $batch['current_set'] + 1;
  4322. $slice1 = array_slice($batch['sets'], 0, $index);
  4323. $slice2 = array_slice($batch['sets'], $index);
  4324. $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
  4325. _batch_populate_queue($batch, $index);
  4326. }
  4327. }
  4328. }
  4329. /**
  4330. * Processes the batch.
  4331. *
  4332. * Unless the batch has been marked with 'progressive' = FALSE, the function
  4333. * issues a drupal_goto and thus ends page execution.
  4334. *
  4335. * This function is generally not needed in form submit handlers;
  4336. * Form API takes care of batches that were set during form submission.
  4337. *
  4338. * @param $redirect
  4339. * (optional) Path to redirect to when the batch has finished processing.
  4340. * @param $url
  4341. * (optional - should only be used for separate scripts like update.php)
  4342. * URL of the batch processing page.
  4343. * @param $redirect_callback
  4344. * (optional) Specify a function to be called to redirect to the progressive
  4345. * processing page. By default drupal_goto() will be used to redirect to a
  4346. * page which will do the progressive page. Specifying another function will
  4347. * allow the progressive processing to be processed differently.
  4348. */
  4349. function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = 'drupal_goto') {
  4350. $batch =& batch_get();
  4351. drupal_theme_initialize();
  4352. if (isset($batch)) {
  4353. // Add process information
  4354. $process_info = array(
  4355. 'current_set' => 0,
  4356. 'progressive' => TRUE,
  4357. 'url' => $url,
  4358. 'url_options' => array(),
  4359. 'source_url' => $_GET['q'],
  4360. 'redirect' => $redirect,
  4361. 'theme' => $GLOBALS['theme_key'],
  4362. 'redirect_callback' => $redirect_callback,
  4363. );
  4364. $batch += $process_info;
  4365. // The batch is now completely built. Allow other modules to make changes
  4366. // to the batch so that it is easier to reuse batch processes in other
  4367. // environments.
  4368. drupal_alter('batch', $batch);
  4369. // Assign an arbitrary id: don't rely on a serial column in the 'batch'
  4370. // table, since non-progressive batches skip database storage completely.
  4371. $batch['id'] = db_next_id();
  4372. // Move operations to a job queue. Non-progressive batches will use a
  4373. // memory-based queue.
  4374. foreach ($batch['sets'] as $key => $batch_set) {
  4375. _batch_populate_queue($batch, $key);
  4376. }
  4377. // Initiate processing.
  4378. if ($batch['progressive']) {
  4379. // Now that we have a batch id, we can generate the redirection link in
  4380. // the generic error message.
  4381. $t = get_t();
  4382. $batch['error_message'] = $t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
  4383. // Clear the way for the drupal_goto() redirection to the batch processing
  4384. // page, by saving and unsetting the 'destination', if there is any.
  4385. if (isset($_GET['destination'])) {
  4386. $batch['destination'] = $_GET['destination'];
  4387. unset($_GET['destination']);
  4388. }
  4389. // Store the batch.
  4390. db_insert('batch')
  4391. ->fields(array(
  4392. 'bid' => $batch['id'],
  4393. 'timestamp' => REQUEST_TIME,
  4394. 'token' => drupal_get_token($batch['id']),
  4395. 'batch' => serialize($batch),
  4396. ))
  4397. ->execute();
  4398. // Set the batch number in the session to guarantee that it will stay alive.
  4399. $_SESSION['batches'][$batch['id']] = TRUE;
  4400. // Redirect for processing.
  4401. $function = $batch['redirect_callback'];
  4402. if (function_exists($function)) {
  4403. $function($batch['url'], array('query' => array('op' => 'start', 'id' => $batch['id'])));
  4404. }
  4405. }
  4406. else {
  4407. // Non-progressive execution: bypass the whole progressbar workflow
  4408. // and execute the batch in one pass.
  4409. require_once DRUPAL_ROOT . '/includes/batch.inc';
  4410. _batch_process();
  4411. }
  4412. }
  4413. }
  4414. /**
  4415. * Retrieves the current batch.
  4416. */
  4417. function &batch_get() {
  4418. // Not drupal_static(), because Batch API operates at a lower level than most
  4419. // use-cases for resetting static variables, and we specifically do not want a
  4420. // global drupal_static_reset() resetting the batch information. Functions
  4421. // that are part of the Batch API and need to reset the batch information may
  4422. // call batch_get() and manipulate the result by reference. Functions that are
  4423. // not part of the Batch API can also do this, but shouldn't.
  4424. static $batch = array();
  4425. return $batch;
  4426. }
  4427. /**
  4428. * Populates a job queue with the operations of a batch set.
  4429. *
  4430. * Depending on whether the batch is progressive or not, the BatchQueue or
  4431. * BatchMemoryQueue handler classes will be used.
  4432. *
  4433. * @param $batch
  4434. * The batch array.
  4435. * @param $set_id
  4436. * The id of the set to process.
  4437. *
  4438. * @return
  4439. * The name and class of the queue are added by reference to the batch set.
  4440. */
  4441. function _batch_populate_queue(&$batch, $set_id) {
  4442. $batch_set = &$batch['sets'][$set_id];
  4443. if (isset($batch_set['operations'])) {
  4444. $batch_set += array(
  4445. 'queue' => array(
  4446. 'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
  4447. 'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
  4448. ),
  4449. );
  4450. $queue = _batch_queue($batch_set);
  4451. $queue->createQueue();
  4452. foreach ($batch_set['operations'] as $operation) {
  4453. $queue->createItem($operation);
  4454. }
  4455. unset($batch_set['operations']);
  4456. }
  4457. }
  4458. /**
  4459. * Returns a queue object for a batch set.
  4460. *
  4461. * @param $batch_set
  4462. * The batch set.
  4463. *
  4464. * @return
  4465. * The queue object.
  4466. */
  4467. function _batch_queue($batch_set) {
  4468. static $queues;
  4469. // The class autoloader is not available when running update.php, so make
  4470. // sure the files are manually included.
  4471. if (!isset($queues)) {
  4472. $queues = array();
  4473. require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
  4474. require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
  4475. }
  4476. if (isset($batch_set['queue'])) {
  4477. $name = $batch_set['queue']['name'];
  4478. $class = $batch_set['queue']['class'];
  4479. if (!isset($queues[$class][$name])) {
  4480. $queues[$class][$name] = new $class($name);
  4481. }
  4482. return $queues[$class][$name];
  4483. }
  4484. }
  4485. /**
  4486. * @} End of "defgroup batch".
  4487. */