form.inc 186 KB

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