form.inc 185 KB

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