form.inc 191 KB

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