form.inc 196 KB

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