form.inc 196 KB

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