webform.module 204 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573
  1. <?php
  2. /**
  3. * @file
  4. * This module provides a simple way to create forms and questionnaires.
  5. *
  6. * The initial development of this module was sponsored by ÅF Industry AB, Open
  7. * Source City and Karlstad University Library. Continued development sponsored
  8. * by Lullabot.
  9. *
  10. * @author Nathan Haug <nate@lullabot.com>
  11. */
  12. /**
  13. * Constants used in conditional logic.
  14. */
  15. define('WEBFORM_CONDITIONAL_EXCLUDE', 0);
  16. define('WEBFORM_CONDITIONAL_INCLUDE', 1);
  17. define('WEBFORM_CONDITIONAL_SAME_PAGE', 2);
  18. /**
  19. * Implements hook_help().
  20. */
  21. function webform_help($section = 'admin/help#webform', $arg = NULL) {
  22. $output = '';
  23. switch ($section) {
  24. case 'admin/config/content/webform':
  25. module_load_include('inc', 'webform', 'includes/webform.admin');
  26. $type_list = webform_admin_type_list();
  27. $output = t('Webform enables nodes to have attached forms and questionnaires.');
  28. if ($type_list) {
  29. $output .= ' ' . t('To add one, create a !types piece of content.', array('!types' => $type_list));
  30. }
  31. else {
  32. $output .= ' <strong>' . t('Webform is currently not enabled on any content types.') . '</strong> ' . t('To use Webform, please enable it on at least one <a href="!url">content type</a>.', array('!url' => url('admin/structure/types')));
  33. }
  34. $output = '<p>' . $output . '</p>';
  35. break;
  36. case 'admin/content/webform':
  37. $output = '<p>' . t('This page lists all of the content on the site that may have a webform attached to it.') . '</p>';
  38. break;
  39. case 'admin/help#webform':
  40. module_load_include('inc', 'webform', 'includes/webform.admin');
  41. $types = webform_admin_type_list();
  42. if (empty($types)) {
  43. $types = t('Webform-enabled piece of content');
  44. $types_message = t('Webform is currently not enabled on any content types.') . ' ' . t('Visit the <a href="!url">Webform settings</a> page and enable Webform on at least one content type.', array('!url' => url('admin/config/content/webform')));
  45. }
  46. else {
  47. $types_message = t('Optional: Enable Webform on multiple types by visiting the <a href="!url">Webform settings</a> page.', array('!url' => url('admin/config/content/webform')));
  48. }
  49. $output = t("<p>This module lets you create forms or questionnaires and define their content. Submissions from these forms are stored in the database and optionally also sent by e-mail to a predefined address.</p>
  50. <p>Here is how to create one:</p>
  51. <ul>
  52. <li>!webform-types-message</li>
  53. <li>Go to <a href=\"!create-content\">Create content</a> and add a !types piece of content.</li>
  54. <li>After saving the new content, you will be redirected to the main field list of the form that will be created. Add the fields you would like on your form.</li>
  55. <li>Once finished adding fields, you may want to send e-mails to administrators or back to the user who filled out the form. Click on the <em>Emails</em> sub-tab underneath the <em>Webform</em> tab on the piece of content.</li>
  56. <li>Finally, visit the <em>Form settings</em> sub-tab under the <em>Webform</em> tab to configure remaining configurations options for your form.
  57. <ul>
  58. <li>Add a confirmation message and/or redirect URL that is to be displayed after successful submission.</li>
  59. <li>Set a submission limit.</li>
  60. <li>Determine which roles may submit the form.</li>
  61. <li>Advanced configuration options such as allowing drafts or show users a message indicating how they can edit their submissions.</li>
  62. </ul>
  63. </li>
  64. <li>Your form is now ready for viewing. After receiving submissions, you can check the results users have submitted by visiting the <em>Results</em> tab on the piece of content.</li>
  65. </ul>
  66. <p>Help on adding and configuring the components will be shown after you add your first component.</p>
  67. ", array(
  68. '!webform-types-message' => $types_message,
  69. '!create-content' => url('node/add'),
  70. '!types' => $types,
  71. )
  72. );
  73. break;
  74. case 'node/%/webform/conditionals':
  75. $output .= '<p>' . t('Conditionals may be used to hide or show certain components (or entire pages!) based on the value of other components.') . '</p>';
  76. break;
  77. case 'node/%/submission/%/resend':
  78. $output .= '<p>' . t('This form may be used to resend e-mails configured for this webform. Check the e-mails that need to be sent and click <em>Resend e-mails</em> to send these e-mails again.') . '</p>';
  79. break;
  80. }
  81. return $output;
  82. }
  83. /**
  84. * Implements hook_menu().
  85. */
  86. function webform_menu() {
  87. $items = array();
  88. // Submissions listing.
  89. $items['admin/content/webform'] = array(
  90. 'title' => 'Webforms',
  91. 'page callback' => 'webform_admin_content',
  92. 'access callback' => 'user_access',
  93. 'access arguments' => array('access all webform results'),
  94. 'description' => 'View and edit all the available webforms on your site.',
  95. 'file' => 'includes/webform.admin.inc',
  96. 'type' => MENU_LOCAL_TASK,
  97. );
  98. // Admin Settings.
  99. $items['admin/config/content/webform'] = array(
  100. 'title' => 'Webform settings',
  101. 'page callback' => 'drupal_get_form',
  102. 'page arguments' => array('webform_admin_settings'),
  103. 'access callback' => 'user_access',
  104. 'access arguments' => array('administer site configuration'),
  105. 'description' => 'Global configuration of webform functionality.',
  106. 'file' => 'includes/webform.admin.inc',
  107. 'type' => MENU_NORMAL_ITEM,
  108. );
  109. // Autocomplete used in Views integration.
  110. $items['webform/autocomplete'] = array(
  111. 'title' => 'Webforms',
  112. 'page callback' => 'webform_views_autocomplete',
  113. 'access arguments' => array('administer views'),
  114. 'file' => 'views/webform.views.inc',
  115. 'type' => MENU_CALLBACK,
  116. );
  117. // Node page tabs.
  118. $items['node/%webform_menu/done'] = array(
  119. 'title' => 'Webform confirmation',
  120. 'page callback' => '_webform_confirmation',
  121. 'page arguments' => array(1),
  122. 'access callback' => 'webform_confirmation_page_access',
  123. 'access arguments' => array(1),
  124. 'type' => MENU_CALLBACK,
  125. );
  126. $items['node/%webform_menu/webform'] = array(
  127. 'title' => 'Webform',
  128. 'page callback' => 'webform_components_page',
  129. 'page arguments' => array(1),
  130. 'access callback' => 'webform_node_update_access',
  131. 'access arguments' => array(1),
  132. 'file' => 'includes/webform.components.inc',
  133. 'weight' => 1,
  134. 'type' => MENU_LOCAL_TASK,
  135. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  136. );
  137. $items['node/%webform_menu/webform/components'] = array(
  138. 'title' => 'Form components',
  139. 'page callback' => 'webform_components_page',
  140. 'page arguments' => array(1),
  141. 'access callback' => 'webform_node_update_access',
  142. 'access arguments' => array(1),
  143. 'file' => 'includes/webform.components.inc',
  144. 'weight' => 0,
  145. 'type' => MENU_DEFAULT_LOCAL_TASK,
  146. );
  147. $items['node/%webform_menu/webform/conditionals'] = array(
  148. 'title' => 'Conditionals',
  149. 'page callback' => 'drupal_get_form',
  150. 'page arguments' => array('webform_conditionals_form', 1),
  151. 'access callback' => 'webform_node_update_access',
  152. 'access arguments' => array(1),
  153. 'file' => 'includes/webform.conditionals.inc',
  154. 'weight' => 1,
  155. 'type' => MENU_LOCAL_TASK,
  156. );
  157. $items['node/%webform_menu/webform/configure'] = array(
  158. 'title' => 'Form settings',
  159. 'page callback' => 'drupal_get_form',
  160. 'page arguments' => array('webform_configure_form', 1),
  161. 'access callback' => 'webform_node_update_access',
  162. 'access arguments' => array(1),
  163. 'file' => 'includes/webform.pages.inc',
  164. 'weight' => 5,
  165. 'type' => MENU_LOCAL_TASK,
  166. );
  167. // Node e-mail forms.
  168. $items['node/%webform_menu/webform/emails'] = array(
  169. 'title' => 'E-mails',
  170. 'page callback' => 'drupal_get_form',
  171. 'page arguments' => array('webform_emails_form', 1),
  172. 'access callback' => 'webform_node_update_access',
  173. 'access arguments' => array(1),
  174. 'file' => 'includes/webform.emails.inc',
  175. 'weight' => 4,
  176. 'type' => MENU_LOCAL_TASK,
  177. );
  178. $items['node/%webform_menu/webform/emails/%webform_menu_email'] = array(
  179. 'load arguments' => array(1),
  180. 'page arguments' => array('webform_email_edit_form', 1, 4),
  181. 'access callback' => 'webform_node_update_access',
  182. 'access arguments' => array(1),
  183. 'file' => 'includes/webform.emails.inc',
  184. 'type' => MENU_LOCAL_TASK,
  185. );
  186. $items['node/%webform_menu/webform/emails/%webform_menu_email/clone'] = array(
  187. 'load arguments' => array(1),
  188. 'page arguments' => array('webform_email_edit_form', 1, 4, TRUE),
  189. 'access callback' => 'webform_node_update_access',
  190. 'access arguments' => array(1),
  191. 'file' => 'includes/webform.emails.inc',
  192. 'type' => MENU_LOCAL_TASK,
  193. );
  194. $items['node/%webform_menu/webform/emails/%webform_menu_email/delete'] = array(
  195. 'load arguments' => array(1),
  196. 'page arguments' => array('webform_email_delete_form', 1, 4),
  197. 'access callback' => 'webform_node_update_access',
  198. 'access arguments' => array(1),
  199. 'type' => MENU_LOCAL_TASK,
  200. );
  201. // Node component forms.
  202. $items['node/%webform_menu/webform/components/%webform_menu_component'] = array(
  203. 'load arguments' => array(1, 5),
  204. 'page callback' => 'drupal_get_form',
  205. 'page arguments' => array('webform_component_edit_form', 1, 4, FALSE),
  206. 'access callback' => 'webform_node_update_access',
  207. 'access arguments' => array(1),
  208. 'file' => 'includes/webform.components.inc',
  209. 'type' => MENU_LOCAL_TASK,
  210. );
  211. $items['node/%webform_menu/webform/components/%webform_menu_component/clone'] = array(
  212. 'load arguments' => array(1, 5),
  213. 'page callback' => 'drupal_get_form',
  214. 'page arguments' => array('webform_component_edit_form', 1, 4, TRUE),
  215. 'access callback' => 'webform_node_update_access',
  216. 'access arguments' => array(1),
  217. 'file' => 'includes/webform.components.inc',
  218. 'type' => MENU_LOCAL_TASK,
  219. );
  220. $items['node/%webform_menu/webform/components/%webform_menu_component/delete'] = array(
  221. 'load arguments' => array(1, 5),
  222. 'page callback' => 'drupal_get_form',
  223. 'page arguments' => array('webform_component_delete_form', 1, 4),
  224. 'access callback' => 'webform_node_update_access',
  225. 'access arguments' => array(1),
  226. 'file' => 'includes/webform.components.inc',
  227. 'type' => MENU_LOCAL_TASK,
  228. );
  229. // AJAX callback for loading select list options.
  230. $items['webform/ajax/options/%webform_menu'] = array(
  231. 'load arguments' => array(3),
  232. 'page callback' => 'webform_select_options_ajax',
  233. 'access callback' => 'webform_node_update_access',
  234. 'access arguments' => array(3),
  235. 'file' => 'components/select.inc',
  236. 'type' => MENU_CALLBACK,
  237. );
  238. // Node webform results.
  239. $items['node/%webform_menu/webform-results'] = array(
  240. 'title' => 'Results',
  241. 'page callback' => 'webform_results_submissions',
  242. 'page arguments' => array(1, FALSE, '50'),
  243. 'access callback' => 'webform_results_access',
  244. 'access arguments' => array(1),
  245. 'file' => 'includes/webform.report.inc',
  246. 'weight' => 2,
  247. 'type' => MENU_LOCAL_TASK,
  248. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  249. );
  250. $items['node/%webform_menu/webform-results/submissions'] = array(
  251. 'title' => 'Submissions',
  252. 'page callback' => 'webform_results_submissions',
  253. 'page arguments' => array(1, FALSE, '50'),
  254. 'access callback' => 'webform_results_access',
  255. 'access arguments' => array(1),
  256. 'file' => 'includes/webform.report.inc',
  257. 'weight' => 4,
  258. 'type' => MENU_DEFAULT_LOCAL_TASK,
  259. );
  260. $items['node/%webform_menu/webform-results/analysis'] = array(
  261. 'title' => 'Analysis',
  262. 'page callback' => 'webform_results_analysis',
  263. 'page arguments' => array(1),
  264. 'access callback' => 'webform_results_access',
  265. 'access arguments' => array(1),
  266. 'file' => 'includes/webform.report.inc',
  267. 'weight' => 5,
  268. 'type' => MENU_LOCAL_TASK,
  269. );
  270. $items['node/%webform_menu/webform-results/analysis/%webform_menu_component'] = array(
  271. 'title' => 'Analysis',
  272. 'load arguments' => array(1, 4),
  273. 'page callback' => 'webform_results_analysis',
  274. 'page arguments' => array(1, array(), 4),
  275. 'access callback' => 'webform_results_access',
  276. 'access arguments' => array(1),
  277. 'file' => 'includes/webform.report.inc',
  278. 'type' => MENU_LOCAL_TASK,
  279. );
  280. $items['node/%webform_menu/webform-results/analysis/%webform_menu_component/more'] = array(
  281. 'title' => 'In-depth analysis',
  282. 'type' => MENU_DEFAULT_LOCAL_TASK,
  283. );
  284. $items['node/%webform_menu/webform-results/table'] = array(
  285. 'title' => 'Table',
  286. 'page callback' => 'webform_results_table',
  287. 'page arguments' => array(1, '50'),
  288. 'access callback' => 'webform_results_access',
  289. 'access arguments' => array(1),
  290. 'file' => 'includes/webform.report.inc',
  291. 'weight' => 6,
  292. 'type' => MENU_LOCAL_TASK,
  293. );
  294. $items['node/%webform_menu/webform-results/download'] = array(
  295. 'title' => 'Download',
  296. 'page callback' => 'drupal_get_form',
  297. 'page arguments' => array('webform_results_download_form', 1),
  298. 'access callback' => 'webform_results_access',
  299. 'access arguments' => array(1),
  300. 'file' => 'includes/webform.report.inc',
  301. 'weight' => 7,
  302. 'type' => MENU_LOCAL_TASK,
  303. );
  304. $items['node/%webform_menu/webform-results/download-file'] = array(
  305. 'title' => 'Download',
  306. 'page callback' => 'webform_results_download_callback',
  307. 'page arguments' => array(1),
  308. 'access callback' => 'webform_results_access',
  309. 'access arguments' => array(1),
  310. 'file' => 'includes/webform.report.inc',
  311. 'type' => MENU_CALLBACK,
  312. );
  313. $items['node/%webform_menu/webform-results/clear'] = array(
  314. 'title' => 'Clear',
  315. 'page callback' => 'drupal_get_form',
  316. 'page arguments' => array('webform_results_clear_form', 1),
  317. 'access callback' => 'webform_results_clear_access',
  318. 'access arguments' => array(1),
  319. 'file' => 'includes/webform.report.inc',
  320. 'weight' => 8,
  321. 'type' => MENU_LOCAL_TASK,
  322. );
  323. // Node submissions.
  324. $items['node/%webform_menu/submissions'] = array(
  325. 'title' => 'Submissions',
  326. 'page callback' => 'webform_results_submissions',
  327. 'page arguments' => array(1, TRUE, '50'),
  328. 'access callback' => 'webform_submission_access',
  329. 'access arguments' => array(1, NULL, 'list'),
  330. 'file' => 'includes/webform.report.inc',
  331. 'type' => MENU_CALLBACK,
  332. );
  333. $items['node/%webform_menu/submission/%webform_menu_submission'] = array(
  334. 'title' => 'Webform submission',
  335. 'load arguments' => array(1),
  336. 'page callback' => 'webform_submission_page',
  337. 'page arguments' => array(1, 3, 'html'),
  338. 'title callback' => 'webform_submission_title',
  339. 'title arguments' => array(1, 3),
  340. 'access callback' => 'webform_submission_access',
  341. 'access arguments' => array(1, 3, 'view'),
  342. 'file' => 'includes/webform.submissions.inc',
  343. 'type' => MENU_CALLBACK,
  344. );
  345. $items['node/%webform_menu/submission/%webform_menu_submission/view'] = array(
  346. 'title' => 'View',
  347. 'load arguments' => array(1),
  348. 'page callback' => 'webform_submission_page',
  349. 'page arguments' => array(1, 3, 'html'),
  350. 'access callback' => 'webform_submission_access',
  351. 'access arguments' => array(1, 3, 'view'),
  352. 'weight' => 0,
  353. 'file' => 'includes/webform.submissions.inc',
  354. 'type' => MENU_DEFAULT_LOCAL_TASK,
  355. );
  356. $items['node/%webform_menu/submission/%webform_menu_submission/edit'] = array(
  357. 'title' => 'Edit',
  358. 'load arguments' => array(1),
  359. 'page callback' => 'webform_submission_page',
  360. 'page arguments' => array(1, 3, 'form'),
  361. 'access callback' => 'webform_submission_access',
  362. 'access arguments' => array(1, 3, 'edit'),
  363. 'weight' => 1,
  364. 'file' => 'includes/webform.submissions.inc',
  365. 'type' => MENU_LOCAL_TASK,
  366. );
  367. $items['node/%webform_menu/submission/%webform_menu_submission/delete'] = array(
  368. 'title' => 'Delete',
  369. 'load arguments' => array(1),
  370. 'page callback' => 'drupal_get_form',
  371. 'page arguments' => array('webform_submission_delete_form', 1, 3),
  372. 'access callback' => 'webform_submission_access',
  373. 'access arguments' => array(1, 3, 'delete'),
  374. 'weight' => 2,
  375. 'file' => 'includes/webform.submissions.inc',
  376. 'type' => MENU_LOCAL_TASK,
  377. );
  378. $items['node/%webform_menu/submission/%webform_menu_submission/resend'] = array(
  379. 'title' => 'Resend e-mails',
  380. 'load arguments' => array(1),
  381. 'page callback' => 'drupal_get_form',
  382. 'page arguments' => array('webform_submission_resend', 1, 3),
  383. 'access callback' => 'webform_results_access',
  384. 'access arguments' => array(1),
  385. 'file' => 'includes/webform.submissions.inc',
  386. 'type' => MENU_CALLBACK,
  387. );
  388. // Devel integration for submissions.
  389. if (module_exists('devel')) {
  390. $items['node/%webform_menu/submission/%webform_menu_submission/devel'] = array(
  391. 'title' => 'Devel',
  392. 'load arguments' => array(1),
  393. 'page callback' => 'devel_load_object',
  394. 'page arguments' => array('submission', 3),
  395. 'access arguments' => array('access devel information'),
  396. 'type' => MENU_LOCAL_TASK,
  397. 'file' => 'devel.pages.inc',
  398. 'file path' => drupal_get_path('module', 'devel'),
  399. 'weight' => 100,
  400. );
  401. $items['node/%webform_menu/submission/%webform_menu_submission/devel/load'] = array(
  402. 'title' => 'Load',
  403. 'type' => MENU_DEFAULT_LOCAL_TASK,
  404. );
  405. if (module_exists('token')) {
  406. $items['node/%webform_menu/submission/%webform_menu_submission/devel/token'] = array(
  407. 'title' => 'Tokens',
  408. 'load arguments' => array(1),
  409. 'page callback' => 'token_devel_token_object',
  410. 'page arguments' => array('webform-submission', 3, 'submission'),
  411. 'access arguments' => array('access devel information'),
  412. 'type' => MENU_LOCAL_TASK,
  413. 'file' => 'token.pages.inc',
  414. 'file path' => drupal_get_path('module', 'token'),
  415. 'weight' => 5,
  416. );
  417. }
  418. }
  419. return $items;
  420. }
  421. /**
  422. * Menu loader callback. Load a webform node if the given nid is a webform.
  423. */
  424. function webform_menu_load($nid) {
  425. if (!is_numeric($nid)) {
  426. return FALSE;
  427. }
  428. $node = node_load($nid);
  429. if (!isset($node->type) || !variable_get('webform_node_' . $node->type, FALSE)) {
  430. return FALSE;
  431. }
  432. return $node;
  433. }
  434. /**
  435. * Menu LOADERNAME_to_arg callback.
  436. *
  437. * Determines the arguments used to generate a menu link.
  438. *
  439. * This is implemented only to give the webform_localization modules an
  440. * opportunity to link to the orignial webform from the localized one. See
  441. * issue 2097277.
  442. *
  443. * @param string $arg
  444. * The argument supplied by the caller.
  445. * @param array $map
  446. * Array of path fragments (for example, array('node','123','edit') for
  447. * 'node/123/edit').
  448. * @param int $index
  449. * Which element of $map corresponds to $arg.
  450. *
  451. * @return string
  452. * The $arg, modified as desired.
  453. */
  454. function webform_menu_to_arg($arg, array $map, $index) {
  455. return function_exists('webform_localization_webform_menu_to_arg')
  456. ? webform_localization_webform_menu_to_arg($arg, $map, $index)
  457. : $arg;
  458. }
  459. /**
  460. * Menu loader callback. Load a webform submission if the given sid is a valid.
  461. */
  462. function webform_menu_submission_load($sid, $nid) {
  463. module_load_include('inc', 'webform', 'includes/webform.submissions');
  464. $submission = webform_get_submission($nid, $sid);
  465. return empty($submission) ? FALSE : $submission;
  466. }
  467. /**
  468. * Menu loader callback. Load a webform component if the given cid is a valid.
  469. */
  470. function webform_menu_component_load($cid, $nid, $type) {
  471. module_load_include('inc', 'webform', 'includes/webform.components');
  472. if ($cid == 'new') {
  473. $components = webform_components();
  474. $component = in_array($type, array_keys($components)) ? array(
  475. 'type' => $type,
  476. 'nid' => $nid,
  477. 'name' => $_GET['name'],
  478. 'required' => $_GET['required'],
  479. 'pid' => $_GET['pid'],
  480. 'weight' => $_GET['weight'],
  481. ) : FALSE;
  482. }
  483. else {
  484. $node = node_load($nid);
  485. $component = isset($node->webform['components'][$cid]) ? $node->webform['components'][$cid] : FALSE;
  486. }
  487. if ($component) {
  488. webform_component_defaults($component);
  489. }
  490. return $component;
  491. }
  492. /**
  493. * Menu loader callback. Load a webform e-mail if the given eid is a valid.
  494. */
  495. function webform_menu_email_load($eid, $nid) {
  496. module_load_include('inc', 'webform', 'includes/webform.emails');
  497. $node = node_load($nid);
  498. $email = webform_email_load($eid, $nid);
  499. if ($eid == 'new') {
  500. if (isset($_GET['option']) && isset($_GET['email'])) {
  501. $type = $_GET['option'];
  502. if ($type == 'custom') {
  503. $email['email'] = $_GET['email'];
  504. }
  505. elseif ($type == 'component' && isset($node->webform['components'][$_GET['email']])) {
  506. $email['email'] = $_GET['email'];
  507. }
  508. }
  509. if (isset($_GET['status'])) {
  510. $email['status'] = $_GET['status'];
  511. }
  512. }
  513. return $email;
  514. }
  515. /**
  516. * Return the access token for a submission.
  517. *
  518. * @param object $submission
  519. * The submission object.
  520. *
  521. * @return string
  522. * The access token for the submission.
  523. */
  524. function webform_get_submission_access_token($submission) {
  525. return md5($submission->submitted . $submission->sid . drupal_get_private_key());
  526. }
  527. /**
  528. * Access function for confirmation pages.
  529. *
  530. * @param object $node
  531. * The webform node object.
  532. *
  533. * @return bool
  534. * Boolean whether the user has access to the confirmation page.
  535. */
  536. function webform_confirmation_page_access($node) {
  537. global $user;
  538. // Make sure SID is a positive integer.
  539. $sid = (!empty($_GET['sid']) && (int) $_GET['sid'] > 0) ? (int) $_GET['sid'] : NULL;
  540. if ($sid) {
  541. module_load_include('inc', 'webform', 'includes/webform.submissions');
  542. $submission = webform_get_submission($node->nid, $sid);
  543. }
  544. else {
  545. $submission = NULL;
  546. }
  547. if ($submission) {
  548. // Logged-in users.
  549. if ($user->uid) {
  550. // User's own submission.
  551. if ($submission->uid === $user->uid && node_access('view', $node)) {
  552. return TRUE;
  553. }
  554. // User has results access to this submission.
  555. elseif (webform_submission_access($node, $submission)) {
  556. return TRUE;
  557. }
  558. }
  559. // Anonymous user for their own submission. Hash of submission data must
  560. // match the hash in the query string.
  561. elseif ((int) $user->uid === 0 && (int) $submission->uid === 0) {
  562. $hash_query = !empty($_GET['token']) ? $_GET['token'] : NULL;
  563. $hash = webform_get_submission_access_token($submission);
  564. if ($hash_query === $hash) {
  565. return TRUE;
  566. }
  567. }
  568. }
  569. else {
  570. // No submission exists (such as auto-deleted by another module, such as
  571. // webform_clear), just ensure that the user has access to view the node
  572. // page.
  573. if (node_access('view', $node)) {
  574. return TRUE;
  575. }
  576. }
  577. return FALSE;
  578. }
  579. /**
  580. * Access function for Webform submissions.
  581. *
  582. * @param object $node
  583. * The webform node object.
  584. * @param object $submission
  585. * The webform submission object.
  586. * @param object $op
  587. * The operation to perform. Must be one of view, edit, delete, list.
  588. * @param object $account
  589. * Optional. A user object or NULL to use the currently logged-in user.
  590. *
  591. * @return bool
  592. * Boolean whether the user has access to a webform submission.
  593. */
  594. function webform_submission_access($node, $submission, $op = 'view', $account = NULL) {
  595. global $user;
  596. $account = isset($account) ? $account : $user;
  597. $access_all = user_access('access all webform results', $account);
  598. $access_own_submission = isset($submission) && user_access('access own webform submissions', $account) && (($account->uid && $account->uid == $submission->uid) || isset($_SESSION['webform_submission'][$submission->sid]));
  599. $access_node_submissions = user_access('access own webform results', $account) && $account->uid == $node->uid;
  600. $token_access = $submission && isset($_GET['token']) && $_GET['token'] == webform_get_submission_access_token($submission);
  601. // If access is granted via a token, then allow subsequent submission access
  602. // for anonymous users.
  603. if (!$account->uid && $token_access) {
  604. $_SESSION['webform_submission'][$submission->sid] = $node->nid;
  605. }
  606. $general_access = $access_all || $access_own_submission || $access_node_submissions || $token_access;
  607. // Disable the page cache for anonymous users in this access callback,
  608. // otherwise the "Access denied" page gets cached.
  609. if (!$account->uid && user_access('access own webform submissions', $account)) {
  610. webform_disable_page_cache();
  611. }
  612. $module_access = count(array_filter(module_invoke_all('webform_submission_access', $node, $submission, $op, $account))) > 0;
  613. switch ($op) {
  614. case 'view':
  615. return $module_access || $general_access;
  616. case 'edit':
  617. case 'delete':
  618. return $module_access || (
  619. $general_access && (
  620. user_access($op . ' all webform submissions', $account) || (
  621. user_access($op . ' own webform submissions', $account) &&
  622. $account->uid == $submission->uid
  623. )
  624. )
  625. );
  626. case 'list':
  627. return $module_access ||
  628. user_access('access all webform results', $account) || (
  629. user_access('access own webform submissions', $account) && (
  630. $account->uid ||
  631. isset($_SESSION['webform_submission'])
  632. )
  633. ) || (
  634. user_access('access own webform results', $account) &&
  635. $account->uid == $node->uid
  636. );
  637. }
  638. }
  639. /**
  640. * Menu access callback. Ensure a user both access and node 'view' permission.
  641. */
  642. function webform_results_access($node, $account = NULL) {
  643. global $user;
  644. $account = isset($account) ? $account : $user;
  645. $module_access = count(array_filter(module_invoke_all('webform_results_access', $node, $account))) > 0;
  646. return node_access('view', $node, $account) && ($module_access || user_access('access all webform results', $account) || (user_access('access own webform results', $account) && $account->uid == $node->uid));
  647. }
  648. /**
  649. * Menu access callback.
  650. *
  651. * Ensure a user has both results access and permission to clear submissions.
  652. */
  653. function webform_results_clear_access($node, $account = NULL) {
  654. global $user;
  655. $account = isset($account) ? $account : $user;
  656. $module_access = count(array_filter(module_invoke_all('webform_results_clear_access', $node, $account))) > 0;
  657. return webform_results_access($node, $account) && ($module_access || user_access('delete all webform submissions', $account));
  658. }
  659. /**
  660. * Menu access callback. Ensure a sure has access to update a webform node.
  661. *
  662. * Unlike webform_results_access and webform_results_clear_access, access is
  663. * completely overridden by the any implementation of
  664. * hook_webform_update_access.
  665. *
  666. * If hook_webform_update_access is implemented by one or more other modules,
  667. * the results must be unanimously TRUE for access to be granted; otherwise it
  668. * is denied if even one implementation returns FALSE, regardless of node_access
  669. * and the 'edit webform components' permission. This allows implementors
  670. * complete flexibility.
  671. *
  672. * hook_webform_update_access should return TRUE if access should absolutely
  673. * be granted, FALSE if it should absolutely be denied, or NULL if node_access
  674. * and 'edit webform components' permission should determine access.
  675. *
  676. * @see hook_webform_update_access()
  677. */
  678. function webform_node_update_access($node, $account = NULL) {
  679. global $user;
  680. $account = isset($account) ? $account : $user;
  681. $module_access = module_invoke_all('webform_update_access', $node, $account);
  682. return empty($module_access)
  683. ? node_access('update', $node, $account) && user_access('edit webform components')
  684. : count(array_filter($module_access)) == count($module_access);
  685. }
  686. /**
  687. * Implements hook_admin_paths().
  688. */
  689. function webform_admin_paths() {
  690. if (variable_get('node_admin_theme')) {
  691. return array(
  692. 'node/*/webform' => TRUE,
  693. 'node/*/webform/*' => TRUE,
  694. 'node/*/webform-results' => TRUE,
  695. 'node/*/webform-results/*' => TRUE,
  696. 'node/*/submission/*' => TRUE,
  697. );
  698. }
  699. }
  700. /**
  701. * Implements hook_perm().
  702. */
  703. function webform_permission() {
  704. return array(
  705. 'access all webform results' => array(
  706. 'title' => t('Access all webform results'),
  707. 'description' => t('Grants access to the "Results" tab on all webform content. Generally an administrative permission.'),
  708. ),
  709. 'access own webform results' => array(
  710. 'title' => t('Access own webform results'),
  711. 'description' => t('Grants access to the "Results" tab to the author of webform content they have created.'),
  712. ),
  713. 'edit all webform submissions' => array(
  714. 'title' => t('Edit all webform submissions'),
  715. 'description' => t('Allows editing of any webform submission by any user. Generally an administrative permission.'),
  716. ),
  717. 'delete all webform submissions' => array(
  718. 'title' => t('Delete all webform submissions'),
  719. 'description' => t('Allows deleting of any webform submission by any user. Generally an administrative permission.'),
  720. ),
  721. 'access own webform submissions' => array(
  722. 'title' => t('Access own webform submissions'),
  723. ),
  724. 'edit own webform submissions' => array(
  725. 'title' => t('Edit own webform submissions'),
  726. ),
  727. 'delete own webform submissions' => array(
  728. 'title' => t('Delete own webform submissions'),
  729. ),
  730. 'edit webform components' => array(
  731. 'title' => t('Content authors: access and edit webform components and settings'),
  732. 'description' => t('Grants additional access to the webform components and settings to users who can edit the content. Generally an authenticated user permission.'),
  733. ),
  734. );
  735. }
  736. /**
  737. * Implements hook_theme().
  738. */
  739. function webform_theme() {
  740. $theme = array(
  741. // webform.module.
  742. 'webform_view' => array(
  743. 'render element' => 'webform',
  744. ),
  745. 'webform_view_messages' => array(
  746. 'variables' => array(
  747. 'node' => NULL,
  748. 'page' => NULL,
  749. 'submission_count' => NULL,
  750. 'user_limit_exceeded' => NULL,
  751. 'total_limit_exceeded' => NULL,
  752. 'allowed_roles' => NULL,
  753. 'closed' => NULL,
  754. 'cached' => NULL,
  755. ),
  756. ),
  757. 'webform_form' => array(
  758. 'render element' => 'form',
  759. 'template' => 'templates/webform-form',
  760. 'pattern' => 'webform_form_[0-9]+',
  761. ),
  762. 'webform_confirmation' => array(
  763. 'variables' => array('node' => NULL, 'sid' => NULL),
  764. 'template' => 'templates/webform-confirmation',
  765. 'pattern' => 'webform_confirmation_[0-9]+',
  766. ),
  767. 'webform_element' => array(
  768. 'render element' => 'element',
  769. ),
  770. 'webform_element_text' => array(
  771. 'render element' => 'element',
  772. ),
  773. 'webform_inline_radio' => array(
  774. 'render element' => 'element',
  775. ),
  776. 'webform_inline_radio_label' => array(
  777. 'render element' => 'element',
  778. ),
  779. 'webform_progressbar' => array(
  780. 'variables' => array(
  781. 'node' => NULL,
  782. 'page_num' => NULL,
  783. 'page_count' => NULL,
  784. 'page_labels' => array(),
  785. ),
  786. 'template' => 'templates/webform-progressbar',
  787. ),
  788. 'webform_mail_message' => array(
  789. 'variables' => array(
  790. 'node' => NULL,
  791. 'submission' => NULL,
  792. 'email' => NULL,
  793. ),
  794. 'template' => 'templates/webform-mail',
  795. 'pattern' => 'webform_mail(_[0-9]+)?',
  796. ),
  797. 'webform_mail_headers' => array(
  798. 'variables' => array(
  799. 'node' => NULL,
  800. 'submission' => NULL,
  801. 'email' => NULL,
  802. ),
  803. 'pattern' => 'webform_mail_headers_[0-9]+',
  804. ),
  805. 'webform_token_help' => array(
  806. 'variables' => array('groups' => array('node')),
  807. ),
  808. // webform.admin.inc.
  809. 'webform_admin_settings' => array(
  810. 'render element' => 'form',
  811. 'file' => 'includes/webform.admin.inc',
  812. ),
  813. 'webform_admin_content' => array(
  814. 'variables' => array('nodes' => NULL),
  815. 'file' => 'includes/webform.admin.inc',
  816. ),
  817. // webform.emails.inc.
  818. 'webform_emails_form' => array(
  819. 'render element' => 'form',
  820. 'file' => 'includes/webform.emails.inc',
  821. ),
  822. 'webform_email_component_mapping' => array(
  823. 'render element' => 'element',
  824. 'file' => 'includes/webform.emails.inc',
  825. ),
  826. 'webform_email_add_form' => array(
  827. 'render element' => 'form',
  828. 'file' => 'includes/webform.emails.inc',
  829. ),
  830. 'webform_email_edit_form' => array(
  831. 'render element' => 'form',
  832. 'file' => 'includes/webform.emails.inc',
  833. ),
  834. // webform.components.inc.
  835. 'webform_components_page' => array(
  836. 'variables' => array('node' => NULL, 'form' => NULL),
  837. 'file' => 'includes/webform.components.inc',
  838. ),
  839. 'webform_components_form' => array(
  840. 'render element' => 'form',
  841. 'file' => 'includes/webform.components.inc',
  842. ),
  843. 'webform_component_select' => array(
  844. 'render element' => 'element',
  845. 'file' => 'includes/webform.components.inc',
  846. ),
  847. // webform.conditionals.inc.
  848. 'webform_conditional_groups' => array(
  849. 'render element' => 'element',
  850. 'file' => 'includes/webform.conditionals.inc',
  851. ),
  852. 'webform_conditional_group_row' => array(
  853. 'render element' => 'element',
  854. 'file' => 'includes/webform.conditionals.inc',
  855. ),
  856. 'webform_conditional' => array(
  857. 'render element' => 'element',
  858. 'file' => 'includes/webform.conditionals.inc',
  859. ),
  860. // webform.pages.inc.
  861. 'webform_advanced_redirection_form' => array(
  862. 'render element' => 'form',
  863. 'file' => 'includes/webform.pages.inc',
  864. ),
  865. 'webform_advanced_submit_limit_form' => array(
  866. 'render element' => 'form',
  867. 'file' => 'includes/webform.pages.inc',
  868. ),
  869. 'webform_advanced_total_submit_limit_form' => array(
  870. 'render element' => 'form',
  871. 'file' => 'includes/webform.pages.inc',
  872. ),
  873. // webform.report.inc.
  874. 'webform_results_per_page' => array(
  875. 'variables' => array('total_count' => NULL, 'pager_count' => NULL),
  876. 'file' => 'includes/webform.report.inc',
  877. ),
  878. 'webform_results_submissions_header' => array(
  879. 'variables' => array('node' => NULL),
  880. 'file' => 'includes/webform.report.inc',
  881. ),
  882. 'webform_results_submissions' => array(
  883. 'render element' => 'element',
  884. 'template' => 'templates/webform-results-submissions',
  885. 'file' => 'includes/webform.report.inc',
  886. ),
  887. 'webform_results_table_header' => array(
  888. 'variables' => array('node' => NULL),
  889. 'file' => 'includes/webform.report.inc',
  890. ),
  891. 'webform_results_table' => array(
  892. 'variables' => array(
  893. 'node' => NULL,
  894. 'components' => NULL,
  895. 'submissions' => NULL,
  896. 'total_count' => NULL,
  897. 'pager_count' => NULL,
  898. ),
  899. 'file' => 'includes/webform.report.inc',
  900. ),
  901. 'webform_results_download_range' => array(
  902. 'render element' => 'element',
  903. 'file' => 'includes/webform.report.inc',
  904. ),
  905. 'webform_results_download_select_format' => array(
  906. 'render element' => 'element',
  907. 'file' => 'includes/webform.report.inc',
  908. ),
  909. 'webform_analysis' => array(
  910. 'render element' => 'analysis',
  911. 'template' => 'templates/webform-analysis',
  912. 'file' => 'includes/webform.report.inc',
  913. ),
  914. 'webform_analysis_component' => array(
  915. 'render element' => 'component_analysis',
  916. 'template' => 'templates/webform-analysis-component',
  917. 'file' => 'includes/webform.report.inc',
  918. ),
  919. 'webform_analysis_component_basic' => array(
  920. 'variables' => array('component' => NULL, 'data' => NULL),
  921. 'file' => 'includes/webform.report.inc',
  922. ),
  923. // webform.submissions.inc.
  924. 'webform_submission' => array(
  925. 'render element' => 'renderable',
  926. 'template' => 'templates/webform-submission',
  927. 'pattern' => 'webform_submission_[0-9]+',
  928. 'file' => 'includes/webform.submissions.inc',
  929. ),
  930. 'webform_submission_page' => array(
  931. 'variables' => array(
  932. 'node' => NULL,
  933. 'submission' => NULL,
  934. 'submission_content' => NULL,
  935. 'submission_navigation' => NULL,
  936. 'submission_information' => NULL,
  937. 'submission_actions' => NULL,
  938. 'mode' => NULL,
  939. ),
  940. 'template' => 'templates/webform-submission-page',
  941. 'file' => 'includes/webform.submissions.inc',
  942. ),
  943. 'webform_submission_information' => array(
  944. 'variables' => array(
  945. 'node' => NULL,
  946. 'submission' => NULL,
  947. 'mode' => 'display',
  948. ),
  949. 'template' => 'templates/webform-submission-information',
  950. 'file' => 'includes/webform.submissions.inc',
  951. ),
  952. 'webform_submission_navigation' => array(
  953. 'variables' => array('node' => NULL, 'submission' => NULL, 'mode' => NULL),
  954. 'template' => 'templates/webform-submission-navigation',
  955. 'file' => 'includes/webform.submissions.inc',
  956. ),
  957. 'webform_submission_resend' => array(
  958. 'render element' => 'form',
  959. 'file' => 'includes/webform.submissions.inc',
  960. ),
  961. );
  962. // Theme functions in all components.
  963. $components = webform_components(TRUE);
  964. foreach ($components as $type => $component) {
  965. if ($theme_additions = webform_component_invoke($type, 'theme')) {
  966. $theme = array_merge($theme, $theme_additions);
  967. }
  968. }
  969. return $theme;
  970. }
  971. /**
  972. * Implements hook_library().
  973. */
  974. function webform_library() {
  975. $module_path = drupal_get_path('module', 'webform');
  976. // Webform administration.
  977. $libraries['admin'] = array(
  978. 'title' => 'Webform: Administration',
  979. 'website' => 'http://drupal.org/project/webform',
  980. 'version' => '1.0',
  981. 'js' => array(
  982. $module_path . '/js/webform-admin.js' => array('group' => JS_DEFAULT),
  983. ),
  984. 'css' => array(
  985. $module_path . '/css/webform-admin.css' => array('group' => CSS_DEFAULT, 'weight' => 1),
  986. ),
  987. );
  988. return $libraries;
  989. }
  990. /**
  991. * Implements hook_element_info().
  992. */
  993. function webform_element_info() {
  994. // A few of our components need to be defined here because Drupal does not
  995. // provide these components natively. Because this hook fires on every page
  996. // load (even on non-webform pages), we don't put this in the component .inc
  997. // files because of the unnecessary loading that it would require.
  998. $elements['webform_time'] = array('#input' => 'TRUE');
  999. $elements['webform_grid'] = array('#input' => 'TRUE');
  1000. $elements['webform_email'] = array(
  1001. '#input' => TRUE,
  1002. '#theme' => 'webform_email',
  1003. '#size' => 60,
  1004. );
  1005. $elements['webform_number'] = array(
  1006. '#input' => TRUE,
  1007. '#theme' => 'webform_number',
  1008. '#min' => NULL,
  1009. '#max' => NULL,
  1010. '#step' => NULL,
  1011. );
  1012. $elements['webform_conditional'] = array(
  1013. '#input' => TRUE,
  1014. '#theme' => 'webform_conditional',
  1015. '#default_value' => NULL,
  1016. '#process' => array('webform_conditional_expand'),
  1017. );
  1018. return $elements;
  1019. }
  1020. /**
  1021. * Implements hook_webform_component_info().
  1022. */
  1023. function webform_webform_component_info() {
  1024. $component_info = array(
  1025. 'date' => array(
  1026. 'label' => t('Date'),
  1027. 'description' => t('Presents month, day, and year fields.'),
  1028. 'features' => array(
  1029. 'views_range' => TRUE,
  1030. 'css_classes' => FALSE,
  1031. ),
  1032. 'file' => 'components/date.inc',
  1033. 'conditional_type' => 'date',
  1034. ),
  1035. 'email' => array(
  1036. 'label' => t('E-mail'),
  1037. 'description' => t('A special textfield that accepts e-mail addresses.'),
  1038. 'file' => 'components/email.inc',
  1039. 'features' => array(
  1040. 'email_address' => TRUE,
  1041. 'spam_analysis' => TRUE,
  1042. 'placeholder' => TRUE,
  1043. 'conditional_action_set' => TRUE,
  1044. ),
  1045. ),
  1046. 'fieldset' => array(
  1047. 'label' => t('Fieldset'),
  1048. 'description' => t('Fieldsets allow you to organize multiple fields into groups.'),
  1049. 'features' => array(
  1050. 'csv' => FALSE,
  1051. 'default_value' => FALSE,
  1052. 'required' => FALSE,
  1053. 'conditional' => FALSE,
  1054. 'group' => TRUE,
  1055. 'title_inline' => FALSE,
  1056. 'wrapper_classes' => FALSE,
  1057. ),
  1058. 'file' => 'components/fieldset.inc',
  1059. ),
  1060. 'grid' => array(
  1061. 'label' => t('Grid'),
  1062. 'description' => t('Allows creation of grid questions, denoted by radio buttons.'),
  1063. 'features' => array(
  1064. 'default_value' => FALSE,
  1065. 'title_inline' => FALSE,
  1066. 'title_internal' => TRUE,
  1067. 'css_classes' => FALSE,
  1068. 'conditional' => FALSE,
  1069. 'group' => TRUE,
  1070. ),
  1071. 'file' => 'components/grid.inc',
  1072. ),
  1073. 'hidden' => array(
  1074. 'label' => t('Hidden'),
  1075. 'description' => t('A field which is not visible to the user, but is recorded with the submission.'),
  1076. 'file' => 'components/hidden.inc',
  1077. 'features' => array(
  1078. 'required' => FALSE,
  1079. 'description' => FALSE,
  1080. 'email_address' => TRUE,
  1081. 'email_name' => TRUE,
  1082. 'title_display' => FALSE,
  1083. 'private' => FALSE,
  1084. 'wrapper_classes' => FALSE,
  1085. 'css_classes' => FALSE,
  1086. 'conditional_action_set' => TRUE,
  1087. ),
  1088. ),
  1089. 'markup' => array(
  1090. 'label' => t('Markup'),
  1091. 'description' => t('Displays text as HTML in the form; does not render a field.'),
  1092. 'features' => array(
  1093. 'analysis' => FALSE,
  1094. 'csv' => FALSE,
  1095. 'default_value' => FALSE,
  1096. 'description' => FALSE,
  1097. 'email' => FALSE,
  1098. 'required' => FALSE,
  1099. 'conditional' => FALSE,
  1100. 'title_display' => FALSE,
  1101. 'private' => FALSE,
  1102. 'wrapper_classes' => FALSE,
  1103. 'css_classes' => FALSE,
  1104. 'conditional_action_set' => TRUE,
  1105. ),
  1106. 'file' => 'components/markup.inc',
  1107. ),
  1108. 'number' => array(
  1109. 'label' => t('Number'),
  1110. 'description' => t('A numeric input field (either as textfield or select list).'),
  1111. 'features' => array(
  1112. 'conditional_action_set' => TRUE,
  1113. ),
  1114. 'file' => 'components/number.inc',
  1115. 'conditional_type' => 'numeric',
  1116. ),
  1117. 'pagebreak' => array(
  1118. 'label' => t('Page break'),
  1119. 'description' => t('Organize forms into multiple pages.'),
  1120. 'features' => array(
  1121. 'analysis' => FALSE,
  1122. 'conditional' => FALSE,
  1123. 'csv' => FALSE,
  1124. 'default_value' => FALSE,
  1125. 'description' => FALSE,
  1126. 'private' => FALSE,
  1127. 'required' => FALSE,
  1128. 'title_display' => FALSE,
  1129. 'wrapper_classes' => FALSE,
  1130. 'css_classes' => FALSE,
  1131. ),
  1132. 'file' => 'components/pagebreak.inc',
  1133. ),
  1134. 'select' => array(
  1135. 'label' => t('Select options'),
  1136. 'description' => t('Allows creation of checkboxes, radio buttons, or select menus.'),
  1137. 'file' => 'components/select.inc',
  1138. 'features' => array(
  1139. 'default_value' => FALSE,
  1140. 'email_address' => TRUE,
  1141. 'email_name' => TRUE,
  1142. 'conditional_action_set' => TRUE,
  1143. ),
  1144. 'conditional_type' => 'select',
  1145. ),
  1146. 'textarea' => array(
  1147. 'label' => t('Textarea'),
  1148. 'description' => t('A large text area that allows for multiple lines of input.'),
  1149. 'file' => 'components/textarea.inc',
  1150. 'features' => array(
  1151. 'spam_analysis' => TRUE,
  1152. 'placeholder' => TRUE,
  1153. 'conditional_action_set' => TRUE,
  1154. ),
  1155. ),
  1156. 'textfield' => array(
  1157. 'label' => t('Textfield'),
  1158. 'description' => t('Basic textfield type.'),
  1159. 'file' => 'components/textfield.inc',
  1160. 'features' => array(
  1161. 'email_name' => TRUE,
  1162. 'spam_analysis' => TRUE,
  1163. 'placeholder' => TRUE,
  1164. 'conditional_action_set' => TRUE,
  1165. ),
  1166. ),
  1167. 'time' => array(
  1168. 'label' => t('Time'),
  1169. 'description' => t('Presents the user with hour and minute fields. Optional am/pm fields.'),
  1170. 'features' => array(
  1171. 'views_range' => TRUE,
  1172. 'css_classes' => FALSE,
  1173. ),
  1174. 'file' => 'components/time.inc',
  1175. 'conditional_type' => 'time',
  1176. ),
  1177. );
  1178. if (module_exists('file')) {
  1179. $component_info['file'] = array(
  1180. 'label' => t('File'),
  1181. 'description' => t('Allow users to upload files of configurable types.'),
  1182. 'features' => array(
  1183. 'conditional' => FALSE,
  1184. 'default_value' => FALSE,
  1185. 'attachment' => TRUE,
  1186. 'file_usage' => TRUE,
  1187. ),
  1188. 'file' => 'components/file.inc',
  1189. );
  1190. }
  1191. return $component_info;
  1192. }
  1193. /**
  1194. * Implements hook_webform_conditional_operator_info().
  1195. */
  1196. function webform_webform_conditional_operator_info() {
  1197. module_load_include('inc', 'webform', 'includes/webform.conditionals');
  1198. return _webform_conditional_operator_info();
  1199. }
  1200. /**
  1201. * Implements hook_forms().
  1202. *
  1203. * All webform_client_form forms share the same form handler.
  1204. */
  1205. function webform_forms($form_id) {
  1206. $forms = array();
  1207. if (strpos($form_id, 'webform_client_form_') === 0) {
  1208. $forms[$form_id]['callback'] = 'webform_client_form';
  1209. }
  1210. return $forms;
  1211. }
  1212. /**
  1213. * Implements hook_webform_select_options_info().
  1214. */
  1215. function webform_webform_select_options_info() {
  1216. module_load_include('inc', 'webform', 'includes/webform.options');
  1217. return _webform_options_info();
  1218. }
  1219. /**
  1220. * Implements hook_webform_webform_submission_actions().
  1221. */
  1222. function webform_webform_submission_actions($node, $submission) {
  1223. $actions = array();
  1224. $destination = drupal_get_destination();
  1225. if (module_exists('print_pdf') && user_access('access PDF version')) {
  1226. $actions['printpdf'] = array(
  1227. 'title' => t('Download PDF'),
  1228. 'href' => 'printpdf/' . $node->nid . '/submission/' . $submission->sid,
  1229. 'query' => $destination,
  1230. );
  1231. }
  1232. if (module_exists('print') && user_access('access print')) {
  1233. $actions['print'] = array(
  1234. 'title' => t('Print'),
  1235. 'href' => 'print/' . $node->nid . '/submission/' . $submission->sid,
  1236. );
  1237. }
  1238. if (webform_results_access($node) && count($node->webform['emails'])) {
  1239. $actions['resend'] = array(
  1240. 'title' => t('Resend e-mails'),
  1241. 'href' => 'node/' . $node->nid . '/submission/' . $submission->sid . '/resend',
  1242. 'query' => drupal_get_destination(),
  1243. );
  1244. }
  1245. return $actions;
  1246. }
  1247. /**
  1248. * Implements hook_webform_submission_presave().
  1249. *
  1250. * We implement our own hook here to facilitate the File component, which needs
  1251. * to clean up manage file usage records and delete files from submissions that
  1252. * have been edited if necessary.
  1253. */
  1254. function webform_webform_submission_presave($node, &$submission) {
  1255. // Check if there are any file components in this submission and if any of
  1256. // them currently contain files.
  1257. $has_file_components = FALSE;
  1258. $new_fids = array();
  1259. $old_fids = array();
  1260. $renameable = array();
  1261. foreach ($node->webform['components'] as $cid => $component) {
  1262. if (webform_component_feature($component['type'], 'file_usage')) {
  1263. $has_file_components = TRUE;
  1264. if (!empty($submission->data[$cid])) {
  1265. foreach ($submission->data[$cid] as $key => $value) {
  1266. if (empty($value)) {
  1267. unset($submission->data[$cid][$key]);
  1268. }
  1269. if (strlen($component['extra']['rename'])) {
  1270. $renameable[$cid][] = $value;
  1271. }
  1272. }
  1273. $new_fids = array_merge($new_fids, $submission->data[$cid]);
  1274. }
  1275. }
  1276. }
  1277. if ($has_file_components) {
  1278. // If we're updating a submission, build a list of previous files.
  1279. if (isset($submission->sid)) {
  1280. drupal_static_reset('webform_get_submission');
  1281. $old_submission = webform_get_submission($node->nid, $submission->sid);
  1282. foreach ($node->webform['components'] as $cid => $component) {
  1283. if (webform_component_feature($component['type'], 'file_usage')) {
  1284. if (!empty($old_submission->data[$cid])) {
  1285. $old_fids = array_merge($old_fids, $old_submission->data[$cid]);
  1286. }
  1287. }
  1288. }
  1289. }
  1290. // Only rename files if this is the first time the submission is being saved
  1291. // as finished.
  1292. if ($submission->is_draft || (isset($old_submission) && !$old_submission->is_draft)) {
  1293. $renameable = array();
  1294. }
  1295. // Save the list of added or removed files so we can add usage in
  1296. // hook_webform_submission_insert() or _update().
  1297. $submission->file_usage = array(
  1298. // Diff the old against new to determine what files were deleted.
  1299. 'deleted_fids' => array_diff($old_fids, $new_fids),
  1300. // Diff the new files against old to determine new uploads.
  1301. 'added_fids' => array_diff($new_fids, $old_fids),
  1302. // A list of files which need renaming with tokens.
  1303. 'renameable' => $renameable,
  1304. );
  1305. }
  1306. }
  1307. /**
  1308. * Implements hook_webform_submission_insert().
  1309. */
  1310. function webform_webform_submission_insert($node, $submission) {
  1311. if (isset($submission->file_usage)) {
  1312. webform_component_include('file');
  1313. webform_file_usage_adjust($submission);
  1314. webform_file_rename($node, $submission);
  1315. }
  1316. }
  1317. /**
  1318. * Implements hook_webform_submission_update().
  1319. */
  1320. function webform_webform_submission_update($node, $submission) {
  1321. if (isset($submission->file_usage)) {
  1322. webform_component_include('file');
  1323. webform_file_usage_adjust($submission);
  1324. webform_file_rename($node, $submission);
  1325. }
  1326. }
  1327. /**
  1328. * Implements hook_webform_submission_render_alter().
  1329. */
  1330. function webform_webform_submission_render_alter(&$renderable) {
  1331. // If displaying a submission to end-users who are viewing their own
  1332. // submissions (and not through an e-mail), do not show hidden values.
  1333. // This needs to be implemented at the level of the entire submission, since
  1334. // individual components do not get contextual information about where they
  1335. // are being displayed.
  1336. $node = $renderable['#node'];
  1337. $is_admin = webform_results_access($node);
  1338. if (empty($renderable['#email']) && !$is_admin) {
  1339. // Find and hide the display of all hidden components.
  1340. module_load_include('inc', 'webform', 'includes/webform.components');
  1341. foreach ($node->webform['components'] as $cid => $component) {
  1342. if ($component['type'] == 'hidden') {
  1343. $parents = webform_component_parent_keys($node, $component);
  1344. $element = &$renderable;
  1345. foreach ($parents as $pid) {
  1346. $element = &$element[$pid];
  1347. }
  1348. $element['#access'] = FALSE;
  1349. }
  1350. }
  1351. }
  1352. }
  1353. /**
  1354. * Implements hook_file_download().
  1355. *
  1356. * Only allow users with view webform submissions to download files.
  1357. */
  1358. function webform_file_download($uri) {
  1359. module_load_include('inc', 'webform', 'includes/webform.submissions');
  1360. // Determine whether this file was a webform upload.
  1361. $row = db_query("SELECT fu.id as sid, f.fid FROM {file_managed} f LEFT JOIN {file_usage} fu ON f.fid = fu.fid AND fu.module = :webform AND fu.type = :submission WHERE f.uri = :uri", array('uri' => $uri, ':webform' => 'webform', ':submission' => 'submission'))->fetchObject();
  1362. if ($row) {
  1363. $file = file_load($row->fid);
  1364. }
  1365. if (!empty($row->sid)) {
  1366. $submissions = webform_get_submissions(array('sid' => $row->sid));
  1367. $submission = reset($submissions);
  1368. }
  1369. // Grant or deny file access based on access to the submission.
  1370. if (!empty($submission)) {
  1371. $node = node_load($submission->nid);
  1372. if (webform_submission_access($node, $submission)) {
  1373. return file_get_content_headers($file);
  1374. }
  1375. else {
  1376. return -1;
  1377. }
  1378. }
  1379. // Grant access to files uploaded by a user before the submission is saved.
  1380. elseif (!empty($file) && !empty($_SESSION['webform_files'][$file->fid])) {
  1381. return file_get_content_headers($file);
  1382. }
  1383. // Ensure we never completely ignore a webform file request.
  1384. if (strpos(file_uri_target($uri), 'webform/') === 0) {
  1385. // The file is not part of a submission or a submission-in-progress (by
  1386. // the current user), however it may be part of a submission-in-progress
  1387. // (or an abandoned submission) by another user. We assume that all files
  1388. // under our enforced directory prefix are in fact webform files, and so
  1389. // we deny access to the file. Abandoned uploads will be deleted by
  1390. // system_cron() in due course.
  1391. return -1;
  1392. }
  1393. }
  1394. /**
  1395. * Return all content type enabled with webform.
  1396. *
  1397. * @return array
  1398. * An array of node type names.
  1399. */
  1400. function webform_node_types() {
  1401. $types = &drupal_static(__FUNCTION__, NULL);
  1402. if (!isset($types)) {
  1403. $types = array();
  1404. foreach (node_type_get_names() as $type => $name) {
  1405. if (variable_get('webform_node_' . $type, FALSE)) {
  1406. $types[] = $type;
  1407. }
  1408. }
  1409. }
  1410. return $types;
  1411. }
  1412. /**
  1413. * Implements hook_node_type_delete().
  1414. */
  1415. function webform_node_type_delete($info) {
  1416. variable_del('webform_node_' . $info->type);
  1417. }
  1418. /**
  1419. * Implements hook_node_insert().
  1420. */
  1421. function webform_node_insert($node) {
  1422. if (!variable_get('webform_node_' . $node->type, FALSE)) {
  1423. return;
  1424. }
  1425. // If added directly through node_save(), set defaults for the node.
  1426. if (!isset($node->webform)) {
  1427. $node->webform = array();
  1428. }
  1429. // Ensure values for all defaults are provided. Useful for importing from
  1430. // older versions into newer ones.
  1431. $node->webform += webform_node_defaults();
  1432. // Do not make an entry if this node does not have any Webform settings.
  1433. if ($node->webform == webform_node_defaults() && !in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
  1434. return;
  1435. }
  1436. module_load_include('inc', 'webform', 'includes/webform.components');
  1437. module_load_include('inc', 'webform', 'includes/webform.conditionals');
  1438. module_load_include('inc', 'webform', 'includes/webform.emails');
  1439. // Prepare the record for writing.
  1440. $node->webform['nid'] = $node->nid;
  1441. $webform_record = $node->webform;
  1442. $webform_record['preview_excluded_components'] = implode(',', $webform_record['preview_excluded_components']);
  1443. // Insert the webform.
  1444. $node->webform['record_exists'] = (bool) drupal_write_record('webform', $webform_record);
  1445. // Insert the components into the database. Used with clone.module.
  1446. if (isset($node->webform['components']) && !empty($node->webform['components'])) {
  1447. foreach ($node->webform['components'] as $cid => $component) {
  1448. // Required for clone.module.
  1449. $component['nid'] = $node->nid;
  1450. webform_component_insert($component);
  1451. }
  1452. }
  1453. // Insert conditionals. Also used with clone.module.
  1454. if (isset($node->webform['conditionals']) && !empty($node->webform['conditionals'])) {
  1455. foreach ($node->webform['conditionals'] as $rgid => $conditional) {
  1456. $conditional['nid'] = $node->nid;
  1457. $conditional['rgid'] = $rgid;
  1458. webform_conditional_insert($conditional);
  1459. }
  1460. }
  1461. // Insert emails. Also used with clone.module.
  1462. if (isset($node->webform['emails']) && !empty($node->webform['emails'])) {
  1463. foreach ($node->webform['emails'] as $eid => $email) {
  1464. $email['nid'] = $node->nid;
  1465. webform_email_insert($email);
  1466. }
  1467. }
  1468. // Set the per-role submission access control.
  1469. foreach (array_filter($node->webform['roles']) as $rid) {
  1470. db_insert('webform_roles')->fields(array('nid' => $node->nid, 'rid' => $rid))->execute();
  1471. }
  1472. // Flush the block cache if creating a block.
  1473. if (module_exists('block') && $node->webform['block']) {
  1474. block_flush_caches();
  1475. }
  1476. }
  1477. /**
  1478. * Implements hook_node_update().
  1479. */
  1480. function webform_node_update($node) {
  1481. if (!variable_get('webform_node_' . $node->type, FALSE)) {
  1482. return;
  1483. }
  1484. // Check if this node needs a webform record at all. If it matches the
  1485. // defaults, any existing record will be deleted.
  1486. webform_check_record($node);
  1487. // If a webform row doesn't even exist, we can assume it needs to be inserted.
  1488. // If the the webform matches the defaults, no row will be inserted.
  1489. if (!$node->webform['record_exists']) {
  1490. webform_node_insert($node);
  1491. return;
  1492. }
  1493. // Prepare the record for writing.
  1494. $node->webform['nid'] = $node->nid;
  1495. $webform_record = $node->webform;
  1496. $webform_record['preview_excluded_components'] = implode(',', $webform_record['preview_excluded_components']);
  1497. // Update the webform entry.
  1498. drupal_write_record('webform', $webform_record, array('nid'));
  1499. // Compare the webform components and don't do anything if it's not needed.
  1500. $original = $node->original;
  1501. if ($original->webform['components'] != $node->webform['components']) {
  1502. module_load_include('inc', 'webform', 'includes/webform.components');
  1503. $original_cids = array_keys($original->webform['components']);
  1504. $current_cids = array_keys($node->webform['components']);
  1505. $all_cids = array_unique(array_merge($original_cids, $current_cids));
  1506. $deleted_cids = array_diff($original_cids, $current_cids);
  1507. $inserted_cids = array_diff($current_cids, $original_cids);
  1508. foreach ($all_cids as $cid) {
  1509. $node->webform['components'][$cid]['nid'] = $node->nid;
  1510. if (in_array($cid, $inserted_cids)) {
  1511. webform_component_insert($node->webform['components'][$cid]);
  1512. }
  1513. elseif (in_array($cid, $deleted_cids)) {
  1514. // Delete components only after all updates have been processed.
  1515. }
  1516. elseif ($node->webform['components'][$cid] != $original->webform['components'][$cid]) {
  1517. webform_component_update($node->webform['components'][$cid]);
  1518. }
  1519. }
  1520. // Delete components now that any parent changes have been saved. When
  1521. // components are moved and deleted in one operation in FormBuilder, this
  1522. // ensures that only the current children are deleted.
  1523. foreach ($deleted_cids as $cid) {
  1524. webform_component_delete($node, $original->webform['components'][$cid]);
  1525. }
  1526. }
  1527. // Compare the webform conditionals and don't do anything if it's not needed.
  1528. if ($original->webform['conditionals'] != $node->webform['conditionals']) {
  1529. module_load_include('inc', 'webform', 'includes/webform.conditionals');
  1530. // Conditionals don't have unique site-wide IDs or configuration, so our
  1531. // update here is a bit more aggressive than for components and e-mails.
  1532. // Delete any conditionals no longer in the webform or that have changed.
  1533. foreach ($original->webform['conditionals'] as $rgid => $conditional) {
  1534. if (!isset($node->webform['conditionals'][$rgid]) || $conditional != $node->webform['conditionals'][$rgid]) {
  1535. webform_conditional_delete($node, $conditional);
  1536. }
  1537. }
  1538. // Insert any conditionals not in the original or that have changed.
  1539. foreach ($node->webform['conditionals'] as $rgid => $conditional) {
  1540. $conditional['nid'] = $node->nid;
  1541. $conditional['rgid'] = $rgid;
  1542. if (!isset($original->webform['conditionals'][$rgid]) || $original->webform['conditionals'][$rgid] != $conditional) {
  1543. webform_conditional_insert($conditional);
  1544. }
  1545. }
  1546. }
  1547. // Compare the webform e-mails and don't do anything if it's not needed.
  1548. if ($original->webform['emails'] != $node->webform['emails']) {
  1549. module_load_include('inc', 'webform', 'includes/webform.emails');
  1550. $original_eids = array_keys($original->webform['emails']);
  1551. $current_eids = array_keys($node->webform['emails']);
  1552. $all_eids = array_unique(array_merge($original_eids, $current_eids));
  1553. $deleted_eids = array_diff($original_eids, $current_eids);
  1554. $inserted_eids = array_diff($current_eids, $original_eids);
  1555. foreach ($all_eids as $eid) {
  1556. $node->webform['emails'][$eid]['nid'] = $node->nid;
  1557. if (in_array($eid, $inserted_eids)) {
  1558. webform_email_insert($node->webform['emails'][$eid]);
  1559. }
  1560. elseif (in_array($eid, $deleted_eids)) {
  1561. webform_email_delete($node, $original->webform['emails'][$eid]);
  1562. }
  1563. elseif ($node->webform['emails'][$eid] != $original->webform['emails'][$eid]) {
  1564. webform_email_update($node->webform['emails'][$eid]);
  1565. }
  1566. }
  1567. }
  1568. // Just delete and re-insert roles if they've changed.
  1569. if ($original->webform['roles'] != $node->webform['roles']) {
  1570. db_delete('webform_roles')->condition('nid', $node->nid)->execute();
  1571. foreach (array_filter($node->webform['roles']) as $rid) {
  1572. db_insert('webform_roles')->fields(array('nid' => $node->nid, 'rid' => $rid))->execute();
  1573. }
  1574. }
  1575. // Flush the block cache if block settings have been changed.
  1576. if (function_exists('block_flush_caches') && $node->webform['block'] != $original->webform['block']) {
  1577. block_flush_caches();
  1578. }
  1579. }
  1580. /**
  1581. * Implements hook_node_delete().
  1582. */
  1583. function webform_node_delete($node) {
  1584. if (!variable_get('webform_node_' . $node->type, FALSE)) {
  1585. return;
  1586. }
  1587. // Allow components clean up extra data, such as uploaded files.
  1588. module_load_include('inc', 'webform', 'includes/webform.components');
  1589. foreach ($node->webform['components'] as $cid => $component) {
  1590. webform_component_delete($node, $component);
  1591. }
  1592. // Remove any trace of webform data from the database.
  1593. db_delete('webform')->condition('nid', $node->nid)->execute();
  1594. db_delete('webform_component')->condition('nid', $node->nid)->execute();
  1595. db_delete('webform_conditional')->condition('nid', $node->nid)->execute();
  1596. db_delete('webform_conditional_rules')->condition('nid', $node->nid)->execute();
  1597. db_delete('webform_conditional_actions')->condition('nid', $node->nid)->execute();
  1598. db_delete('webform_emails')->condition('nid', $node->nid)->execute();
  1599. db_delete('webform_roles')->condition('nid', $node->nid)->execute();
  1600. db_delete('webform_submissions')->condition('nid', $node->nid)->execute();
  1601. db_delete('webform_submitted_data')->condition('nid', $node->nid)->execute();
  1602. db_delete('webform_last_download')->condition('nid', $node->nid)->execute();
  1603. }
  1604. /**
  1605. * Default settings for a newly created webform node.
  1606. */
  1607. function webform_node_defaults() {
  1608. $progress_bar_defaults = webform_variable_get('webform_progressbar_style');
  1609. $defaults = array(
  1610. 'confirmation' => '',
  1611. 'confirmation_format' => NULL,
  1612. 'redirect_url' => '<confirmation>',
  1613. 'block' => '0',
  1614. 'allow_draft' => '0',
  1615. 'auto_save' => '0',
  1616. 'confidential' => '0',
  1617. 'submit_notice' => '1',
  1618. 'submit_text' => '',
  1619. 'next_serial' => 1,
  1620. 'submit_limit' => '-1',
  1621. 'submit_interval' => '-1',
  1622. 'total_submit_limit' => '-1',
  1623. 'total_submit_interval' => '-1',
  1624. 'progressbar_page_number' => in_array('progressbar_page_number', $progress_bar_defaults) ? '1' : '0',
  1625. 'progressbar_percent' => in_array('progressbar_percent', $progress_bar_defaults) ? '1' : '0',
  1626. 'progressbar_bar' => in_array('progressbar_bar', $progress_bar_defaults) ? '1' : '0',
  1627. 'progressbar_pagebreak_labels' => in_array('progressbar_pagebreak_labels', $progress_bar_defaults) ? '1' : '0',
  1628. 'progressbar_include_confirmation' => in_array('progressbar_include_confirmation', $progress_bar_defaults) ? '1' : '0',
  1629. 'progressbar_label_first' => webform_variable_get('webform_progressbar_label_first'),
  1630. 'progressbar_label_confirmation' => webform_variable_get('webform_progressbar_label_confirmation'),
  1631. 'preview' => 0,
  1632. 'preview_next_button_label' => '',
  1633. 'preview_prev_button_label' => '',
  1634. 'preview_title' => '',
  1635. 'preview_message' => '',
  1636. 'preview_message_format' => NULL,
  1637. 'preview_excluded_components' => array(),
  1638. 'status' => '1',
  1639. 'record_exists' => FALSE,
  1640. 'roles' => array('1', '2'),
  1641. 'emails' => array(),
  1642. 'components' => array(),
  1643. 'conditionals' => array(),
  1644. );
  1645. drupal_alter('webform_node_defaults', $defaults);
  1646. return $defaults;
  1647. }
  1648. /**
  1649. * Implements hook_node_prepare().
  1650. */
  1651. function webform_node_prepare($node) {
  1652. if (variable_get('webform_node_' . $node->type, FALSE) && !isset($node->webform)) {
  1653. $node->webform = webform_node_defaults();
  1654. }
  1655. }
  1656. /**
  1657. * Implements hook_node_load().
  1658. */
  1659. function webform_node_load($nodes, $types) {
  1660. // Quick check to see if we need to do anything at all for these nodes.
  1661. $webform_types = webform_node_types();
  1662. if (count(array_intersect($types, $webform_types)) == 0) {
  1663. return;
  1664. }
  1665. module_load_include('inc', 'webform', 'includes/webform.components');
  1666. // Select all webforms that match these node IDs.
  1667. $result = db_select('webform')
  1668. ->fields('webform')
  1669. ->condition('nid', array_keys($nodes), 'IN')
  1670. ->execute()
  1671. ->fetchAllAssoc('nid', PDO::FETCH_ASSOC);
  1672. foreach ($result as $nid => $webform) {
  1673. // Load the basic information for each node.
  1674. $nodes[$nid]->webform = $webform;
  1675. $nodes[$nid]->webform['record_exists'] = TRUE;
  1676. // Expand the list of excluded preview components.
  1677. $nodes[$nid]->webform['preview_excluded_components'] = array_filter(explode(',', $webform['preview_excluded_components']));
  1678. }
  1679. // Load the components, emails, and defaults for all webform-enabled nodes.
  1680. // @todo: Increase efficiency here by pulling in all information all at once
  1681. // instead of individual queries.
  1682. foreach ($nodes as $nid => $node) {
  1683. if (!in_array($node->type, $webform_types)) {
  1684. continue;
  1685. }
  1686. // If a webform record doesn't exist, just return the defaults.
  1687. if (!isset($nodes[$nid]->webform)) {
  1688. $nodes[$nid]->webform = webform_node_defaults();
  1689. continue;
  1690. }
  1691. $nodes[$nid]->webform['roles'] = db_select('webform_roles')
  1692. ->fields('webform_roles', array('rid'))
  1693. ->condition('nid', $nid)
  1694. ->execute()
  1695. ->fetchCol();
  1696. $nodes[$nid]->webform['emails'] = db_select('webform_emails')
  1697. ->fields('webform_emails')
  1698. ->condition('nid', $nid)
  1699. ->execute()
  1700. ->fetchAllAssoc('eid', PDO::FETCH_ASSOC);
  1701. // Unserialize the mappings and excluded component list for e-mails.
  1702. foreach ($nodes[$nid]->webform['emails'] as $eid => $email) {
  1703. $nodes[$nid]->webform['emails'][$eid]['excluded_components'] = array_filter(explode(',', $email['excluded_components']));
  1704. $nodes[$nid]->webform['emails'][$eid]['extra'] = unserialize($email['extra']);
  1705. if (webform_variable_get('webform_format_override')) {
  1706. $nodes[$nid]->webform['emails'][$eid]['html'] = webform_variable_get('webform_default_format');
  1707. }
  1708. }
  1709. // Load components for each node.
  1710. $nodes[$nid]->webform['components'] = db_select('webform_component')
  1711. ->fields('webform_component')
  1712. ->condition('nid', $nid)
  1713. ->orderBy('weight')
  1714. ->orderBy('name')
  1715. ->execute()
  1716. ->fetchAllAssoc('cid', PDO::FETCH_ASSOC);
  1717. // Do a little cleanup on each component.
  1718. foreach ($nodes[$nid]->webform['components'] as $cid => $component) {
  1719. $nodes[$nid]->webform['components'][$cid]['nid'] = $nid;
  1720. $nodes[$nid]->webform['components'][$cid]['extra'] = unserialize($component['extra']);
  1721. webform_component_defaults($nodes[$nid]->webform['components'][$cid]);
  1722. }
  1723. // Organize the components into a fieldset-based order.
  1724. if (!empty($nodes[$nid]->webform['components'])) {
  1725. $component_tree = array();
  1726. $page_count = 1;
  1727. _webform_components_tree_build($nodes[$nid]->webform['components'], $component_tree, 0, $page_count);
  1728. $nodes[$nid]->webform['components'] = _webform_components_tree_flatten($component_tree['children']);
  1729. }
  1730. // Load all the conditional information, if any.
  1731. $nodes[$nid]->webform['conditionals'] = db_select('webform_conditional')
  1732. ->fields('webform_conditional')
  1733. ->condition('nid', $nid)
  1734. ->orderBy('weight')
  1735. ->execute()
  1736. ->fetchAllAssoc('rgid', PDO::FETCH_ASSOC);
  1737. if ($nodes[$nid]->webform['conditionals']) {
  1738. $rules = db_select('webform_conditional_rules')
  1739. ->fields('webform_conditional_rules')
  1740. ->condition('nid', $nid)
  1741. ->orderBy('rgid')
  1742. ->orderBy('rid')
  1743. ->execute();
  1744. foreach ($rules as $rule) {
  1745. $nodes[$nid]->webform['conditionals'][$rule->rgid]['rules'][$rule->rid] = (array) $rule;
  1746. }
  1747. $actions = db_select('webform_conditional_actions')
  1748. ->fields('webform_conditional_actions')
  1749. ->condition('nid', $nid)
  1750. ->orderBy('rgid')
  1751. ->orderBy('aid')
  1752. ->execute();
  1753. foreach ($actions as $action) {
  1754. $nodes[$nid]->webform['conditionals'][$action->rgid]['actions'][$action->aid] = (array) $action;
  1755. }
  1756. }
  1757. }
  1758. }
  1759. /**
  1760. * Implements hook_user_role_delete().
  1761. *
  1762. * Removes references to deleted role from existing webforms.
  1763. */
  1764. function webform_user_role_delete($role) {
  1765. db_delete('webform_roles')->condition('rid', $role->rid)->execute();
  1766. }
  1767. /**
  1768. * Implements hook_form_alter().
  1769. */
  1770. function webform_form_alter(&$form, $form_state, $form_id) {
  1771. if (isset($form['#node']->type) && $form_id == $form['#node']->type . '_node_form' && variable_get('webform_node_' . $form['#node']->type, FALSE)) {
  1772. $node = $form['#node'];
  1773. // Preserve all Webform options currently set on the node.
  1774. $form['webform'] = array(
  1775. '#type' => 'value',
  1776. '#value' => $node->webform,
  1777. );
  1778. // If a new node, redirect the user to the components form after save.
  1779. if (empty($node->nid) && in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
  1780. $form['actions']['submit']['#submit'][] = 'webform_form_submit';
  1781. }
  1782. }
  1783. }
  1784. /**
  1785. * Implements hook_form_BASE_FORM_ID_alter().
  1786. */
  1787. function webform_form_node_type_form_alter(&$form, $form_state) {
  1788. if (isset($form['type'])) {
  1789. $form['webform'] = array(
  1790. '#title' => t('Webform'),
  1791. '#type' => 'fieldset',
  1792. '#collapsible' => TRUE,
  1793. '#collapsed' => TRUE,
  1794. '#group' => 'additional_settings',
  1795. '#weight' => 10,
  1796. '#attached' => array(
  1797. 'js' => array(drupal_get_path('module', 'webform') . '/js/node-type-form.js'),
  1798. ),
  1799. );
  1800. $form['webform']['webform_node'] = array(
  1801. '#type' => 'checkbox',
  1802. '#title' => t('Enable webform functionality'),
  1803. '#description' => t('Allows a form to be attached to content. This will add tabs for "Webform" and "Results" on all content of this type.'),
  1804. '#weight' => 0,
  1805. '#default_value' => variable_get('webform_node_' . $form['#node_type']->type, FALSE),
  1806. '#attributes' => array(
  1807. 'data-enabled-description' => t('Enabled'),
  1808. 'data-disabled-description' => t('Disabled'),
  1809. ),
  1810. );
  1811. }
  1812. }
  1813. /**
  1814. * Submit handler for the webform node form.
  1815. *
  1816. * Redirect the user to the components form on new node inserts. Note that this
  1817. * fires after the hook_submit() function above.
  1818. */
  1819. function webform_form_submit($form, &$form_state) {
  1820. drupal_set_message(t('The new webform %title has been created. Add new fields to your webform with the form below.', array('%title' => $form_state['values']['title'])));
  1821. $form_state['redirect'] = 'node/' . $form_state['nid'] . '/webform/components';
  1822. }
  1823. /**
  1824. * Implements hook_node_view().
  1825. */
  1826. function webform_node_view($node, $view_mode) {
  1827. global $user;
  1828. if (!variable_get('webform_node_' . $node->type, FALSE)) {
  1829. return;
  1830. }
  1831. // If empty or a new node (during preview) do not display.
  1832. if (empty($node->webform['components']) || empty($node->nid)) {
  1833. return;
  1834. }
  1835. // If the webform is not set to display in this view mode, return early.
  1836. // View mode of 'form' is exempted to allow blocks and views to force display.
  1837. $extra_fields = field_extra_fields_get_display('node', $node->type, $view_mode);
  1838. if ($view_mode != 'form' && empty($extra_fields['webform']['visible'])) {
  1839. return;
  1840. }
  1841. $submission = FALSE;
  1842. $submission_count = 0;
  1843. $page = node_is_page($node);
  1844. $logging_in = FALSE;
  1845. $total_limit_exceeded = FALSE;
  1846. $user_limit_exceeded = FALSE;
  1847. $closed = FALSE;
  1848. // If a teaser, tell the form to load subsequent pages on the node page. A
  1849. // special exception is made for this view mode only.
  1850. if ($view_mode == 'teaser' && !isset($node->webform['action'])) {
  1851. $query = array_diff_key($_GET, array('q' => ''));
  1852. $node->webform['action'] = url('node/' . $node->nid, array('query' => $query));
  1853. }
  1854. // When logging in using a form on the same page as a webform node, suppress
  1855. // output messages so that they don't show up after the user has logged in.
  1856. // See http://drupal.org/node/239343.
  1857. if (isset($_POST['op']) && isset($_POST['name']) && isset($_POST['pass'])) {
  1858. $logging_in = TRUE;
  1859. }
  1860. if ($node->webform['status'] == 0) {
  1861. $closed = TRUE;
  1862. $enabled = FALSE;
  1863. $allowed_roles = array();
  1864. }
  1865. else {
  1866. // $enabled set by reference.
  1867. $allowed_roles = _webform_allowed_roles($node, $enabled);
  1868. }
  1869. // Get a count of previous submissions by this user. Note that the
  1870. // webform_submission_access() function may disable the page cache for
  1871. // anonymous users if they are allowed to edit their own submissions!
  1872. if ($page && webform_submission_access($node, NULL, 'list')) {
  1873. module_load_include('inc', 'webform', 'includes/webform.submissions');
  1874. $submission_count = webform_get_submission_count($node->nid, $user->uid);
  1875. }
  1876. // Check if this page is cached or not.
  1877. $cached = drupal_page_is_cacheable();
  1878. // Check if the user can add another submission based on the individual
  1879. // submission limit.
  1880. // -1: Submissions are never throttled.
  1881. if ($node->webform['submit_limit'] != -1) {
  1882. module_load_include('inc', 'webform', 'includes/webform.submissions');
  1883. // Disable the form if the limit is exceeded and page cache is not active.
  1884. // This prevents one anonymous user from generated a disabled webform page
  1885. // for the cache, which would be shown to other anonymous users who have not
  1886. // exceeded the limit.
  1887. // Cached should be checked first to avoid the expensive limit check on
  1888. // cached requests.
  1889. if (!$cached && ($user_limit_exceeded = webform_submission_user_limit_check($node))) {
  1890. $enabled = FALSE;
  1891. }
  1892. }
  1893. // Check if the user can add another submission if there is a limit on total
  1894. // submissions.
  1895. // -1: Submissions are never throttled.
  1896. if ($node->webform['total_submit_limit'] != -1) {
  1897. module_load_include('inc', 'webform', 'includes/webform.submissions');
  1898. // Disable the form if the limit is exceeded. The cache is irrelevant for
  1899. // the total submission limit; when it is exceeded for one user, it is
  1900. // exceeded for any other user.
  1901. if (($total_limit_exceeded = webform_submission_total_limit_check($node))) {
  1902. $enabled = FALSE;
  1903. }
  1904. }
  1905. // Check if this user has a draft for this webform.
  1906. $resume_draft = FALSE;
  1907. if (($node->webform['allow_draft'] || $node->webform['auto_save']) && $user->uid != 0) {
  1908. // Draft found - display form with draft data for further editing.
  1909. if ($draft_sid = _webform_fetch_draft_sid($node->nid, $user->uid)) {
  1910. module_load_include('inc', 'webform', 'includes/webform.submissions');
  1911. $submission = webform_get_submission($node->nid, $draft_sid);
  1912. $enabled = TRUE;
  1913. $resume_draft = TRUE;
  1914. }
  1915. }
  1916. // Avoid building the same form twice on the same page request (which can
  1917. // happen if the webform is displayed in a panel or block) because this
  1918. // causes multistep forms to build incorrectly the second time.
  1919. $cached_forms = &drupal_static(__FUNCTION__, array());
  1920. if (isset($cached_forms[$node->nid])) {
  1921. $form = $cached_forms[$node->nid];
  1922. }
  1923. // If this is the first time, generate the form array.
  1924. else {
  1925. $form = drupal_get_form('webform_client_form_' . $node->nid, $node, $submission, $resume_draft);
  1926. $cached_forms[$node->nid] = $form;
  1927. }
  1928. // Remove the surrounding <form> tag if this is a preview.
  1929. if (!empty($node->in_preview)) {
  1930. $form['#type'] = 'markup';
  1931. }
  1932. // Print out messages for the webform.
  1933. if (empty($node->in_preview) && !isset($node->webform_block) && !$logging_in) {
  1934. theme('webform_view_messages', array(
  1935. 'node' => $node,
  1936. 'page' => $page,
  1937. 'submission_count' => $submission_count,
  1938. 'user_limit_exceeded' => $user_limit_exceeded,
  1939. 'total_limit_exceeded' => $total_limit_exceeded,
  1940. 'allowed_roles' => $allowed_roles,
  1941. 'closed' => $closed,
  1942. 'cached' => $cached,
  1943. )
  1944. );
  1945. }
  1946. // Add the output to the node.
  1947. $node->content['webform'] = array(
  1948. '#theme' => 'webform_view',
  1949. '#node' => $node,
  1950. '#page' => $page,
  1951. '#form' => $form,
  1952. '#enabled' => $enabled,
  1953. '#visible' => $extra_fields['webform']['visible'],
  1954. '#weight' => 10,
  1955. );
  1956. }
  1957. /**
  1958. * Helper. Generates an array of allowed roles.
  1959. *
  1960. * @param object $node
  1961. * The loaded node object containing a webform.
  1962. * @param bool $user_is_allowed
  1963. * Reference to boolean to be set to whether the current user is allowed.
  1964. *
  1965. * @return array
  1966. * Associative array of allowed roles indexed by the role id with a boolean
  1967. * value indicating if the current user has this role.
  1968. */
  1969. function _webform_allowed_roles($node, &$user_is_allowed) {
  1970. global $user;
  1971. if ($node->webform['confidential']) {
  1972. // Confidential webform may only be submitted anonymously, including uid 1.
  1973. $user_is_allowed = user_is_anonymous();
  1974. $allowed_roles = array(DRUPAL_ANONYMOUS_RID => $user_is_allowed);
  1975. }
  1976. elseif (webform_variable_get('webform_submission_access_control')) {
  1977. // Check if the user's role can submit this webform.
  1978. $allowed_roles = array();
  1979. foreach ($node->webform['roles'] as $rid) {
  1980. $allowed_roles[$rid] = isset($user->roles[$rid]);
  1981. }
  1982. $user_is_allowed = $user->uid == 1 || array_search(TRUE, $allowed_roles);
  1983. }
  1984. else {
  1985. // If not using Webform submission access control, allow all roles.
  1986. $user_is_allowed = TRUE;
  1987. $allowed_roles = array_fill_keys(array_keys(user_roles()), TRUE);
  1988. }
  1989. return $allowed_roles;
  1990. }
  1991. /**
  1992. * Output the Webform into the node content.
  1993. *
  1994. * @param array $variables
  1995. * The variables array.
  1996. *
  1997. * @return string
  1998. * The rendered Webform.
  1999. */
  2000. function theme_webform_view(array $variables) {
  2001. // Only show the form if this user is allowed access.
  2002. if ($variables['webform']['#enabled']) {
  2003. return drupal_render($variables['webform']['#form']);
  2004. }
  2005. }
  2006. /**
  2007. * Display a message to a user if they are not allowed to fill out a form.
  2008. *
  2009. * @param array $variables
  2010. * The variables array.
  2011. */
  2012. function theme_webform_view_messages(array $variables) {
  2013. global $user;
  2014. $node = $variables['node'];
  2015. $page = $variables['page'];
  2016. $submission_count = $variables['submission_count'];
  2017. $user_limit_exceeded = $variables['user_limit_exceeded'];
  2018. $total_limit_exceeded = $variables['total_limit_exceeded'];
  2019. $allowed_roles = $variables['allowed_roles'];
  2020. $closed = $variables['closed'];
  2021. $cached = $variables['cached'];
  2022. $type = 'warning';
  2023. if ($closed) {
  2024. $message = t('Submissions for this form are closed.');
  2025. }
  2026. elseif ($node->webform['confidential'] && user_is_logged_in()) {
  2027. $message = t('This form is confidential. You must <a href="!url">Log out</a> to submit it.', array('!url' => url('user/logout', array('query' => drupal_get_destination()))));
  2028. }
  2029. // If open and not allowed to submit the form, give an explanation.
  2030. elseif (array_search(TRUE, $allowed_roles) === FALSE && $user->uid != 1) {
  2031. if (empty($allowed_roles)) {
  2032. // No roles are allowed to submit the form.
  2033. $message = t('Submissions for this form are closed.');
  2034. }
  2035. elseif ($user->uid == 0) {
  2036. // The user is anonymous, so (at least) needs to log in to view the form.
  2037. $login = url('user/login', array('query' => drupal_get_destination()));
  2038. $register = url('user/register', array('query' => drupal_get_destination()));
  2039. if (variable_get('user_register', 1) == 0) {
  2040. $message = t('You must <a href="!login">login</a> to view this form.', array('!login' => $login));
  2041. }
  2042. else {
  2043. $message = t('You must <a href="!login">login</a> or <a href="!register">register</a> to view this form.', array('!login' => $login, '!register' => $register));
  2044. }
  2045. }
  2046. else {
  2047. // The user must be some other role to submit.
  2048. $message = t('You do not have permission to view this form.');
  2049. $type = 'error';
  2050. }
  2051. }
  2052. // If the user has exceeded the limit of submissions, explain the limit.
  2053. elseif ($user_limit_exceeded && !$cached) {
  2054. if ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] > 1) {
  2055. $message = t('You have submitted this form the maximum number of times (@count).', array('@count' => $node->webform['submit_limit']));
  2056. }
  2057. elseif ($node->webform['submit_interval'] == -1 && $node->webform['submit_limit'] == 1) {
  2058. $message = t('You have already submitted this form.');
  2059. }
  2060. else {
  2061. $message = t('You may not submit another entry at this time.');
  2062. }
  2063. }
  2064. elseif ($total_limit_exceeded && !$cached) {
  2065. if ($node->webform['total_submit_interval'] == -1 && $node->webform['total_submit_limit'] > 1) {
  2066. $message = t('This form has received the maximum number of entries.');
  2067. }
  2068. else {
  2069. $message = t('You may not submit another entry at this time.');
  2070. }
  2071. }
  2072. // If the user has submitted before, give them a link to their submissions.
  2073. if ($submission_count > 0 && $node->webform['submit_notice'] == 1 && !$cached) {
  2074. if (empty($message)) {
  2075. $message = t('You have already submitted this form.');
  2076. $type = 'status';
  2077. }
  2078. $message .= ' ' . t('<a href="!url">View your previous submissions</a>.', array('!url' => url('node/' . $node->nid . '/submissions')));
  2079. }
  2080. if ($page && isset($message)) {
  2081. drupal_set_message($message, $type, FALSE);
  2082. }
  2083. }
  2084. /**
  2085. * Implements hook_mail().
  2086. */
  2087. function webform_mail($key, &$message, $params) {
  2088. $message['headers'] = array_merge($message['headers'], $params['headers']);
  2089. $message['subject'] = $params['subject'];
  2090. $message['body'][] = $params['message'];
  2091. }
  2092. /**
  2093. * Implements hook_block_info().
  2094. */
  2095. function webform_block_info() {
  2096. $blocks = array();
  2097. $webform_node_types = webform_node_types();
  2098. if (!empty($webform_node_types)) {
  2099. $query = db_select('webform', 'w')->fields('w')->fields('n', array('title'));
  2100. $query->leftJoin('node', 'n', 'w.nid = n.nid');
  2101. $query->condition('w.block', 1);
  2102. $query->condition('n.type', $webform_node_types, 'IN');
  2103. $result = $query->execute();
  2104. foreach ($result as $data) {
  2105. $blocks['client-block-' . $data->nid] = array(
  2106. 'info' => t('Webform: !title', array('!title' => $data->title)),
  2107. 'cache' => DRUPAL_NO_CACHE,
  2108. );
  2109. }
  2110. }
  2111. return $blocks;
  2112. }
  2113. /**
  2114. * Implements hook_block_view().
  2115. */
  2116. function webform_block_view($delta = '') {
  2117. // Load the block-specific configuration settings.
  2118. $webform_blocks = webform_variable_get('webform_blocks');
  2119. $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
  2120. $settings += array(
  2121. 'display' => 'form',
  2122. 'pages_block' => 1,
  2123. 'confirmation_block' => 0,
  2124. );
  2125. // Get the node ID from delta.
  2126. $nid = drupal_substr($delta, strrpos($delta, '-') + 1);
  2127. // Load node in current language.
  2128. if (module_exists('translation')) {
  2129. global $language;
  2130. if (($translations = translation_node_get_translations($nid)) && (isset($translations[$language->language]))) {
  2131. $nid = $translations[$language->language]->nid;
  2132. }
  2133. }
  2134. // The webform node to display in the block.
  2135. $node = node_load($nid);
  2136. // Return if user has no access to the webform node.
  2137. if (!node_access('view', $node)) {
  2138. return;
  2139. }
  2140. // This is a webform node block.
  2141. $node->webform_block = TRUE;
  2142. $node->webform['confirmation_block'] = $settings['confirmation_block'];
  2143. // If not displaying pages in the block, set the #action property on the form.
  2144. if ($settings['pages_block']) {
  2145. $node->webform['action'] = FALSE;
  2146. }
  2147. else {
  2148. $query = array_diff_key($_GET, array('q' => ''));
  2149. $node->webform['action'] = url('node/' . $node->nid, array('query' => $query));
  2150. }
  2151. // Generate the content of the block based on display settings.
  2152. $content = array();
  2153. if ($settings['display'] == 'form') {
  2154. webform_node_view($node, 'form');
  2155. if (isset($node->content['webform'])) {
  2156. $content = $node->content['webform'];
  2157. if (!$node->content['webform']['#visible']) {
  2158. // If the webform form is only shown in a block and not as within the
  2159. // node, remove the content from the node.
  2160. unset($node->content['webform']);
  2161. }
  2162. }
  2163. }
  2164. else {
  2165. $content = node_view($node, $settings['display']);
  2166. }
  2167. // Check for an in-block confirmation message.
  2168. if (isset($_SESSION['webform_confirmation'][$nid])) {
  2169. if ($_SESSION['webform_confirmation'][$nid]['confirmation_page']) {
  2170. // Replace form with confirmation page.
  2171. $content = array(
  2172. '#theme' => array('webform_confirmation_' . $node->nid, 'webform_confirmation'),
  2173. '#node' => $node,
  2174. '#sid' => $_SESSION['webform_confirmation'][$nid]['sid'],
  2175. );
  2176. }
  2177. elseif (strlen(trim(strip_tags($node->webform['confirmation'])))) {
  2178. // Display confirmation link drupal status messages, but in the block.
  2179. $message = webform_replace_tokens($node->webform['confirmation'],
  2180. $node,
  2181. webform_get_submission($nid, $_SESSION['webform_confirmation'][$nid]['confirmation_page']),
  2182. NULL,
  2183. $node->webform['confirmation_format']);
  2184. $content = array(
  2185. 'confirmation_message' => array(
  2186. '#markup' => "<div class=\"messages status webform-confirmation\">\n" .
  2187. '<h2 class="element-invisible">' . t('Status message') . "</h2>\n" .
  2188. $message .
  2189. "</div>\n",
  2190. '#weight' => -1,
  2191. ),
  2192. 'webform_view' => $content,
  2193. );
  2194. }
  2195. unset($_SESSION['webform_confirmation'][$nid]);
  2196. if (empty($_SESSION['webform_confirmation'])) {
  2197. unset($_SESSION['webform_confirmation']);
  2198. }
  2199. }
  2200. // Add contextual links for the webform node if they aren't already there.
  2201. if (!isset($content['#contextual_links']['node'])) {
  2202. $content['#contextual_links']['node'] = array('node', array($node->nid));
  2203. }
  2204. // Create the block, using the node title for the block title.
  2205. // Note that we render the content immediately here rather than passing back
  2206. // a renderable so that if the block is empty it is hidden.
  2207. $block = array(
  2208. 'subject' => check_plain($node->title),
  2209. 'content' => $content,
  2210. );
  2211. return $block;
  2212. }
  2213. /**
  2214. * Implements hook_block_configure().
  2215. */
  2216. function webform_block_configure($delta = '') {
  2217. $nid = str_replace('client-block-', '', $delta);
  2218. $node = node_load($nid);
  2219. // Load the block-specific configuration settings.
  2220. $webform_blocks = webform_variable_get('webform_blocks');
  2221. $settings = isset($webform_blocks[$delta]) ? $webform_blocks[$delta] : array();
  2222. $settings += array(
  2223. 'display' => 'form',
  2224. 'pages_block' => 1,
  2225. 'confirmation_block' => 0,
  2226. );
  2227. // Build a list of view modes for this node.
  2228. $entity_info = entity_get_info('node');
  2229. $view_modes = array(
  2230. 'form' => t('Form only'),
  2231. );
  2232. foreach ($entity_info['view modes'] as $view_mode_key => $view_mode_info) {
  2233. $view_modes[$view_mode_key] = $view_mode_info['label'];
  2234. }
  2235. $form = array();
  2236. $form['display'] = array(
  2237. '#type' => 'select',
  2238. '#title' => t('View mode'),
  2239. '#default_value' => $settings['display'],
  2240. '#options' => $view_modes,
  2241. '#description' => t('The view mode determines how much of the webform to show within the block. You may <a href="!view_modes">customize different view modes</a> (other than the "Form only" mode) or even create new custom view modes if either the <a href="http://drupal.org/project/entity_view_mode">Entity view modes</a> or <a href="http://drupal.org/project/ds">Display Suite</a> modules are installed.', array('!view_modes' => url('admin/structure/types/manage/' . $node->type . '/display'))),
  2242. );
  2243. $form['pages_block'] = array(
  2244. '#type' => 'radios',
  2245. '#title' => t('Multi-page handling'),
  2246. '#options' => array(
  2247. 1 => t('Display all pages inside block'),
  2248. 0 => t('Redirect to the node page after the first page'),
  2249. ),
  2250. '#default_value' => $settings['pages_block'],
  2251. '#description' => t('If your webform has multiple pages, you may change the behavior of the "Next" button. This will also affect where validation messages show up after an error.'),
  2252. );
  2253. $form['confirmation_block'] = array(
  2254. '#type' => 'radios',
  2255. '#title' => t('Confirmation message'),
  2256. '#options' => array(
  2257. 0 => t('Display as configured in the webform'),
  2258. 1 => t('Display the confirmation page in the block on the same page (no redirect)'),
  2259. ),
  2260. '#default_value' => $settings['confirmation_block'],
  2261. '#description' => t("This setting overrides the webform's configuration and redirection location settings when the webform is submitted via this block."),
  2262. );
  2263. return $form;
  2264. }
  2265. /**
  2266. * Implements hook_block_save().
  2267. */
  2268. function webform_block_save($delta = '', $edit = array()) {
  2269. // Load the previously defined block-specific configuration settings.
  2270. $settings = webform_variable_get('webform_blocks');
  2271. // Build the settings array.
  2272. $new_settings[$delta] = array(
  2273. 'display' => $edit['display'],
  2274. 'pages_block' => $edit['pages_block'],
  2275. 'confirmation_block' => $edit['confirmation_block'],
  2276. );
  2277. // We store settings for multiple blocks in just one variable
  2278. // so we merge the existing settings with the new ones before save.
  2279. variable_set('webform_blocks', array_merge($settings, $new_settings));
  2280. }
  2281. /**
  2282. * Client form generation function.
  2283. *
  2284. * If this is displaying an existing submission, pass in the $submission
  2285. * variable with the contents of the submission to be displayed.
  2286. *
  2287. * @param $form
  2288. * The current form array (always empty).
  2289. * @param $form_state
  2290. * The current form values of a submission, used in multipage webforms.
  2291. * @param object $node
  2292. * The current webform node.
  2293. * @param $submission
  2294. * An object containing information about the form submission if we're
  2295. * displaying a result.
  2296. * @param $resume_draft
  2297. * Optional. Set to TRUE when resuming a draft and skipping past previously-
  2298. * validated pages is desired.
  2299. * @param $filter
  2300. * Whether or not to filter the contents of descriptions and values when
  2301. * building the form. Values need to be unfiltered to be editable by
  2302. * Form Builder.
  2303. */
  2304. function webform_client_form($form, &$form_state, $node, $submission = FALSE, $resume_draft = FALSE, $filter = TRUE) {
  2305. global $user;
  2306. // Attach necessary JavaScript and CSS.
  2307. $form['#attached'] = array(
  2308. 'css' => array(drupal_get_path('module', 'webform') . '/css/webform.css'),
  2309. 'js' => array(drupal_get_path('module', 'webform') . '/js/webform.js'),
  2310. );
  2311. form_load_include($form_state, 'inc', 'webform', 'includes/webform.components');
  2312. form_load_include($form_state, 'inc', 'webform', 'includes/webform.submissions');
  2313. // For ajax requests, $form_state['values']['details'] is missing. Restore
  2314. // from storage, if available, for multi-page forms.
  2315. if (empty($form_state['values']['details']) && !empty($form_state['storage']['details'])) {
  2316. $form_state['values']['details'] = $form_state['storage']['details'];
  2317. }
  2318. // If in a multi-step form, a submission ID may be specified in form state.
  2319. // Load this submission. This allows anonymous users to use auto-save.
  2320. if (empty($submission) && !empty($form_state['values']['details']['sid'])) {
  2321. $submission = webform_get_submission($node->nid, $form_state['values']['details']['sid']);
  2322. }
  2323. $finished = isset($submission->is_draft) ? (!$submission->is_draft) : 0;
  2324. $submit_button_text = $finished
  2325. ? t('Save')
  2326. : (empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']));
  2327. // Bind arguments to $form to make them available in theming and form_alter.
  2328. $form['#node'] = $node;
  2329. $form['#submission'] = $submission;
  2330. $form['#is_draft'] = $submission && $submission->is_draft;
  2331. $form['#filter'] = $filter;
  2332. // Add a theme function for this form.
  2333. $form['#theme'] = array('webform_form_' . $node->nid, 'webform_form');
  2334. // Add a CSS class for all client forms.
  2335. $form['#attributes']['class'][] = 'webform-client-form';
  2336. $form['#attributes']['class'][] = 'webform-client-form-' . $node->nid;
  2337. // Sometimes when displaying a webform as a teaser or block, a custom action
  2338. // property is set to direct the user to the node page.
  2339. if (!empty($node->webform['action'])) {
  2340. $form['#action'] = $node->webform['action'];
  2341. }
  2342. $form['#submit'] = array('webform_client_form_pages', 'webform_client_form_submit');
  2343. $form['#validate'] = array('webform_client_form_validate');
  2344. // Add includes for used component types and pre/post validation handlers.
  2345. $form['#process'] = array('webform_client_form_process');
  2346. if (is_array($node->webform['components']) && !empty($node->webform['components'])) {
  2347. // Prepare a new form array.
  2348. $form['submitted'] = array(
  2349. '#tree' => TRUE,
  2350. );
  2351. $form['details'] = array(
  2352. '#tree' => TRUE,
  2353. );
  2354. // Put the components into a tree structure.
  2355. if (!isset($form_state['storage']['component_tree'])) {
  2356. $form_state['webform']['component_tree'] = array();
  2357. $form_state['webform']['page_count'] = 1;
  2358. $form_state['webform']['page_num'] = 1;
  2359. _webform_components_tree_build($node->webform['components'], $form_state['webform']['component_tree'], 0, $form_state['webform']['page_count']);
  2360. // If preview is enabled, increase the page count by one.
  2361. if ($node->webform['preview']) {
  2362. $form_state['webform']['page_count']++;
  2363. }
  2364. $form_state['webform']['preview'] = $node->webform['preview'];
  2365. // If this is the first time this draft has been restore and presented to
  2366. // the user, let them know that they are looking at a draft, rather than
  2367. // a new form. This applies to the node view page, but not to a submission
  2368. // edit page (where they presummably know what submission they are
  2369. // editing).
  2370. if ($resume_draft && empty($form_state['input'])) {
  2371. drupal_set_message(t('A partially-completed form was found. Please complete the remaining portions.'));
  2372. }
  2373. }
  2374. else {
  2375. $form_state['webform']['component_tree'] = $form_state['storage']['component_tree'];
  2376. $form_state['webform']['page_count'] = $form_state['storage']['page_count'];
  2377. $form_state['webform']['page_num'] = $form_state['storage']['page_num'];
  2378. $form_state['webform']['preview'] = $form_state['storage']['preview'];
  2379. }
  2380. // Set the input values based on whether we're editing an existing
  2381. // submission or not.
  2382. $input_values = isset($submission->data) ? $submission->data : array();
  2383. // Form state storage override any default submission information. Convert
  2384. // the value structure to always be an array, matching $submission->data.
  2385. if (isset($form_state['storage']['submitted'])) {
  2386. foreach ($form_state['storage']['submitted'] as $cid => $data) {
  2387. $input_values[$cid] = is_array($data) ? $data : array($data);
  2388. }
  2389. }
  2390. // Form state values override any default submission information. Convert
  2391. // the value structure to always be an array, matching $submission->data.
  2392. if (isset($form_state['values']['submitted'])) {
  2393. foreach ($form_state['values']['submitted'] as $cid => $data) {
  2394. $input_values[$cid] = is_array($data) ? $data : array($data);
  2395. }
  2396. }
  2397. // Generate conditional topological order & report any errors.
  2398. $sorter = webform_get_conditional_sorter($node);
  2399. $sorter->reportErrors();
  2400. // Excecute the condtionals on the current input values.
  2401. $input_values = $sorter->executeConditionals($input_values);
  2402. // Allow values from other pages to be sent to browser for conditionals.
  2403. $form['#conditional_values'] = $input_values;
  2404. // Allow components access to most up-to-date values.
  2405. $form_state['#conditional_values'] = $input_values;
  2406. // For resuming a previous draft, find the next page after the last
  2407. // validated page.
  2408. if (!isset($form_state['storage']['page_num']) && $submission && $submission->is_draft && $submission->highest_valid_page) {
  2409. // Find the:
  2410. // 1. previous/next non-empty page, or
  2411. // 2. the preview page, or
  2412. // 3. the preview page, forcing its display if the form would unexpectedly
  2413. // submit, or
  2414. // 4. page 1 even if empty, if no other previous page would be shown.
  2415. $form_state['webform']['page_num'] = $submission->highest_valid_page;
  2416. do {
  2417. $form_state['webform']['page_num']++;
  2418. } while (!webform_get_conditional_sorter($node)->pageVisibility($form_state['webform']['page_num']));
  2419. if (!$form_state['webform']['preview'] && $form_state['webform']['page_num'] == $form_state['webform']['page_count'] + (int) !$form_state['webform']['preview']) {
  2420. // Force a preview to avert an unintended submission via Next.
  2421. $form_state['webform']['preview'] = TRUE;
  2422. $form_state['webform']['page_count']++;
  2423. }
  2424. // The form hasn't been submitted (ever) and the preview code will expect
  2425. // $form_state['values']['submitted'] to be set from a previous
  2426. // submission, so provide these values here.
  2427. $form_state['values']['submitted'] = $input_values;
  2428. $form_state['storage']['submitted'] = $input_values;
  2429. }
  2430. // Shorten up our variable names.
  2431. $component_tree = $form_state['webform']['component_tree'];
  2432. $page_count = $form_state['webform']['page_count'];
  2433. $page_num = $form_state['webform']['page_num'];
  2434. $preview = $form_state['webform']['preview'];
  2435. if ($node->webform['progressbar_include_confirmation'] || $page_count > 1) {
  2436. $page_labels = webform_page_labels($node, $form_state);
  2437. $form['progressbar'] = array(
  2438. '#theme' => 'webform_progressbar',
  2439. '#node' => $node,
  2440. '#page_num' => $page_num,
  2441. '#page_count' => count($page_labels),
  2442. '#page_labels' => $page_labels,
  2443. '#weight' => -100,
  2444. );
  2445. }
  2446. // Check whether a previous submission was truncated. The length of the
  2447. // client form is not estimated before submission because a) the
  2448. // determination may not be accurate for some webform components and b) the
  2449. // error will be apparent upon submission.
  2450. webform_input_vars_check($form, $form_state, 'submitted');
  2451. // Recursively add components to the form. The unfiltered version of the
  2452. // form (typically used in Form Builder), includes all components.
  2453. foreach ($component_tree['children'] as $cid => $component) {
  2454. if ($component['type'] == 'pagebreak') {
  2455. $next_page_labels[$component['page_num'] - 1] = !empty($component['extra']['next_page_label']) ? t($component['extra']['next_page_label']) : t('Next Page >');
  2456. $prev_page_labels[$component['page_num']] = !empty($component['extra']['prev_page_label']) ? t($component['extra']['prev_page_label']) : t('< Previous Page');
  2457. }
  2458. if (!$filter || $sorter->componentVisibility($cid, $page_num)) {
  2459. $component_value = isset($input_values[$cid]) ? $input_values[$cid] : NULL;
  2460. _webform_client_form_add_component($node, $component, $component_value, $form['submitted'], $form, $input_values, 'form', $page_num, $filter);
  2461. }
  2462. }
  2463. if ($preview) {
  2464. $next_page_labels[$page_count - 1] = $node->webform['preview_next_button_label'] ? t($node->webform['preview_next_button_label']) : t('Preview');
  2465. $prev_page_labels[$page_count] = $node->webform['preview_prev_button_label'] ? t($node->webform['preview_prev_button_label']) : t('< Previous');
  2466. }
  2467. // Add the preview if needed.
  2468. if ($preview && $page_num === $page_count) {
  2469. $preview_submission = webform_submission_create($node, $user, $form_state, TRUE, $submission);
  2470. $preview_message = $node->webform['preview_message'];
  2471. if (strlen(trim(strip_tags($preview_message))) === 0) {
  2472. $preview_message = t('Please review your submission. Your submission is not complete until you press the "!button" button!', array('!button' => $submit_button_text));
  2473. }
  2474. $form['preview_message'] = array(
  2475. '#type' => 'markup',
  2476. '#markup' => webform_replace_tokens($preview_message, $node, $preview_submission, NULL, $node->webform['preview_message_format']),
  2477. );
  2478. $form['preview'] = webform_submission_render($node, $preview_submission, NULL, 'html', $node->webform['preview_excluded_components']);
  2479. $form['#attributes']['class'][] = 'preview';
  2480. }
  2481. // These form details help managing data upon submission.
  2482. $form['details']['nid'] = array(
  2483. '#type' => 'value',
  2484. '#value' => $node->nid,
  2485. );
  2486. $form['details']['sid'] = array(
  2487. '#type' => 'hidden',
  2488. '#value' => isset($submission->sid) ? $submission->sid : NULL,
  2489. );
  2490. $form['details']['uid'] = array(
  2491. '#type' => 'value',
  2492. '#value' => isset($submission->uid) ? $submission->uid : $user->uid,
  2493. );
  2494. $form['details']['page_num'] = array(
  2495. '#type' => 'hidden',
  2496. '#value' => $page_num,
  2497. );
  2498. $form['details']['page_count'] = array(
  2499. '#type' => 'hidden',
  2500. '#value' => $page_count,
  2501. );
  2502. $form['details']['finished'] = array(
  2503. '#type' => 'hidden',
  2504. '#value' => $finished,
  2505. );
  2506. // Add process functions to remove the IDs forced upon buttons and wrappers.
  2507. $actions_pre_render = array_merge(element_info_property('actions', '#pre_render', array()), array('webform_pre_render_remove_id'));
  2508. $buttons_pre_render = array_merge(element_info_property('submit', '#pre_render', array()), array('webform_pre_render_remove_id'));
  2509. // Add buttons for pages, drafts, and submissions.
  2510. $form['actions'] = array(
  2511. '#type' => 'actions',
  2512. '#weight' => 1000,
  2513. '#pre_render' => $actions_pre_render,
  2514. );
  2515. // Add the draft button.
  2516. if ($node->webform['allow_draft'] && (empty($submission) || $submission->is_draft) && $user->uid != 0) {
  2517. $form['actions']['draft'] = array(
  2518. '#type' => 'submit',
  2519. '#value' => t('Save Draft'),
  2520. '#weight' => -2,
  2521. // Prevalidation only; no element validation for Save Draft.
  2522. '#validate' => array('webform_client_form_prevalidate'),
  2523. '#attributes' => array(
  2524. 'formnovalidate' => 'formnovalidate',
  2525. 'class' => array('webform-draft'),
  2526. ),
  2527. '#pre_render' => $buttons_pre_render,
  2528. );
  2529. }
  2530. // Add the submit button(s).
  2531. if ($page_num > 1) {
  2532. $form['actions']['previous'] = array(
  2533. '#type' => 'submit',
  2534. '#value' => $prev_page_labels[$page_num],
  2535. '#weight' => 5,
  2536. '#validate' => array(),
  2537. '#attributes' => array(
  2538. 'formnovalidate' => 'formnovalidate',
  2539. 'class' => array('webform-previous'),
  2540. ),
  2541. '#pre_render' => $buttons_pre_render,
  2542. );
  2543. }
  2544. if ($page_num == $page_count) {
  2545. $form['actions']['submit'] = array(
  2546. '#type' => 'submit',
  2547. '#value' => $submit_button_text,
  2548. '#weight' => 10,
  2549. '#attributes' => array(
  2550. 'class' => array('webform-submit', 'button-primary'),
  2551. ),
  2552. '#pre_render' => $buttons_pre_render,
  2553. );
  2554. }
  2555. elseif ($page_num < $page_count) {
  2556. $form['actions']['next'] = array(
  2557. '#type' => 'submit',
  2558. '#value' => $next_page_labels[$page_num],
  2559. '#weight' => 10,
  2560. '#attributes' => array(
  2561. 'class' => array('webform-next', 'button-primary'),
  2562. ),
  2563. '#pre_render' => $buttons_pre_render,
  2564. );
  2565. }
  2566. }
  2567. return $form;
  2568. }
  2569. /**
  2570. * Process function for webform_client_form().
  2571. *
  2572. * Include all the enabled components for this form to ensure availability.
  2573. * Also adds the pre- and post-validators to ensure that hook_form_alters don't
  2574. * add their validation functions in the wrong order.
  2575. */
  2576. function webform_client_form_process($form, $form_state) {
  2577. $components = webform_components();
  2578. foreach ($components as $component_type => $component) {
  2579. webform_component_include($component_type);
  2580. }
  2581. // Add the post validation to end of validators. Do this first on the off
  2582. // chance that an _alter function has unset form['#validate'].
  2583. $form['#validate'][] = 'webform_client_form_postvalidate';
  2584. // Add the pre-validator to the front of the list to run first.
  2585. array_unshift($form['#validate'], 'webform_client_form_prevalidate');
  2586. return $form;
  2587. }
  2588. /**
  2589. * Add a component to a renderable array. Called recursively for fieldsets.
  2590. *
  2591. * This function assists in the building of the client form, as well as the
  2592. * display of results, and the text of e-mails.
  2593. *
  2594. * @param object $node
  2595. * The current webform node.
  2596. * @param $component
  2597. * The component to be added to the form.
  2598. * @param $component_value
  2599. * The components current value if known.
  2600. * @param $parent_fieldset
  2601. * The fieldset to which this element will be added.
  2602. * @param $form
  2603. * The entire form array.
  2604. * @param $input_values
  2605. * All the values for this form, keyed by the component IDs. This may be
  2606. * pulled from $form_state['values']['submitted'] or $submission->data.
  2607. * These values are used to check if the component should be displayed
  2608. * conditionally.
  2609. * @param $format
  2610. * The format the form should be displayed as. May be one of the following:
  2611. * - form: Show as an editable form.
  2612. * - html: Show as HTML results.
  2613. * - text: Show as plain text.
  2614. * @param $page_num
  2615. * The page number. Defaults to 0.
  2616. * @param $filter
  2617. * Whether the form element properties should be filtered. Only set to FALSE
  2618. * if needing the raw properties for editing.
  2619. *
  2620. * @see webform_client_form()
  2621. * @see webform_submission_render()
  2622. */
  2623. function _webform_client_form_add_component($node, $component, $component_value, &$parent_fieldset, &$form, $input_values, $format = 'form', $page_num = 0, $filter = TRUE) {
  2624. $cid = $component['cid'];
  2625. $component_access = empty($component['extra']['private']) || webform_results_access($node);
  2626. // Load with submission information if necessary.
  2627. if ($format != 'form') {
  2628. // This component is display only.
  2629. $data = empty($input_values[$cid]) ? NULL : $input_values[$cid];
  2630. if ($display_element = webform_component_invoke($component['type'], 'display', $component, $data, $format, $form['#submission'])) {
  2631. // Set access based on the private property.
  2632. $display_element += array('#access' => TRUE);
  2633. $display_element['#access'] = $display_element['#access'] && $component_access;
  2634. // Ensure the component is added as a property.
  2635. $display_element['#webform_component'] = $component;
  2636. // Add custom CSS classes to the field and wrapper.
  2637. _webform_component_classes($display_element, $component);
  2638. // Allow modules to modify a "display only" webform component.
  2639. drupal_alter('webform_component_display', $display_element, $component);
  2640. // The form_builder() function usually adds #parents and #id for us, but
  2641. // because these are not marked for #input, we need to add them manually.
  2642. if (!isset($display_element['#parents'])) {
  2643. $parents = isset($parent_fieldset['#parents']) ? $parent_fieldset['#parents'] : array('submitted');
  2644. $parents[] = $component['form_key'];
  2645. $display_element['#parents'] = $parents;
  2646. }
  2647. if (!isset($display_element['#id'])) {
  2648. $display_element['#id'] = drupal_clean_css_identifier('edit-' . implode('-', $display_element['#parents']));
  2649. }
  2650. // Add the element into the proper parent in the display.
  2651. $parent_fieldset[$component['form_key']] = $display_element;
  2652. }
  2653. }
  2654. // Show the component only on its form page, or if building an unfiltered
  2655. // version of the form (such as for Form Builder).
  2656. elseif ($component['page_num'] == $page_num || $filter == FALSE) {
  2657. // Add this user-defined field to the form (with all the values that are
  2658. // always available).
  2659. if ($element = webform_component_invoke($component['type'], 'render', $component, $component_value, $filter, $form['#submission'])) {
  2660. // Set access based on the private property.
  2661. $element += array('#access' => TRUE);
  2662. $element['#access'] = $element['#access'] && $component_access;
  2663. // Ensure the component is added as a property.
  2664. $element['#webform_component'] = $component;
  2665. // The 'private' option is in most components, but it's not a real
  2666. // property. Add it for Form Builder compatibility.
  2667. if (webform_component_feature($component['type'], 'private')) {
  2668. $element['#webform_private'] = $component['extra']['private'];
  2669. }
  2670. // The 'placeholder' option is in some components, but it's not a real
  2671. // property. Add it for Form Builder compatibility.
  2672. if (webform_component_feature($component['type'], 'placeholder')) {
  2673. $element['#webform_placeholder'] = $component['extra']['placeholder'];
  2674. }
  2675. // Add custom CSS classes to the field and wrapper.
  2676. _webform_component_classes($element, $component);
  2677. // Allow modules to modify a webform component that is going to be render
  2678. // in a form.
  2679. drupal_alter('webform_component_render', $element, $component);
  2680. // Add the element into the proper parent in the form.
  2681. $parent_fieldset[$component['form_key']] = $element;
  2682. }
  2683. else {
  2684. drupal_set_message(t('The webform component @type is not able to be displayed', array('@type' => $component['type'])));
  2685. }
  2686. }
  2687. // Disable validation initially on all elements. We manually validate
  2688. // all webform elements in webform_client_form_validate().
  2689. if (isset($parent_fieldset[$component['form_key']])) {
  2690. $parent_fieldset[$component['form_key']]['#validated'] = TRUE;
  2691. $parent_fieldset[$component['form_key']]['#webform_validated'] = FALSE;
  2692. }
  2693. if (isset($component['children']) && is_array($component['children'])) {
  2694. $sorter = webform_get_conditional_sorter($node);
  2695. foreach ($component['children'] as $scid => $subcomponent) {
  2696. $subcomponent_value = isset($input_values[$scid]) ? $input_values[$scid] : NULL;
  2697. // Include if always shown, or for forms, also if currently hidden but
  2698. // might be shown due to conditionals.
  2699. $visibility = $sorter->componentVisibility($scid, $subcomponent['page_num']);
  2700. if ($visibility == WebformConditionals::componentShown || ($format == 'form' && $visibility) || !$filter) {
  2701. _webform_client_form_add_component($node, $subcomponent, $subcomponent_value, $parent_fieldset[$component['form_key']], $form, $input_values, $format, $page_num, $filter);
  2702. }
  2703. }
  2704. }
  2705. }
  2706. /**
  2707. * Validates that the form can still be submitted, saved as draft, or edited.
  2708. *
  2709. * Because forms may be submitted from cache or the webform changed while the
  2710. * submission is in progress, the conditions to allow the form are re-checked
  2711. * upon form submission.
  2712. */
  2713. function webform_client_form_prevalidate($form, &$form_state) {
  2714. // Refresh the node in case it changed since the form was build and retrieved
  2715. // from cache.
  2716. $node = $form['#node'] = node_load($form['#node']->nid);
  2717. $finished = $form_state['values']['details']['finished'];
  2718. // Check if the user is allowed to submit based on role. This check is
  2719. // repeated here to ensure the user is still logged in at the time of
  2720. // submission, otherwise a stale form in another window may be allowed.
  2721. // $allowed_role set by reference.
  2722. $allowed_roles = _webform_allowed_roles($node, $allowed_role);
  2723. // Check that the submissions have not exceeded the total submission limit.
  2724. $total_limit_exceeded = FALSE;
  2725. if ($node->webform['total_submit_limit'] != -1 && !$finished) {
  2726. $total_limit_exceeded = webform_submission_total_limit_check($node);
  2727. }
  2728. // Check that the user has not exceeded the submission limit.
  2729. // This usually will only apply to anonymous users when the page cache is
  2730. // enabled, because they may submit the form even if they do not have access.
  2731. $user_limit_exceeded = FALSE;
  2732. if ($node->webform['submit_limit'] != -1 && !$finished) {
  2733. $user_limit_exceeded = webform_submission_user_limit_check($node);
  2734. }
  2735. // Check that the form is still open at time of submission.
  2736. // See https://www.drupal.org/node/2317273
  2737. // Consider the webform closed when it's status is closed AND either there
  2738. // is no submission yet (hence isn't being edited) or the user isn't an admin.
  2739. // Another way to consider this is that the form is open when its status is
  2740. // open OR there is a submission and the user is an admin.
  2741. $closed = empty($node->webform['status']) && (
  2742. empty($form['#submission']) ||
  2743. !user_access('edit all webform submissions')
  2744. );
  2745. // Prevent submission by throwing an error.
  2746. if ((!$allowed_role || $total_limit_exceeded || $user_limit_exceeded || $closed)) {
  2747. theme('webform_view_messages', array('node' => $node, 'page' => 1, 'submission_count' => 0, 'user_limit_exceeded' => $user_limit_exceeded, 'total_limit_exceeded' => $total_limit_exceeded, 'allowed_roles' => $allowed_roles, 'closed' => $closed, 'cached' => FALSE));
  2748. form_set_error('', NULL);
  2749. }
  2750. }
  2751. /**
  2752. * Form API #validate handler for the webform_client_form() form.
  2753. */
  2754. function webform_client_form_validate($form, &$form_state) {
  2755. if (($errors = form_get_errors()) && array_key_exists('', $errors)) {
  2756. // Prevalidation failed. The form cannot be submitted. Do not attemp futher
  2757. // validation.
  2758. return;
  2759. }
  2760. if ($form_state['webform']['preview'] && $form_state['webform']['page_count'] === $form_state['webform']['page_num']) {
  2761. // Form has already passed validation and is on the preview page.
  2762. return;
  2763. }
  2764. module_load_include('inc', 'webform', 'includes/webform.submissions');
  2765. $node = $form['#node'];
  2766. // Assemble an array of all past and new input values that will determine if
  2767. // certain elements need validation at all.
  2768. if (!empty($node->webform['conditionals'])) {
  2769. $input_values = isset($form_state['storage']['submitted']) ? $form_state['storage']['submitted'] : array();
  2770. $new_values = isset($form_state['values']['submitted']) ? _webform_client_form_submit_flatten($form['#node'], $form_state['values']['submitted']) : array();
  2771. foreach ($new_values as $cid => $values) {
  2772. $input_values[$cid] = $values;
  2773. }
  2774. // Ensure that all conditionally-hidden values are removed.
  2775. $input_values = webform_get_conditional_sorter($node)->executeConditionals($input_values, $form_state['webform']['page_num']);
  2776. }
  2777. else {
  2778. $input_values = NULL;
  2779. }
  2780. // Run all #element_validate and #required checks. These are skipped initially
  2781. // by setting #validated = TRUE on all components when they are added.
  2782. _webform_client_form_validate($form, $form_state, 'webform_client_form', $input_values);
  2783. }
  2784. /**
  2785. * Recursive validation function to trigger normal Drupal validation.
  2786. *
  2787. * This function imitates _form_validate in Drupal's form.inc, only it sets
  2788. * a different property to ensure that validation has occurred.
  2789. */
  2790. function _webform_client_form_validate(&$elements, &$form_state, $form_id = NULL, $input_values = NULL) {
  2791. if (isset($input_values) && isset($elements['#webform_component'])) {
  2792. $sorter = webform_get_conditional_sorter($form_state['complete form']['#node']);
  2793. $cid = $elements['#webform_component']['cid'];
  2794. $page_num = $form_state['values']['details']['page_num'];
  2795. // Webform-specific enhancements:
  2796. // 1. Only validate the field if it was used in this submission.
  2797. // This both skips validation on the field and sets the value of the
  2798. // field to NULL, preventing any dangerous input. Short-circuit
  2799. // validation for a hidden component (hidden by rules dependent upon
  2800. // component on previous pages), or a component this is dependent upon
  2801. // values on the current page, but is hidden based upon their current
  2802. // values.
  2803. // 2. Only validate if the field has not been set by conditionals.
  2804. // The user will be unable to fix the validation without surmising the
  2805. // logic and changing the trigger for the conditional. Also, it isn't
  2806. // possible to set $element['#value'] without component-specific
  2807. // knowledge of how the data is stored because $input_values is already
  2808. // webform-normalized to contain values in arrays.
  2809. if ($sorter->componentVisibility($cid, $page_num) != WebformConditionals::componentShown) {
  2810. form_set_value($elements, NULL, $form_state);
  2811. return;
  2812. }
  2813. if ($sorter->componentSet($cid, $page_num)) {
  2814. $component = $elements['#webform_component'];
  2815. $value = $input_values[$cid];
  2816. $value = is_array($value) ? $value[0] : $value;
  2817. // webform_component_invoke cannot be called with reference arguments.
  2818. // Call directly.
  2819. // webform_component_invoke($component['type'], 'action_set', $component,
  2820. // $elements, $form_state, $value);.
  2821. $function = '_webform_action_set_' . $component['type'];
  2822. $function($component, $elements, $form_state, $value);
  2823. }
  2824. // Check for changes in required status made by conditionals.
  2825. $required = $sorter->componentRequired($cid, $page_num);
  2826. if (isset($required)) {
  2827. $elements['#required'] = $required;
  2828. // Some components, for example, grids, have nested sub-elements. Extend
  2829. // required to any sub-components.
  2830. foreach (element_children($elements) as $key) {
  2831. if (isset($elements[$key]) && $elements[$key] && !isset($elements[$key]['#webform_component'])) {
  2832. // Child is *not* a component.
  2833. $elements[$key]['#required'] = $required;
  2834. }
  2835. }
  2836. }
  2837. }
  2838. // Recurse through all children.
  2839. foreach (element_children($elements) as $key) {
  2840. if (isset($elements[$key]) && $elements[$key]) {
  2841. _webform_client_form_validate($elements[$key], $form_state, NULL, $input_values);
  2842. }
  2843. }
  2844. // Validate the current input.
  2845. if (isset($elements['#webform_validated']) && !$elements['#webform_validated']) {
  2846. if (isset($elements['#needs_validation'])) {
  2847. // Make sure a value is passed when the field is required.
  2848. // A simple call to empty() will not cut it here as some fields, like
  2849. // checkboxes, can return a valid value of 0. Instead, check the
  2850. // length if it's a string, and if it's an array whether it is empty. For
  2851. // radios, FALSE means that no value was submitted, so check that too.
  2852. $value_is_empty_string = is_string($elements['#value']) && strlen(trim($elements['#value'])) === 0;
  2853. $value_is_empty_array = is_array($elements['#value']) && !$elements['#value'];
  2854. if ($elements['#required'] && ($value_is_empty_string || $value_is_empty_array || $elements['#value'] === FALSE || $elements['#value'] === NULL)) {
  2855. form_error($elements, t('!name field is required.', array('!name' => $elements['#title'])));
  2856. }
  2857. // Verify that the value is not longer than #maxlength.
  2858. if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
  2859. 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']))));
  2860. }
  2861. // Verify that the value is not shorter than #minlength. The value may
  2862. // still be empty (required is a separate validation option).
  2863. if (isset($elements['#minlength'])) {
  2864. $length = drupal_strlen($elements['#value']);
  2865. if ($length > 0 && $length < $elements['#minlength']) {
  2866. form_error($elements, t('!name cannot be shorter than %min characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%min' => $elements['#minlength'], '%length' => drupal_strlen($elements['#value']))));
  2867. }
  2868. }
  2869. if (isset($elements['#options']) && isset($elements['#value'])) {
  2870. if ($elements['#type'] == 'select') {
  2871. $options = form_options_flatten($elements['#options']);
  2872. }
  2873. else {
  2874. $options = $elements['#options'];
  2875. }
  2876. if (is_array($elements['#value'])) {
  2877. $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
  2878. foreach ($value as $v) {
  2879. if (!isset($options[$v])) {
  2880. form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
  2881. watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  2882. }
  2883. }
  2884. }
  2885. elseif ($elements['#value'] !== '' && !isset($options[$elements['#value']])) {
  2886. form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
  2887. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  2888. }
  2889. }
  2890. }
  2891. // Call user-defined form level validators.
  2892. if (isset($form_id)) {
  2893. form_execute_handlers('validate', $elements, $form_state);
  2894. }
  2895. // Call any element-specific validators. These must act on the element
  2896. // #value data.
  2897. elseif (isset($elements['#element_validate'])) {
  2898. foreach ($elements['#element_validate'] as $function) {
  2899. if (is_callable($function)) {
  2900. $function($elements, $form_state, $form_state['complete form']);
  2901. }
  2902. }
  2903. }
  2904. $elements['#webform_validated'] = TRUE;
  2905. }
  2906. }
  2907. /**
  2908. * Saves submissions that fail validation as drafts.
  2909. *
  2910. * When a user attempts to submit an unfinished form and auto-save is allowed,
  2911. * automatically save the form as a draft to allow the user to complete the
  2912. * form later. This prevents the common failure of a user trying to submit a
  2913. * form and not noticing validation errors. The user then leaves the page
  2914. * without realizing that the form hasn't been submitted.
  2915. *
  2916. * THEORY OF OPERATION:
  2917. * The Drupal 7 Form API lacks an easy way to rebuild the form in the event of
  2918. * validation errors. The operations is thus:
  2919. *
  2920. * 1) The form is first displayed. If it is an existing draft,
  2921. * webform_client_form will generated a form to edit the draft submission.
  2922. * Otherwise it creates a form for a new, empty submission. As usual.
  2923. * 2) The submit button is pressed. The form is retrieved from cache or is
  2924. * recreated by webform_client_form. The values from the $_POST are merged in
  2925. * and the validation routines are called. As usual.
  2926. * 3) The postvalidation routine, below, detects that validation errors should
  2927. * be autosaved and calls the submit handlers on a copy of the form and
  2928. * form_state. This creates the submission, or saves to the existing
  2929. * submission. The original form and form_state are not modified (yet).
  2930. * 4) If a new submission was created, the form and form_state are updated with
  2931. * the newly-created sid of the submission, which is returned to the
  2932. * browser in the hidden field [details][sid]. The form is set to not be
  2933. * cached, and any existing cached copy is cleared to force step 5. The form
  2934. * is presented with validation errors as usual.
  2935. * 5) When the form is submitted again, the form must be rebuilt because it is
  2936. * not in the cache. The existing draft detection in _webform_fetch_draft_sid
  2937. * detects that a webform draft is being submitted, and uses its sid in
  2938. * preference to any other stored draft sid in the database. In the event
  2939. * that multiple drafts are being implemented by another module, this ensures
  2940. * that the correct draft is edited.
  2941. * 6) Repeat from step 2 until the form is abandoned (leaving the draft) or
  2942. * successfully submitted.
  2943. */
  2944. function webform_client_form_postvalidate(&$form, &$form_state) {
  2945. $errors = form_get_errors();
  2946. $nid = $form_state['values']['details']['nid'];
  2947. $node = node_load($nid);
  2948. if (user_is_logged_in() &&
  2949. $errors && !array_key_exists('', $errors) &&
  2950. $node->webform['auto_save'] &&
  2951. !$form_state['values']['details']['finished'] &&
  2952. !empty($form_state['values']['op'])) {
  2953. // Validation errors are present, prevalidation succeeded (for example
  2954. // submission limits are ok), auto-save is enabled, this form isn't finished
  2955. // (this is, is or soon will be a draft) and a button was pushed (not ajax).
  2956. //
  2957. // Process submission on a copy of the form and form_state to prevent the
  2958. // submission handlers from making unintended changes. Use a button that
  2959. // isn't Save Draft, Next Page, Submit, etc to avoid triggering any
  2960. // unwanted side effects.
  2961. $submit_form = $form;
  2962. $submit_form_state = $form_state;
  2963. $submit_form_state['values']['op'] = '__AUTOSAVE__';
  2964. form_execute_handlers('submit', $submit_form, $submit_form_state);
  2965. $sid = $submit_form_state['values']['details']['sid'];
  2966. if ($sid != $form_state['values']['details']['sid']) {
  2967. // A new submission was created. Update the form and form_state as if it
  2968. // has been submitted with the new sid. This causes the Form API to
  2969. // render the form with new sid.
  2970. $form_state['values']['details']['sid'] = $sid;
  2971. $form_state['input']['details']['sid'] = $sid;
  2972. $form['details']['sid']['#value'] = $sid;
  2973. // Prevent the form from being cached, forcing it to be rebuilt from the
  2974. // form definition function, which will honor the new sid.
  2975. $form_state['no_cache'] = TRUE;
  2976. if (!empty($form_state['values']['form_build_id'])) {
  2977. cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
  2978. cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
  2979. }
  2980. }
  2981. }
  2982. }
  2983. /**
  2984. * Handle the processing of pages and conditional logic.
  2985. */
  2986. function webform_client_form_pages($form, &$form_state) {
  2987. $node = node_load($form_state['values']['details']['nid']);
  2988. // Multistep forms may not have any components on the first page.
  2989. if (!isset($form_state['values']['submitted'])) {
  2990. $form_state['values']['submitted'] = array();
  2991. }
  2992. // Move special settings to storage.
  2993. if (isset($form_state['webform']['component_tree'])) {
  2994. $form_state['storage']['component_tree'] = $form_state['webform']['component_tree'];
  2995. $form_state['storage']['page_count'] = $form_state['webform']['page_count'];
  2996. $form_state['storage']['page_num'] = $form_state['webform']['page_num'];
  2997. $form_state['storage']['preview'] = $form_state['webform']['preview'];
  2998. }
  2999. // Flatten trees within the submission.
  3000. $form_state['values']['submitted'] = _webform_client_form_submit_flatten($node, $form_state['values']['submitted']);
  3001. // Perform post processing by components.
  3002. _webform_client_form_submit_process($node, $form_state['values']['submitted']);
  3003. // Assume the form is completed unless the page logic says otherwise.
  3004. $form_state['webform_completed'] = TRUE;
  3005. // Merge any stored submission data for multistep forms.
  3006. $original_values = is_array($form_state['values']['submitted']) ? $form_state['values']['submitted'] : array();
  3007. if (isset($form_state['storage']['submitted'])) {
  3008. // Array + operator keeps all elements of left operand and discards any
  3009. // duplicate elements in right operand.
  3010. $original_values += $form_state['storage']['submitted'];
  3011. }
  3012. // Execute conditionals on submission values.
  3013. $form_state['values']['submitted'] = webform_get_conditional_sorter($node)->executeConditionals($original_values);
  3014. // Check for a multi-page form that is not yet complete.
  3015. $submit_op = !empty($form['actions']['submit']['#value']) ? $form['actions']['submit']['#value'] : t('Submit');
  3016. $draft_op = !empty($form['actions']['draft']['#value']) ? $form['actions']['draft']['#value'] : t('Save Draft');
  3017. if (!in_array($form_state['values']['op'], array($submit_op, $draft_op, '__AUTOSAVE__'))) {
  3018. // Store values from the current page in the form state storage.
  3019. $form_state['storage']['submitted'] = $form_state['values']['submitted'];
  3020. // Set the page number.
  3021. if (!isset($form_state['storage']['page_num'])) {
  3022. $form_state['storage']['page_num'] = 1;
  3023. }
  3024. if (end($form_state['clicked_button']['#parents']) == 'next') {
  3025. $forward = 1;
  3026. }
  3027. elseif (end($form_state['clicked_button']['#parents']) == 'previous') {
  3028. $forward = -1;
  3029. }
  3030. $current_page = $form_state['storage']['page_num'];
  3031. if (isset($forward)) {
  3032. // Find the:
  3033. // 1. previous/next non-empty page, or
  3034. // 2. the preview page, or
  3035. // 3. the preview page, forcing its display if the form would unexpectedly
  3036. // submit, or
  3037. // 4. page 1 even if empty, if no other previous page would be shown.
  3038. $preview_page_num = $form_state['storage']['page_count'] + (int) !$form_state['webform']['preview'];
  3039. $page_num = $current_page;
  3040. do {
  3041. $page_num += $forward;
  3042. } while (!webform_get_conditional_sorter($node)->pageVisibility($page_num));
  3043. if (!$form_state['webform']['preview'] && $page_num == $preview_page_num) {
  3044. // Force a preview to avert an unintended submission via Next.
  3045. $form_state['webform']['preview'] = TRUE;
  3046. $form_state['storage']['preview'] = TRUE;
  3047. $form_state['storage']['page_count']++;
  3048. }
  3049. $form_state['storage']['page_num'] = $page_num;
  3050. }
  3051. // The form is done if the page number is greater than the page count.
  3052. $form_state['webform_completed'] = $form_state['storage']['page_num'] > $form_state['storage']['page_count'];
  3053. }
  3054. // Inform the submit handlers that a draft will be saved.
  3055. $form_state['save_draft'] = in_array($form_state['values']['op'], array($draft_op, '__AUTOSAVE__')) || ($node->webform['auto_save'] && !$form_state['values']['details']['finished'] && !$form_state['webform_completed'] && user_is_logged_in());
  3056. // Determine what we need to do on the next page.
  3057. if (!empty($form_state['save_draft']) || !$form_state['webform_completed']) {
  3058. // Rebuild the form and display the current (on drafts) or next page.
  3059. $form_state['rebuild'] = TRUE;
  3060. }
  3061. else {
  3062. // Remove the form state storage now that we're done with the pages.
  3063. $form_state['rebuild'] = FALSE;
  3064. unset($form_state['storage']);
  3065. }
  3066. }
  3067. /**
  3068. * Submit handler for saving the form values and sending e-mails.
  3069. */
  3070. function webform_client_form_submit($form, &$form_state) {
  3071. module_load_include('inc', 'webform', 'includes/webform.submissions');
  3072. module_load_include('inc', 'webform', 'includes/webform.components');
  3073. global $user;
  3074. if (empty($form_state['save_draft']) && empty($form_state['webform_completed'])) {
  3075. return;
  3076. }
  3077. $node = $form['#node'];
  3078. $sid = $form_state['values']['details']['sid'] ? (int) $form_state['values']['details']['sid'] : NULL;
  3079. // Check if user is submitting as a draft.
  3080. $is_draft = (int) !empty($form_state['save_draft']);
  3081. // To maintain time and user information, load the existing submission.
  3082. // If a draft is deleted while a user is working on completing it, $sid will
  3083. // exist, but webform_get_submission() will not find the draft. So, make a new
  3084. // submission.
  3085. if ($sid && $submission = webform_get_submission($node->webform['nid'], $sid)) {
  3086. // Store original data on object for use in update hook.
  3087. $submission->original = clone $submission;
  3088. // Merge with new submission data. The + operator maintains numeric keys.
  3089. // This maintains existing data with just-submitted data when a user resumes
  3090. // a submission previously saved as a draft. Remove any existing data on
  3091. // this and previous pages. If components are hidden, they may be in the
  3092. // $submission->data but absent entirely from $new_data.
  3093. $page_map = webform_get_conditional_sorter($node)->getPageMap();
  3094. for ($page_nr = 1; $page_nr <= $form_state['webform']['page_num']; $page_nr++) {
  3095. $submission->data = array_diff_key($submission->data, $page_map[$page_nr]);
  3096. }
  3097. $submission->data = webform_submission_data($node, $form_state['values']['submitted']) + $submission->data;
  3098. }
  3099. else {
  3100. // Create a new submission object.
  3101. $submission = webform_submission_create($node, $user, $form_state);
  3102. // Since this is a new submission, a new sid is needed.
  3103. $sid = NULL;
  3104. }
  3105. // Save draft state, and for drafts, save the current page (if clicking next)
  3106. // or the previous page (if not) as the last valid page.
  3107. $submission->is_draft = $is_draft;
  3108. $submission->highest_valid_page = 0;
  3109. if ($is_draft) {
  3110. $submission->highest_valid_page = end($form_state['clicked_button']['#parents']) == 'next' && $form_state['values']['op'] != '__AUTOSAVE__'
  3111. ? $form_state['webform']['page_num']
  3112. : $form_state['webform']['page_num'] - 1;
  3113. }
  3114. // If there is no data to be saved (such as on a multipage form with no fields
  3115. // on the first page), process no further. Submissions with no data cannot
  3116. // be loaded from the database as efficiently, so we don't save them at all.
  3117. if (empty($submission->data)) {
  3118. return;
  3119. }
  3120. // Save the submission to the database.
  3121. if (!$sid) {
  3122. // No sid was found thus insert it in the dataabase.
  3123. $form_state['values']['details']['sid'] = $sid = webform_submission_insert($node, $submission);
  3124. $form_state['values']['details']['is_new'] = TRUE;
  3125. // Save the new details in storage. When ajax calls for file upload/remove,
  3126. // $form_state['values']['details'] is missing. This allows the proper
  3127. // submission to be retrieved in webform_client_form. See #2562703.
  3128. $form_state['storage']['details'] = $form_state['values']['details'];
  3129. // Set a cookie including the server's submission time. The cookie expires
  3130. // in the length of the interval plus a day to compensate for timezones.
  3131. $tracking_mode = webform_variable_get('webform_tracking_mode');
  3132. if ($tracking_mode === 'cookie' || $tracking_mode === 'strict') {
  3133. $cookie_name = 'webform-' . $node->nid;
  3134. $time = REQUEST_TIME;
  3135. $params = session_get_cookie_params();
  3136. setcookie($cookie_name . '[' . $time . ']', $time, $time + $node->webform['submit_interval'] + 86400, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
  3137. }
  3138. // Save session information about this submission for anonymous users,
  3139. // allowing them to access or edit their submissions.
  3140. if (!$user->uid && user_access('access own webform submissions')) {
  3141. $_SESSION['webform_submission'][$sid] = $node->nid;
  3142. }
  3143. }
  3144. else {
  3145. // Sid was found thus update the existing sid in the database.
  3146. webform_submission_update($node, $submission);
  3147. $form_state['values']['details']['is_new'] = FALSE;
  3148. }
  3149. // Check if this form is sending an email.
  3150. if (!$is_draft && !$form_state['values']['details']['finished']) {
  3151. drupal_static_reset('webform_get_submission');
  3152. $submission = webform_get_submission($node->webform['nid'], $sid);
  3153. webform_submission_send_mail($node, $submission);
  3154. }
  3155. // Strip out empty tags added by WYSIWYG editors if needed.
  3156. $message = strlen(trim(strip_tags($node->webform['confirmation']))) > 0;
  3157. // Check confirmation and redirect_url fields.
  3158. $redirect = NULL;
  3159. $redirect_url = trim($node->webform['redirect_url']);
  3160. if (isset($form['actions']['draft']['#value']) && $form_state['values']['op'] == $form['actions']['draft']['#value']) {
  3161. $message = t('Submission saved. You may return to this form later and it will restore the current values.');
  3162. }
  3163. elseif ($is_draft) {
  3164. // No redirect needed. No confirmation message needed.
  3165. $message = FALSE;
  3166. }
  3167. elseif (!empty($form_state['values']['details']['finished'])) {
  3168. $message = t('Submission updated.');
  3169. $redirect = "node/{$node->nid}/submission/$sid";
  3170. }
  3171. elseif (!empty($node->webform['confirmation_block'])) {
  3172. $message = FALSE;
  3173. // Webform was submitted in a block and the confirmation message is to be
  3174. // displayed in the block.
  3175. $_SESSION['webform_confirmation'][$node->nid] = array(
  3176. 'sid' => $sid,
  3177. 'confirmation_page' => $redirect_url == '<confirmation>',
  3178. );
  3179. drupal_page_is_cacheable(FALSE);
  3180. }
  3181. elseif ($redirect_url == '<none>') {
  3182. // No redirect needed. Show a confirmatin message if there is one.
  3183. }
  3184. elseif ($redirect_url == '<confirmation>') {
  3185. // No confirmation message needed because it will be shown on the
  3186. // confirmation page.
  3187. $message = FALSE;
  3188. $query = array('sid' => $sid);
  3189. if ((int) $user->uid === 0) {
  3190. $query['token'] = webform_get_submission_access_token($submission);
  3191. }
  3192. $redirect = array('node/' . $node->nid . '/done', array('query' => $query));
  3193. }
  3194. else {
  3195. // Clean up the redirect URL, filter it for tokens and detect external
  3196. // domains. If the redirect is to an external URL, then don't show the
  3197. // confirmation message.
  3198. $redirect = webform_replace_url_tokens($redirect_url, $node, $submission);
  3199. if ($redirect[1]['#webform_external']) {
  3200. $message = FALSE;
  3201. }
  3202. }
  3203. // Show a message if manually set.
  3204. if (is_string($message)) {
  3205. drupal_set_message($message);
  3206. }
  3207. // If redirecting and we have a confirmation message, show it as a message.
  3208. elseif ($message) {
  3209. drupal_set_message(webform_replace_tokens($node->webform['confirmation'], $node, $submission, NULL, $node->webform['confirmation_format']));
  3210. }
  3211. $form_state['redirect'] = $redirect;
  3212. }
  3213. /**
  3214. * Post processes the submission tree with any updates from components.
  3215. *
  3216. * @param object $node
  3217. * The full webform node.
  3218. * @param $form_values
  3219. * The form values for the form.
  3220. * @param $types
  3221. * Optional. Specific types to perform processing.
  3222. * @param $parent
  3223. * Internal use. The current parent CID whose children are being processed.
  3224. */
  3225. function _webform_client_form_submit_process($node, &$form_values) {
  3226. foreach ($form_values as $cid => $value) {
  3227. if (isset($node->webform['components'][$cid])) {
  3228. // Call the component process submission function.
  3229. $component = $node->webform['components'][$cid];
  3230. if ((!isset($types) || in_array($component['type'], $types)) && webform_component_implements($component['type'], 'submit')) {
  3231. $form_values[$cid] = webform_component_invoke($component['type'], 'submit', $component, $form_values[$cid]);
  3232. }
  3233. }
  3234. }
  3235. }
  3236. /**
  3237. * Flattens a submitted values back into a single flat array representation.
  3238. */
  3239. function _webform_client_form_submit_flatten($node, $fieldset, $parent = 0) {
  3240. $values = array();
  3241. if (is_array($fieldset)) {
  3242. foreach ($fieldset as $form_key => $value) {
  3243. if ($cid = webform_get_cid($node, $form_key, $parent)) {
  3244. if (is_array($value) && webform_component_feature($node->webform['components'][$cid]['type'], 'group')) {
  3245. $values += _webform_client_form_submit_flatten($node, $value, $cid);
  3246. }
  3247. else {
  3248. $values[$cid] = $value;
  3249. }
  3250. }
  3251. else {
  3252. // This $form_key must belong to the parent. For example, a grid.
  3253. $values[$parent][$form_key] = $value;
  3254. }
  3255. }
  3256. }
  3257. return $values;
  3258. }
  3259. /**
  3260. * Prints the confirmation message after a successful submission.
  3261. */
  3262. function _webform_confirmation($node) {
  3263. drupal_set_title($node->title);
  3264. webform_set_breadcrumb($node, TRUE);
  3265. $sid = isset($_GET['sid']) ? $_GET['sid'] : NULL;
  3266. return theme(array('webform_confirmation_' . $node->nid, 'webform_confirmation'), array('node' => $node, 'sid' => $sid));
  3267. }
  3268. /**
  3269. * Prepare for theming of the webform form.
  3270. */
  3271. function template_preprocess_webform_form(&$vars) {
  3272. if (isset($vars['form']['details']['nid']['#value'])) {
  3273. $vars['nid'] = $vars['form']['details']['nid']['#value'];
  3274. }
  3275. elseif (isset($vars['form']['submission']['#value'])) {
  3276. $vars['nid'] = $vars['form']['submission']['#value']->nid;
  3277. }
  3278. if (!empty($vars['form']['#node']->webform['conditionals']) && empty($vars['form']['preview'])) {
  3279. module_load_include('inc', 'webform', 'includes/webform.conditionals');
  3280. $submission_data = isset($vars['form']['#conditional_values']) ? $vars['form']['#conditional_values'] : array();
  3281. $settings = webform_conditional_prepare_javascript($vars['form']['#node'],
  3282. $submission_data,
  3283. $vars['form']['details']['page_num']['#value']);
  3284. drupal_add_js(array('webform' => array('conditionals' => array('webform-client-form-' . $vars['nid'] => $settings))), 'setting');
  3285. }
  3286. }
  3287. /**
  3288. * Prepare for theming of the webform submission confirmation.
  3289. */
  3290. function template_preprocess_webform_confirmation(&$vars) {
  3291. $node = $vars['node'];
  3292. // Strip out empty tags added by WYSIWYG editors if needed.
  3293. $confirmation = $node->webform['confirmation'];
  3294. $confirmation = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';
  3295. // Replace tokens.
  3296. module_load_include('inc', 'webform', 'includes/webform.submissions');
  3297. $submission = webform_get_submission($node->nid, $vars['sid']);
  3298. $vars['confirmation_message'] = webform_replace_tokens($confirmation, $node, $submission, NULL, $node->webform['confirmation_format']);
  3299. // URL back to form (or same page for in-block confirmations).
  3300. $vars['url'] = empty($node->webform_block)
  3301. ? url('node/' . $node->nid)
  3302. : url(current_path(), array('query' => drupal_get_query_parameters()));
  3303. // Progress bar.
  3304. $vars['progressbar'] = '';
  3305. if ($node->webform['progressbar_include_confirmation']) {
  3306. $page_labels = webform_page_labels($node);
  3307. $page_count = count($page_labels);
  3308. $vars['progressbar'] = theme('webform_progressbar', array(
  3309. 'node' => $node,
  3310. 'page_num' => $page_count,
  3311. 'page_count' => $page_count,
  3312. 'page_labels' => $page_labels,
  3313. ));
  3314. }
  3315. }
  3316. /**
  3317. * Prepare for theming of the webform progressbar.
  3318. */
  3319. function template_preprocess_webform_progressbar(&$vars) {
  3320. // Add CSS used by the progress bar.
  3321. drupal_add_css(drupal_get_path('module', 'webform') . '/css/webform.css');
  3322. $vars['progressbar_page_number'] = $vars['node']->webform['progressbar_page_number'];
  3323. $vars['progressbar_percent'] = $vars['node']->webform['progressbar_percent'];
  3324. $vars['progressbar_bar'] = $vars['node']->webform['progressbar_bar'];
  3325. $vars['progressbar_pagebreak_labels'] = $vars['node']->webform['progressbar_pagebreak_labels'];
  3326. $vars['progressbar_include_confirmation'] = $vars['node']->webform['progressbar_include_confirmation'];
  3327. $vars['percent'] = ($vars['page_num'] - 1) / ($vars['page_count'] - 1) * 100;
  3328. }
  3329. /**
  3330. * Prepare to theme the contents of e-mails sent by webform.
  3331. */
  3332. function template_preprocess_webform_mail_message(&$vars) {
  3333. global $user;
  3334. $vars['user'] = $user;
  3335. $vars['ip_address'] = webform_ip_address($vars['node']);
  3336. }
  3337. /**
  3338. * A Form API #pre_render function. Sets display based on #title_display.
  3339. *
  3340. * This function is used regularly in D6 for all elements, but specifically for
  3341. * fieldsets in D7, which don't support #title_display natively.
  3342. */
  3343. function webform_element_title_display($element) {
  3344. if (isset($element['#title_display']) && strcmp($element['#title_display'], 'none') === 0) {
  3345. $element['#title'] = NULL;
  3346. }
  3347. return $element;
  3348. }
  3349. /**
  3350. * A Form API #pre_render function that removes the ID from an element.
  3351. *
  3352. * Drupal forcibly adds IDs to all form elements, including those that do not
  3353. * need them for any reason, such as the actions wrapper or submit buttons. We
  3354. * use this process function wherever we wish to remove an ID from an element.
  3355. * Because #states and #ajax require IDs, they are only removed if the states
  3356. * and ajax arrays are empty.
  3357. */
  3358. function webform_pre_render_remove_id($element) {
  3359. if (empty($element['#states']) && empty($element['#ajax'])) {
  3360. $element['#id'] = NULL;
  3361. // Removing array parents is required to prevent theme_container from adding
  3362. // an empty ID attribute.
  3363. $element['#array_parents'] = NULL;
  3364. }
  3365. return $element;
  3366. }
  3367. /**
  3368. * Implements template_preprocess_THEME_HOOK().
  3369. */
  3370. function template_preprocess_webform_element(&$variables) {
  3371. $element = &$variables['element'];
  3372. // Ensure defaults.
  3373. $element += array(
  3374. '#title_display' => 'before',
  3375. '#wrapper_attributes' => array(),
  3376. );
  3377. $element['#wrapper_attributes'] += array(
  3378. 'class' => array(),
  3379. );
  3380. // All elements using this for display only are given the "display" type.
  3381. if (isset($element['#format']) && $element['#format'] == 'html') {
  3382. $type = 'display';
  3383. }
  3384. else {
  3385. $type = ($element['#webform_component']['type'] == 'select' && isset($element['#type'])) ? $element['#type'] : $element['#webform_component']['type'];
  3386. }
  3387. // Convert the parents array into a string, excluding the "submitted" wrapper.
  3388. $nested_level = $element['#parents'][0] == 'submitted' ? 1 : 0;
  3389. $parents = str_replace('_', '-', implode('--', array_slice($element['#parents'], $nested_level)));
  3390. // Build up a list of classes to apply on the element wrapper.
  3391. $wrapper_classes = array(
  3392. 'form-item',
  3393. 'webform-component',
  3394. 'webform-component-' . str_replace('_', '-', $type),
  3395. 'webform-component--' . $parents,
  3396. );
  3397. if (isset($element['#title_display']) && strcmp($element['#title_display'], 'inline') === 0) {
  3398. $wrapper_classes[] = 'webform-container-inline';
  3399. }
  3400. $element['#wrapper_attributes']['class'] = array_merge($element['#wrapper_attributes']['class'], $wrapper_classes);
  3401. // If #title_display is none, set it to invisible instead - none only used if
  3402. // we have no title at all to use.
  3403. if ($element['#title_display'] == 'none') {
  3404. $element['#title_display'] = 'invisible';
  3405. if (empty($element['#attributes']['title']) && !empty($element['#title'])) {
  3406. $element['#attributes']['title'] = $element['#title'];
  3407. }
  3408. }
  3409. // If #title is not set, we don't display any label or required marker.
  3410. if (!isset($element['#title'])) {
  3411. $element['#title_display'] = 'none';
  3412. }
  3413. // If an internal title is being used, generate no external title.
  3414. if ($element['#title_display'] == 'internal') {
  3415. $element['#title_display'] = 'none';
  3416. }
  3417. }
  3418. /**
  3419. * Replacement for theme_form_element().
  3420. */
  3421. function theme_webform_element($variables) {
  3422. $element = $variables['element'];
  3423. $output = '<div ' . drupal_attributes($element['#wrapper_attributes']) . '>' . "\n";
  3424. $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . webform_filter_xss($element['#field_prefix']) . '</span> ' : '';
  3425. $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . webform_filter_xss($element['#field_suffix']) . '</span>' : '';
  3426. // Generate description for above or below the field.
  3427. $above = !empty($element['#webform_component']['extra']['description_above']);
  3428. $description = array(
  3429. FALSE => '',
  3430. TRUE => !empty($element['#description']) ? ' <div class="description">' . $element['#description'] . "</div>\n" : '',
  3431. );
  3432. // If #children does not contain an element with a matching @id, do not
  3433. // include @for in the label.
  3434. if (isset($variables['element']['#id']) && strpos($element['#children'], ' id="' . $variables['element']['#id'] . '"') === FALSE) {
  3435. $variables['element']['#id'] = NULL;
  3436. }
  3437. // Determine whether or not this element has form control children. If so and
  3438. // if webform_fieldset_wrap is TRUE, wrap them in a fieldset and use legend
  3439. // instead of label.
  3440. $has_element_children = FALSE;
  3441. if (webform_variable_get('webform_fieldset_wrap')) {
  3442. foreach (array_keys($element) as $key) {
  3443. if (substr($key, 0, 1) !== '#') {
  3444. $has_element_children = TRUE;
  3445. break;
  3446. }
  3447. }
  3448. }
  3449. if ($has_element_children) {
  3450. $output .= '<fieldset class="fieldset-invisible">';
  3451. }
  3452. switch ($element['#title_display']) {
  3453. case 'inline':
  3454. $output .= $description[$above];
  3455. $description[$above] = '';
  3456. case 'before':
  3457. case 'invisible':
  3458. case 'after':
  3459. if ($has_element_children) {
  3460. $title = '<legend>' . $element['#title'];
  3461. if ($element['#required']) {
  3462. $title .= ' ' . theme('form_required_marker', $variables);
  3463. }
  3464. $title .= '</legend>';
  3465. }
  3466. else {
  3467. $title = ' ' . theme('form_element_label', $variables);
  3468. }
  3469. break;
  3470. }
  3471. $children = ' ' . $description[$above] . $prefix . $element['#children'] . $suffix;
  3472. switch ($element['#title_display']) {
  3473. case 'inline':
  3474. case 'before':
  3475. case 'invisible':
  3476. $output .= $title;
  3477. $output .= $children;
  3478. break;
  3479. case 'after':
  3480. $output .= $children;
  3481. $output .= $title;
  3482. break;
  3483. case 'none':
  3484. case 'attribute':
  3485. // Output no label and no required marker, only the children.
  3486. $output .= $children;
  3487. break;
  3488. }
  3489. $output .= "\n";
  3490. $output .= $description[!$above];
  3491. if ($has_element_children) {
  3492. $output .= '</fieldset>';
  3493. }
  3494. $output .= "</div>\n";
  3495. return $output;
  3496. }
  3497. /**
  3498. * Output a form element in plain text format.
  3499. */
  3500. function theme_webform_element_text($variables) {
  3501. $element = $variables['element'];
  3502. $value = $variables['element']['#children'];
  3503. $output = '';
  3504. $is_group = webform_component_feature($element['#webform_component']['type'], 'group');
  3505. // Output the element title.
  3506. if (isset($element['#title'])) {
  3507. if ($is_group) {
  3508. $output .= '==' . $element['#title'] . '==';
  3509. }
  3510. elseif (!in_array(drupal_substr($element['#title'], -1), array('?', ':', '!', '%', ';', '@'))) {
  3511. $output .= $element['#title'] . ':';
  3512. }
  3513. else {
  3514. $output .= $element['#title'];
  3515. }
  3516. }
  3517. // Wrap long values at 65 characters, allowing for a few fieldset indents.
  3518. // It's common courtesy to wrap at 75 characters in e-mails.
  3519. if ($is_group && drupal_strlen($value) > 65) {
  3520. $value = wordwrap($value, 65, "\n");
  3521. $lines = explode("\n", $value);
  3522. foreach ($lines as $key => $line) {
  3523. $lines[$key] = ' ' . $line;
  3524. }
  3525. $value = implode("\n", $lines);
  3526. }
  3527. // Add the value to the output. Add a newline before the response if needed.
  3528. $output .= (strpos($value, "\n") === FALSE ? ' ' : "\n") . $value;
  3529. // Indent fieldsets.
  3530. if ($is_group) {
  3531. $lines = explode("\n", $output);
  3532. foreach ($lines as $number => $line) {
  3533. if (strlen($line)) {
  3534. $lines[$number] = ' ' . $line;
  3535. }
  3536. }
  3537. $output = implode("\n", $lines);
  3538. $output .= "\n";
  3539. }
  3540. if ($output) {
  3541. $output .= "\n";
  3542. }
  3543. return $output;
  3544. }
  3545. /**
  3546. * Theme a radio button and another element together.
  3547. *
  3548. * This is used in the e-mail configuration to show a radio button and a text
  3549. * field or select list on the same line.
  3550. */
  3551. function theme_webform_inline_radio($variables) {
  3552. $element = $variables['element'];
  3553. // Add element's #type and #name as class to aid with JS/CSS selectors.
  3554. $class = array('form-item');
  3555. if (!empty($element['#type'])) {
  3556. $class[] = 'form-type-' . strtr($element['#type'], '_', '-');
  3557. }
  3558. if (!empty($element['#name'])) {
  3559. $class[] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3560. }
  3561. // Add container-inline to all elements.
  3562. $class[] = 'webform-container-inline';
  3563. if (isset($element['#inline_element']) && isset($variables['element']['#title'])) {
  3564. $variables['element']['#title'] .= ': ';
  3565. }
  3566. $output = '<div class="' . implode(' ', $class) . '">' . "\n";
  3567. $output .= ' ' . $element['#children'];
  3568. if (!empty($element['#title'])) {
  3569. $output .= ' ' . theme('webform_inline_radio_label', $variables) . "\n";
  3570. }
  3571. if (!empty($element['#description'])) {
  3572. $output .= ' <div class="description">' . $element['#description'] . "</div>\n";
  3573. }
  3574. $output .= "</div>\n";
  3575. return $output;
  3576. }
  3577. /**
  3578. * Replacement for theme_form_element_label()
  3579. *
  3580. * This varies from theme_element_label in that it allows inline fields such
  3581. * as select and input tags within the label itself.
  3582. */
  3583. function theme_webform_inline_radio_label($variables) {
  3584. $element = $variables['element'];
  3585. // This is also used in the installer, pre-database setup.
  3586. $t = get_t();
  3587. // If title and required marker are both empty, output no label.
  3588. if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
  3589. return '';
  3590. }
  3591. // If the element is required, a required marker is appended to the label.
  3592. $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
  3593. // theme_element_label() does a filter_xss() here, we skip it because we know
  3594. // every use where this theme function is used and we need to allow input and
  3595. // select elements.
  3596. $title = $element['#title'];
  3597. $attributes = isset($element['#attributes']) ? $element['#attributes'] : array();
  3598. // Style the label as class option to display inline with the element.
  3599. if ($element['#title_display'] == 'after') {
  3600. $attributes['class'][] = 'option';
  3601. }
  3602. // Show label only to screen readers to avoid disruption in visual flows.
  3603. elseif ($element['#title_display'] == 'invisible') {
  3604. $attributes['class'][] = 'element-invisible';
  3605. }
  3606. $attributes['class'][] = 'webform-inline-radio';
  3607. if (!empty($element['#id'])) {
  3608. $attributes['for'] = $element['#id'];
  3609. }
  3610. // The leading whitespace helps visually separate fields from inline labels.
  3611. return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
  3612. }
  3613. /**
  3614. * Theme the headers when sending an email from webform.
  3615. *
  3616. * @param array $variables
  3617. * The variables array.
  3618. *
  3619. * @return array
  3620. * An array of headers to be used when sending a webform email. If headers
  3621. * for "From", "To", or "Subject" are set, they will take precedence over
  3622. * the values set in the webform configuration.
  3623. */
  3624. function theme_webform_mail_headers(array $variables) {
  3625. $headers = array(
  3626. 'X-Mailer' => 'Drupal Webform' . (ini_get('expose_php') ? ' (PHP/' . phpversion() . ')' : ''),
  3627. );
  3628. return $headers;
  3629. }
  3630. /**
  3631. * Check if current user has a draft of this webform, and return the sid.
  3632. */
  3633. function _webform_fetch_draft_sid($nid, $uid) {
  3634. $q = db_select('webform_submissions')
  3635. ->fields('webform_submissions', array('sid'))
  3636. ->condition('nid', $nid)
  3637. ->condition('uid', $uid)
  3638. ->condition('is_draft', 1)
  3639. ->orderBy('submitted', 'DESC');
  3640. // Detect whether a webform draft is being edited. If so, that is the one that
  3641. // should be returned.
  3642. $is_webform = isset($_POST['form_id']) && stripos($_POST['form_id'], 'webform_client_form_') === 0;
  3643. $sid_provided = !empty($_POST['details']['sid']) && is_string($_POST['details']['sid']);
  3644. $not_finished = empty($_POST['details']['finished']);
  3645. if ($is_webform && $sid_provided && $not_finished) {
  3646. // Validate that the sid from $_POST belongs to the current user.
  3647. $q->condition('sid', $_POST['details']['sid']);
  3648. $existing_sid = TRUE;
  3649. }
  3650. // Retrieve exisiting draft sid.
  3651. $sid = $q
  3652. ->execute()
  3653. ->fetchField();
  3654. // Allow modules to alter the initial choice of sid when there might be more
  3655. // than one.
  3656. if ($sid && empty($existing_sid)) {
  3657. $context = array(
  3658. 'nid' => $nid,
  3659. 'uid' => $uid,
  3660. );
  3661. drupal_alter('webform_draft', $sid, $context);
  3662. }
  3663. return $sid;
  3664. }
  3665. /**
  3666. * Returns a new or cached WebformConditionals object for the specified node.
  3667. *
  3668. * @param object $node
  3669. * The loaded webform node.
  3670. *
  3671. * @returns object
  3672. * Object of type WebformConditionals, possibly with the conditionals already
  3673. * analyzed for dependencies.
  3674. */
  3675. function webform_get_conditional_sorter($node) {
  3676. return WebformConditionals::factory($node);
  3677. }
  3678. /**
  3679. * Wrapper for webform_replace_tokens().
  3680. *
  3681. * @deprecated in webform:7.x-4.0 and is removed from webform:7.x-5.0. Use
  3682. * webform_replace_tokens().
  3683. * @see https://www.drupal.org/project/webform/issues/2038199
  3684. */
  3685. function _webform_filter_values($string, $node = NULL, $submission = NULL, $email = NULL, $strict = TRUE) {
  3686. $output = webform_replace_tokens($string, $node, $submission, $email, $strict);
  3687. return $strict ? webform_filter_xss($output) : $output;
  3688. }
  3689. /**
  3690. * Replace tokens with Webform contexts populated.
  3691. *
  3692. * @param $string
  3693. * The string to have its tokens replaced.
  3694. * @param object $node
  3695. * If replacing node-level tokens, the node for which tokens will be created.
  3696. * @param $submission
  3697. * If replacing submission-level tokens, the submission for which tokens will
  3698. * be created.
  3699. * @param $email
  3700. * If replacing tokens within the context of an e-mail, the Webform e-mail
  3701. * settings array.
  3702. * @param $sanitize
  3703. * Boolean or format name value indicating if the results will be displayed as
  3704. * HTML output. If FALSE, the contents returned will be unsanitized. This will
  3705. * also result in all Webform submission tokens being returned as plain-text,
  3706. * without HTML markup, in preparation for e-mailing or other text-only
  3707. * purposes (default values, etc.). If TRUE, the tokens only are sanitized by
  3708. * token_replace. Otherwise $sanitize is the machine name of an import filter
  3709. * to be used with check_markup().
  3710. */
  3711. function webform_replace_tokens($string, $node = NULL, $submission = NULL, $email = NULL, $sanitize = FALSE) {
  3712. // Don't do any filtering if the string is empty.
  3713. if (!strlen(trim($string)) || !webform_variable_get('webform_token_access')) {
  3714. return $string;
  3715. }
  3716. $token_data = array();
  3717. if ($node) {
  3718. $token_data['node'] = $node;
  3719. }
  3720. if ($submission) {
  3721. $token_data['webform-submission'] = $submission;
  3722. }
  3723. if ($email) {
  3724. $token_data['webform-email'] = $email;
  3725. }
  3726. $clear = is_bool($sanitize);
  3727. $string = token_replace($string, $token_data, array('clear' => $clear, 'sanitize' => $sanitize === TRUE));
  3728. if (!$clear) {
  3729. $string = webform_replace_tokens_clear(check_markup($string, $sanitize));
  3730. }
  3731. return $string;
  3732. }
  3733. /**
  3734. * Removes tokens from string.
  3735. *
  3736. * Call this function in cases where you need to remove unreplaced tokens but
  3737. * can't call webform_replace_tokens() with the option $clear = TRUE.
  3738. *
  3739. * In some cases the function token_replace() in webform_replace_tokens() needs
  3740. * to be called with the option 'clear' => FALSE, to not remove input filters.
  3741. * For security reasons webform_replace_tokens() is called before
  3742. * check_markup(), where input filters get replaced. Tokens won't be replaced if
  3743. * there is no value provided. These tokens, that is, [current-page:query:*]
  3744. * needs to be removed to not show up in the output.
  3745. *
  3746. * Note: This function was previously named webform_clear_tokens, which
  3747. * conflicted with the webform_clear module, being called as hook_tokens.
  3748. *
  3749. * @param string $text
  3750. * The text to have its tokens removed.
  3751. *
  3752. * @return mixed|string
  3753. * Replace tokens with actual value.
  3754. *
  3755. * @see token_replace()
  3756. */
  3757. function webform_replace_tokens_clear($text) {
  3758. if (empty($text) || !webform_variable_get('webform_token_access')) {
  3759. return $text;
  3760. }
  3761. $text_tokens = token_scan($text);
  3762. if (empty($text_tokens)) {
  3763. return $text;
  3764. }
  3765. $replacements = array();
  3766. foreach ($text_tokens as $type => $tokens) {
  3767. $replacements += array_fill_keys($tokens, '');
  3768. }
  3769. $tokens = array_keys($replacements);
  3770. $values = array_values($replacements);
  3771. return str_replace($tokens, $values, $text);
  3772. }
  3773. /**
  3774. * Replace tokens within a URL, encoding the parts within the query string.
  3775. *
  3776. * @param string $redirect_url
  3777. * The redirect URL, with everything other than tokens already URL encoded.
  3778. * @param object $node
  3779. * If replacing node-level tokens, the node for which tokens will be created.
  3780. * @param $submission
  3781. * If replacing submission-level tokens, the submission for which tokens will
  3782. * be created.
  3783. *
  3784. * @return array
  3785. * An array of path and url() options, suitable for a redirect or drupal_goto.
  3786. */
  3787. function webform_replace_url_tokens($redirect_url, $node = NULL, $submission = NULL) {
  3788. // Parse the url into its components.
  3789. $parsed_redirect_url = drupal_parse_url($redirect_url);
  3790. // Replace tokens in each component.
  3791. $parsed_redirect_url['path'] = webform_replace_tokens($parsed_redirect_url['path'], $node, $submission);
  3792. if (!empty($parsed_redirect_url['query'])) {
  3793. foreach ($parsed_redirect_url['query'] as $key => $value) {
  3794. $parsed_redirect_url['query'][$key] = trim(webform_replace_tokens($value, $node, $submission));
  3795. }
  3796. }
  3797. $parsed_redirect_url['fragment'] = webform_replace_tokens($parsed_redirect_url['fragment'], $node, $submission);
  3798. // Determine whether the path is internal or external. Paths which contain the
  3799. // site's base url are still considered internal. #webform_external is private
  3800. // to webform.
  3801. $parsed_redirect_url['#webform_external'] = url_is_external($parsed_redirect_url['path']);
  3802. foreach (array(NULL, TRUE, FALSE) as $https) {
  3803. if (stripos($parsed_redirect_url['path'], url('', array('absolute' => TRUE, 'https' => $https))) === 0) {
  3804. $parsed_redirect_url['#webform_external'] = FALSE;
  3805. }
  3806. }
  3807. // Return an array suitable for a form redirect or drupal_goto.
  3808. return array($parsed_redirect_url['path'], $parsed_redirect_url);
  3809. }
  3810. /**
  3811. * Replace tokens in descriptions and sanitize according to Webform settings.
  3812. */
  3813. function webform_filter_descriptions($string, $node = NULL, $submission = NULL) {
  3814. return strlen($string) == 0 ? '' : webform_filter_xss(webform_replace_tokens($string, $node, $submission));
  3815. }
  3816. /**
  3817. * Duplicates webform_filter_descriptions().
  3818. *
  3819. * @deprecated in webform:7.x-4.0 and is removed from webform:7.x-5.0. Use
  3820. * webform_filter_descriptions().
  3821. * @see https://www.drupal.org/project/webform/issues/2038199
  3822. */
  3823. function _webform_filter_descriptions($string, $node = NULL, $submission = NULL) {
  3824. return webform_filter_descriptions($string, $node, $submission);
  3825. }
  3826. /**
  3827. * Filter labels for display by running through XSS checks.
  3828. */
  3829. function webform_filter_xss($string) {
  3830. static $allowed_tags;
  3831. $allowed_tags = isset($allowed_tags) ? $allowed_tags : webform_variable_get('webform_allowed_tags');
  3832. return filter_xss($string, $allowed_tags);
  3833. }
  3834. /**
  3835. * Duplicates webform_filter_xss().
  3836. *
  3837. * @deprecated in webform:7.x-4.0 and is removed from webform:7.x-5.0. Use
  3838. * webform_filter_xss().
  3839. * @see https://www.drupal.org/project/webform/issues/2038199
  3840. */
  3841. function _webform_filter_xss($string) {
  3842. return webform_filter_xss($string);
  3843. }
  3844. /**
  3845. * Utility function to ensure that a webform record exists in the database.
  3846. *
  3847. * @param object $node
  3848. * The node object to check if a database entry exists.
  3849. *
  3850. * @return bool
  3851. * This function should always return TRUE if no errors were encountered,
  3852. * ensuring that a webform table row has been created. Will return FALSE if
  3853. * a record does not exist and a new one could not be created.
  3854. */
  3855. function webform_ensure_record(&$node) {
  3856. if (!$node->webform['record_exists']) {
  3857. // Even though webform_node_insert() would set this property to TRUE,
  3858. // we set record_exists to trigger a difference from the defaults.
  3859. $node->webform['record_exists'] = TRUE;
  3860. webform_node_insert($node);
  3861. }
  3862. return $node->webform['record_exists'];
  3863. }
  3864. /**
  3865. * Utility function to check if a webform record is necessary in the database.
  3866. *
  3867. * If the node is no longer using any webform settings, this function will
  3868. * delete the settings from the webform table. Note that this function will NOT
  3869. * delete rows from the webform table if the node-type is exclusively used for
  3870. * webforms (per the "webform_node_types_primary" variable).
  3871. *
  3872. * @param object $node
  3873. * The node object to check if a database entry is still required.
  3874. *
  3875. * @return bool
  3876. * Returns TRUE if the webform still has a record in the database. Returns
  3877. * FALSE if the webform does not have a record or if the previously existing
  3878. * record was just deleted.
  3879. */
  3880. function webform_check_record(&$node) {
  3881. $webform = $node->webform;
  3882. $webform['record_exists'] = FALSE;
  3883. unset($webform['nid']);
  3884. // Don't include empty values in the comparison, this makes it so modules that
  3885. // extend Webform with empty defaults won't affect cleanup of rows.
  3886. $webform = array_filter($webform);
  3887. $defaults = array_filter(webform_node_defaults());
  3888. if ($webform == $defaults && !in_array($node->type, webform_variable_get('webform_node_types_primary'))) {
  3889. webform_node_delete($node);
  3890. $node->webform = webform_node_defaults();
  3891. }
  3892. return $node->webform['record_exists'];
  3893. }
  3894. /**
  3895. * Given a component's form_key and optionally its parent's cid, get its cid(s).
  3896. *
  3897. * @param object $node
  3898. * A fully loaded webform node object.
  3899. * @param string $form_key
  3900. * The form key for which to find the cid(s).
  3901. * @param int|null $pid
  3902. * The cid of the parent component.
  3903. *
  3904. * @return int|int[]
  3905. * The cid of the component or an array of component ids.
  3906. */
  3907. function webform_get_cid($node, $form_key, $pid = NULL) {
  3908. if ($pid === NULL) {
  3909. $cids = array();
  3910. foreach ($node->webform['components'] as $cid => $component) {
  3911. if ((string) $component['form_key'] === (string) $form_key) {
  3912. $cids[] = $cid;
  3913. }
  3914. }
  3915. return $cids;
  3916. }
  3917. else {
  3918. foreach ($node->webform['components'] as $cid => $component) {
  3919. if ((string) $component['form_key'] === (string) $form_key && $component['pid'] == $pid) {
  3920. return $cid;
  3921. }
  3922. }
  3923. }
  3924. }
  3925. /**
  3926. * Find the label of a given page based on page breaks.
  3927. *
  3928. * @param object $node
  3929. * The webform node.
  3930. * @param $form_state
  3931. * The form's state, if available
  3932. *
  3933. * @return array
  3934. * An array of all page labels, indexed by page number.
  3935. */
  3936. function webform_page_labels($node, $form_state = array()) {
  3937. $page_count = 1;
  3938. $page_labels = array();
  3939. $page_labels[0] = t($node->webform['progressbar_label_first']);
  3940. foreach ($node->webform['components'] as $component) {
  3941. if ($component['type'] == 'pagebreak') {
  3942. if (module_exists('webform_localization')) {
  3943. module_load_include('inc', 'webform_localization', 'includes/webform_localization.i18n');
  3944. $string = webform_localization_i18n_string_name($component['nid'], $component['cid'], '#title');
  3945. $component['name'] = i18n_string($string, $component['name'], array(
  3946. 'update' => TRUE,
  3947. 'sanitize' => FALSE,
  3948. ));
  3949. }
  3950. $page_labels[$page_count] = $component['name'];
  3951. $page_count++;
  3952. }
  3953. }
  3954. if ($node->webform['preview'] || !empty($form_state['webform']['preview'])) {
  3955. $page_labels[] = $node->webform['preview_title'] ? t($node->webform['preview_title']) : t('Preview');
  3956. }
  3957. if ($node->webform['progressbar_include_confirmation']) {
  3958. $page_labels[] = t($node->webform['progressbar_label_confirmation']);
  3959. }
  3960. return $page_labels;
  3961. }
  3962. /**
  3963. * Retrieve a Drupal variable with the appropriate default value.
  3964. */
  3965. function webform_variable_get($variable) {
  3966. switch ($variable) {
  3967. case 'webform_blocks':
  3968. $result = variable_get('webform_blocks', array());
  3969. break;
  3970. case 'webform_tracking_mode':
  3971. $result = variable_get('webform_tracking_mode', 'cookie');
  3972. break;
  3973. case 'webform_allowed_tags':
  3974. $result = variable_get('webform_allowed_tags', array('a', 'em', 'strong', 'code', 'img'));
  3975. break;
  3976. case 'webform_email_address_format':
  3977. $result = variable_get('webform_email_address_format', 'long');
  3978. break;
  3979. case 'webform_email_address_individual':
  3980. $result = variable_get('webform_email_address_individual', 0);
  3981. break;
  3982. case 'webform_default_from_name':
  3983. $result = variable_get('webform_default_from_name', variable_get('site_name', ''));
  3984. break;
  3985. case 'webform_default_from_address':
  3986. $result = variable_get('webform_default_from_address', variable_get('site_mail', ini_get('sendmail_from')));
  3987. break;
  3988. case 'webform_default_subject':
  3989. $result = variable_get('webform_default_subject', t('Form submission from: [node:title]'));
  3990. break;
  3991. case 'webform_email_replyto':
  3992. $result = variable_get('webform_email_replyto', TRUE);
  3993. break;
  3994. case 'webform_email_html_capable':
  3995. $result = variable_get('webform_email_html_capable', FALSE);
  3996. break;
  3997. case 'webform_default_format':
  3998. $result = variable_get('webform_default_format', 0);
  3999. break;
  4000. case 'webform_format_override':
  4001. $result = variable_get('webform_format_override', 0);
  4002. break;
  4003. case 'webform_email_select_max':
  4004. $result = variable_get('webform_email_select_max', 50);
  4005. break;
  4006. case 'webform_node_types':
  4007. $result = webform_node_types();
  4008. break;
  4009. case 'webform_node_types_primary':
  4010. $result = variable_get('webform_node_types_primary', array('webform'));
  4011. break;
  4012. case 'webform_date_type':
  4013. $result = variable_get('webform_date_type', 'medium');
  4014. break;
  4015. case 'webform_export_format':
  4016. module_load_include('inc', 'webform', 'includes/webform.export');
  4017. $options = webform_export_list();
  4018. $result = variable_get('webform_export_format', 'excel');
  4019. $result = isset($options[$result]) ? $result : key($options);
  4020. break;
  4021. case 'webform_csv_delimiter':
  4022. $result = variable_get('webform_csv_delimiter', '\t');
  4023. break;
  4024. case 'webform_csv_line_ending':
  4025. $result = variable_get('webform_csv_line_ending', "\n");
  4026. break;
  4027. case 'webform_export_wordwrap':
  4028. $result = variable_get('webform_export_wordwrap', 0);
  4029. break;
  4030. case 'webform_excel_legacy_exporter':
  4031. $result = variable_get('webform_excel_legacy_exporter', 0);
  4032. break;
  4033. case 'webform_progressbar_style':
  4034. $result = variable_get('webform_progressbar_style', array('progressbar_bar', 'progressbar_pagebreak_labels', 'progressbar_include_confirmation'));
  4035. break;
  4036. case 'webform_progressbar_label_first':
  4037. $result = variable_get('webform_progressbar_label_first', t('Start'));
  4038. break;
  4039. case 'webform_progressbar_label_confirmation':
  4040. $result = variable_get('webform_progressbar_label_confirmation', t('Complete'));
  4041. break;
  4042. case 'webform_table':
  4043. $result = variable_get('webform_table', FALSE);
  4044. break;
  4045. case 'webform_submission_access_control':
  4046. $result = variable_get('webform_submission_access_control', 1);
  4047. break;
  4048. case 'webform_token_access':
  4049. $result = variable_get('webform_token_access', 1);
  4050. break;
  4051. case 'webform_update_batch_size':
  4052. $result = variable_get('webform_update_batch_size', 100);
  4053. break;
  4054. case 'webform_disabled_components':
  4055. $result = variable_get('webform_disabled_components', array());
  4056. break;
  4057. case 'webform_fieldset_wrap':
  4058. $result = variable_get('webform_fieldset_wrap', FALSE);
  4059. break;
  4060. }
  4061. return $result;
  4062. }
  4063. /**
  4064. * Output the contents of token help used throughout Webform.
  4065. *
  4066. * In earlier versions of Token, a fieldset is used to show all the tokens.
  4067. * Later versions now use a modal dialog that is accessed through a link. If
  4068. * Token module is not available, a message should be displayed.
  4069. */
  4070. function theme_webform_token_help($variables) {
  4071. if (!webform_variable_get('webform_token_access')) {
  4072. return '';
  4073. }
  4074. $groups = $variables['groups'];
  4075. // Assume dialogs are not supported, show as a fieldset.
  4076. $help = array(
  4077. '#title' => t('Token values'),
  4078. '#type' => 'fieldset',
  4079. '#collapsible' => TRUE,
  4080. '#collapsed' => TRUE,
  4081. '#attributes' => array('class' => array('collapsible', 'collapsed')),
  4082. 'help' => array(
  4083. '#markup' => '<p>' . t('This field supports dynamic token values. Common values might be [current-user:mail] or [node:title].') . '</p>',
  4084. ),
  4085. 'token_tree' => array(
  4086. '#theme' => 'token_tree',
  4087. '#token_types' => $groups,
  4088. ),
  4089. );
  4090. if (!module_exists('token')) {
  4091. // No token module at all. Display a simple suggestion to enable it.
  4092. $help['help']['#markup'] .= '<p>' . t('A full listing of tokens may be listed here by installing the <a href="http://drupal.org/project/token">Token module</a>.') . '</p>';
  4093. unset($help['token_tree']);
  4094. }
  4095. else {
  4096. module_load_include('inc', 'token', 'token.pages');
  4097. if (function_exists('token_page_output_tree')) {
  4098. // Token supports dialogs: display simply as a link.
  4099. $help = $help['token_tree'];
  4100. $help['#dialog'] = TRUE;
  4101. }
  4102. }
  4103. return render($help);
  4104. }
  4105. /**
  4106. * Convert a name into an identifier.
  4107. *
  4108. * The identifier is safe for machine names, classes, and other ASCII uses.
  4109. */
  4110. function _webform_safe_name($name) {
  4111. $new = trim($name);
  4112. $new = _webform_transliterate($new);
  4113. $new = str_replace(array(' ', '-', '/'), array('_', '_', '_'), $new);
  4114. $new = drupal_strtolower($new);
  4115. $new = preg_replace('/[^a-z0-9_]/', '', $new);
  4116. return $new;
  4117. }
  4118. /**
  4119. * Transliterate common non-English characters to 7-bit ASCII.
  4120. */
  4121. function _webform_transliterate($name) {
  4122. // If transliteration is available, use it to convert names to ASCII.
  4123. return function_exists('transliteration_get')
  4124. ? transliteration_get($name, '')
  4125. : str_replace(array('€', 'ƒ', 'Š', 'Ž', 'š', 'ž', 'Ÿ', '¢', '¥', 'µ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Œ', 'œ', 'Æ', 'Ð', 'Þ', 'ß', 'æ', 'ð', 'þ'),
  4126. array('E', 'f', 'S', 'Z', 's', 'z', 'Y', 'c', 'Y', 'u', 'A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'),
  4127. $name);
  4128. }
  4129. /**
  4130. * Given an email address and a name, format an e-mail address.
  4131. *
  4132. * The address can be the cid of a component with multiple values. When $single
  4133. * is true, a single address is return (the first of any multiples). When not
  4134. * true, an array of addresses is returned.
  4135. *
  4136. * Note that multiple names could be used with multiple addresses, but this
  4137. * capability is not currently possible with the webform UI. Separate names
  4138. * are only used with the From address, which is always single.
  4139. *
  4140. * @param $address
  4141. * The e-mail address.
  4142. * @param $name
  4143. * The name to be used in the formatted address. If the address contains a
  4144. * name in 'Some Name <somename@example.com>' format, $name is ignored.
  4145. * @param object $node
  4146. * The webform node if replacements will be done.
  4147. * @param $submission
  4148. * The webform submission values if replacements will be done.
  4149. * @param $encode
  4150. * Encode the text for use in an e-mail.
  4151. * @param $single
  4152. * Force a single value to be returned, even if a component expands to
  4153. * multiple addresses. This is useful to ensure a single e-mail will be
  4154. * returned for the "From" address.
  4155. * @param $format
  4156. * The e-mail format, defaults to the site-wide setting. May be "short",
  4157. * "long", or NULL for the system default.
  4158. * @param $mapping
  4159. * A mapping array to be applied to the address values.
  4160. *
  4161. * @return string|array
  4162. * The formatted e-mail address -- or addresses (if not $single)
  4163. */
  4164. function webform_format_email_address($address, $name, $node = NULL, $submission = NULL, $encode = TRUE, $single = TRUE, $format = NULL, $mapping = NULL) {
  4165. if (!isset($format)) {
  4166. $format = webform_variable_get('webform_email_address_format');
  4167. }
  4168. if ($name == 'default') {
  4169. $name = webform_variable_get('webform_default_from_name');
  4170. }
  4171. elseif (is_numeric($name) && isset($node->webform['components'][$name])) {
  4172. if (isset($submission->data[$name])) {
  4173. $component = $node->webform['components'][$name];
  4174. $name = $submission->data[$name];
  4175. // Convert the FROM name to be the label of select lists.
  4176. if (webform_component_implements($component['type'], 'options')) {
  4177. $options = webform_component_invoke($component['type'], 'options', $component);
  4178. foreach ($name as &$one_name) {
  4179. $one_name = isset($options[$one_name]) ? $options[$one_name] : $one_name;
  4180. }
  4181. // Drop PHP reference.
  4182. unset($one_name);
  4183. }
  4184. }
  4185. else {
  4186. $name = t('Value of !component', array('!component' => $node->webform['components'][$name]['name']));
  4187. }
  4188. }
  4189. elseif (!isset($name)) {
  4190. $name = '';
  4191. }
  4192. if ($address == 'default') {
  4193. $address = webform_variable_get('webform_default_from_address');
  4194. }
  4195. elseif (is_numeric($address) && isset($node->webform['components'][$address])) {
  4196. if (isset($submission->data[$address])) {
  4197. $values = $submission->data[$address];
  4198. $address = array();
  4199. foreach ($values as $value) {
  4200. if (isset($mapping) && isset($mapping[$value])) {
  4201. $value = $mapping[$value];
  4202. }
  4203. $address = array_merge($address, explode(',', $value));
  4204. }
  4205. }
  4206. else {
  4207. $address = t('Value of "!component"', array('!component' => $node->webform['components'][$address]['name']));
  4208. }
  4209. }
  4210. // Convert single values to an array to simplify processing.
  4211. $address = is_array($address) ? $address : explode(',', $address);
  4212. $name = is_array($name) ? $name : array($name);
  4213. $name_shortage = count($address) - count($name);
  4214. if ($name_shortage > 0) {
  4215. $name += array_fill(count($name), $name_shortage, $name[0]);
  4216. }
  4217. foreach ($address as $key => $individual_address) {
  4218. $individual_address = trim($individual_address);
  4219. $individual_address = webform_replace_tokens($individual_address, $node, $submission);
  4220. $email_parts = webform_parse_email_address($individual_address);
  4221. if ($format == 'long' && !empty($name[$key]) && !strlen($email_parts['name'])) {
  4222. $individual_name = $name[$key];
  4223. $individual_name = webform_replace_tokens($individual_name, $node, $submission);
  4224. if ($encode) {
  4225. $individual_name = mime_header_encode($individual_name);
  4226. }
  4227. $individual_name = trim($individual_name);
  4228. $individual_address = '"' . $individual_name . '" <' . $individual_address . '>';
  4229. }
  4230. $address[$key] = $individual_address;
  4231. }
  4232. return $single ? reset($address) : $address;
  4233. }
  4234. /**
  4235. * Validates an email form element.
  4236. *
  4237. * @param string $emails
  4238. * An email or list of comma-seperated email addresses. Passed by reference.
  4239. * Empty emails will be eliminated, and mutiple addresses will be seperated
  4240. * with a comma and space.
  4241. * @param string $form_name
  4242. * The name of the form element to receive an error, in form_set_error format.
  4243. * @param bool $allow_empty
  4244. * TRUE if optional. FALSE if required.
  4245. * @param bool $allow_multiple
  4246. * TRUE if a list of emails is allowed. FALSE if only one.
  4247. * @param bool $allow_tokens
  4248. * TRUE if any token should be assumed to contain a valid e-mail address.
  4249. * @param string $format
  4250. * 'short', 'long', or NULL (for default) format. Long format has a name and
  4251. * the address in angle brackets.
  4252. *
  4253. * @return int|bool
  4254. * The number of valid addresses found, or FALSE for an invalid email found.
  4255. */
  4256. function webform_email_validate(&$emails, $form_name, $allow_empty, $allow_multiple, $allow_tokens, $format = NULL) {
  4257. $nr_valid = webform_valid_email_address($emails, $allow_tokens, $format);
  4258. if ($nr_valid === FALSE) {
  4259. form_set_error($form_name, t('The entered e-mail address "@email" does not appear valid.', array('@email' => $emails)));
  4260. }
  4261. elseif ($nr_valid === 0 && !$allow_empty) {
  4262. form_set_error($form_name, t('When adding a new custom e-mail, the e-mail field is required.'));
  4263. }
  4264. elseif ($nr_valid > 1 && !$allow_multiple) {
  4265. form_set_error($form_name, t('Only one e-mail address is allowed.'));
  4266. }
  4267. return $nr_valid;
  4268. }
  4269. /**
  4270. * Validates email address(es) with optional name(s).
  4271. *
  4272. * @param string $emails
  4273. * An email address, a list of comma-separated email addresses. If all the
  4274. * addresses are valid, the list of trimmed, non-empty emails is returned by
  4275. * reference.
  4276. * @param bool $allow_tokens
  4277. * TRUE if any token should be assumed to contain a valid e-mail address.
  4278. * @param string $format
  4279. * 'short', 'long', or NULL (for default) format. Long format has a name and
  4280. * the address in angle brackets.
  4281. *
  4282. * @return bool|int
  4283. * Returns FALSE if an invalid e-mail address was found, 0 if no email
  4284. * address(es) were found, or the number of valid e-mail addresses found.
  4285. */
  4286. function webform_valid_email_address(&$emails, $allow_tokens = FALSE, $format = NULL) {
  4287. $email_array = array_filter(array_map('trim', explode(',', $emails)));
  4288. $count = 0;
  4289. foreach ($email_array as $email) {
  4290. if ($allow_tokens && webform_variable_get('webform_token_access')) {
  4291. foreach (token_scan($email) as $tokens) {
  4292. foreach ($tokens as $token) {
  4293. $email = str_replace($token, 'admin@example.com', $email);
  4294. }
  4295. }
  4296. }
  4297. $matches = webform_parse_email_address($email, $format);
  4298. if (!valid_email_address($matches['address'])) {
  4299. return FALSE;
  4300. }
  4301. $count++;
  4302. }
  4303. $emails = implode(', ', $email_array);
  4304. return $count;
  4305. }
  4306. /**
  4307. * Parses an e-mail address into name and address.
  4308. *
  4309. * @param string $email
  4310. * The email address to be parsed, with an optional name.
  4311. * @param string $format
  4312. * 'short', 'long', or NULL (for default) format. Long format has a name and
  4313. * the address in angle brackets.
  4314. *
  4315. * @return array
  4316. * Associative array indexed by 'name' and 'address'.
  4317. */
  4318. function webform_parse_email_address($email, $format = NULL) {
  4319. if (!$format) {
  4320. $format = webform_variable_get('webform_email_address_format');
  4321. }
  4322. if ($format == 'long') {
  4323. // Match e-mails of the form 'My Name <email@domain.com>'.
  4324. preg_match('/^"?([^<]*?)"? *(?:<(.*)>)?$/', $email, $matches);
  4325. if (isset($matches[2]) && strlen($matches[2])) {
  4326. return array(
  4327. 'name' => $matches[1],
  4328. 'address' => $matches[2],
  4329. );
  4330. }
  4331. }
  4332. return array(
  4333. 'name' => '',
  4334. 'address' => $email,
  4335. );
  4336. }
  4337. /**
  4338. * Given an email subject, format it with any needed replacements.
  4339. */
  4340. function webform_format_email_subject($subject, $node = NULL, $submission = NULL) {
  4341. if ($subject == 'default') {
  4342. $subject = webform_variable_get('webform_default_subject');
  4343. }
  4344. elseif (is_numeric($subject) && isset($node->webform['components'][$subject])) {
  4345. $component = $node->webform['components'][$subject];
  4346. if (isset($submission->data[$subject])) {
  4347. $display_function = '_webform_display_' . $component['type'];
  4348. $value = $submission->data[$subject];
  4349. // Convert the value to a clean text representation if possible.
  4350. if (function_exists($display_function)) {
  4351. $display = $display_function($component, $value, 'text');
  4352. $display['#theme_wrappers'] = array();
  4353. $display['#webform_component'] = $component;
  4354. $subject = str_replace("\n", ' ', drupal_render($display));
  4355. }
  4356. else {
  4357. $subject = $value;
  4358. }
  4359. }
  4360. else {
  4361. $subject = t('Value of "!component"', array('!component' => $component['name']));
  4362. }
  4363. }
  4364. // Convert arrays to strings (may happen if checkboxes are used as the value).
  4365. if (is_array($subject)) {
  4366. $subject = reset($subject);
  4367. }
  4368. return webform_replace_tokens($subject, $node, $submission);
  4369. }
  4370. /**
  4371. * Convert an array of components into a tree.
  4372. */
  4373. function _webform_components_tree_build($src, &$tree, $parent, &$page_count) {
  4374. foreach ($src as $cid => $component) {
  4375. if ($component['pid'] == $parent) {
  4376. _webform_components_tree_build($src, $component, $cid, $page_count);
  4377. if ($component['type'] == 'pagebreak') {
  4378. $page_count++;
  4379. }
  4380. $tree['children'][$cid] = $component;
  4381. $tree['children'][$cid]['page_num'] = $page_count;
  4382. }
  4383. }
  4384. return $tree;
  4385. }
  4386. /**
  4387. * Flatten a component tree into a flat list.
  4388. */
  4389. function _webform_components_tree_flatten($tree) {
  4390. $components = array();
  4391. foreach ($tree as $cid => $component) {
  4392. if (isset($component['children'])) {
  4393. unset($component['children']);
  4394. $components[$cid] = $component;
  4395. // array_merge() can't be used here because the keys are numeric.
  4396. $children = _webform_components_tree_flatten($tree[$cid]['children']);
  4397. foreach ($children as $ccid => $ccomponent) {
  4398. $components[$ccid] = $ccomponent;
  4399. }
  4400. }
  4401. else {
  4402. $components[$cid] = $component;
  4403. }
  4404. }
  4405. return $components;
  4406. }
  4407. /**
  4408. * Helper for the uasort in webform_tree_sort()
  4409. */
  4410. function _webform_components_sort($a, $b) {
  4411. if ($a['weight'] == $b['weight']) {
  4412. return strcasecmp($a['name'], $b['name']);
  4413. }
  4414. return ($a['weight'] < $b['weight']) ? -1 : 1;
  4415. }
  4416. /**
  4417. * Sort each level of a component tree by weight and name.
  4418. */
  4419. function _webform_components_tree_sort($tree) {
  4420. if (isset($tree['children']) && is_array($tree['children'])) {
  4421. $children = array();
  4422. uasort($tree['children'], '_webform_components_sort');
  4423. foreach ($tree['children'] as $cid => $component) {
  4424. $children[$cid] = _webform_components_tree_sort($component);
  4425. }
  4426. $tree['children'] = $children;
  4427. }
  4428. return $tree;
  4429. }
  4430. /**
  4431. * Get a list of all available component definitions.
  4432. */
  4433. function webform_components($include_disabled = FALSE, $reset = FALSE) {
  4434. static $components, $enabled;
  4435. if (!isset($components) || $reset) {
  4436. $components = array();
  4437. $disabled = array_flip(webform_variable_get('webform_disabled_components'));
  4438. foreach (module_implements('webform_component_info') as $module) {
  4439. $module_components = module_invoke($module, 'webform_component_info');
  4440. foreach ($module_components as $type => $info) {
  4441. $module_components[$type]['module'] = $module;
  4442. $module_components[$type]['enabled'] = !array_key_exists($type, $disabled);
  4443. }
  4444. $components += $module_components;
  4445. }
  4446. drupal_alter('webform_component_info', $components);
  4447. uasort($components, function ($a, $b) {
  4448. return strnatcasecmp($a['label'], $b['label']);
  4449. });
  4450. $enabled = array_diff_key($components, $disabled);
  4451. }
  4452. return $include_disabled ? $components : $enabled;
  4453. }
  4454. /**
  4455. * Build a list of components suitable for use as select list options.
  4456. */
  4457. function webform_component_options($include_disabled = FALSE) {
  4458. $component_info = webform_components($include_disabled);
  4459. $options = array();
  4460. foreach ($component_info as $type => $info) {
  4461. $options[$type] = $info['label'];
  4462. }
  4463. return $options;
  4464. }
  4465. /**
  4466. * Load a component file into memory.
  4467. *
  4468. * @param $component_type
  4469. * The string machine name of a component.
  4470. */
  4471. function webform_component_include($component_type) {
  4472. static $included = array();
  4473. // No need to load components that have already been added once.
  4474. if (!isset($included[$component_type])) {
  4475. $components = webform_components(TRUE);
  4476. $included[$component_type] = TRUE;
  4477. if (isset($components[$component_type]['file'])) {
  4478. $info = $components[$component_type];
  4479. $pathinfo = pathinfo($info['file']);
  4480. $basename = basename($pathinfo['basename'], '.' . $pathinfo['extension']);
  4481. $path = (!empty($pathinfo['dirname']) ? $pathinfo['dirname'] . '/' : '') . $basename;
  4482. module_load_include($pathinfo['extension'], $info['module'], $path);
  4483. }
  4484. }
  4485. }
  4486. /**
  4487. * Invoke a component callback.
  4488. *
  4489. * @param $type
  4490. * The component type as a string.
  4491. * @param $callback
  4492. * The callback to execute.
  4493. * @param ...
  4494. * Any additional parameters required by the $callback.
  4495. *
  4496. * @return mixed
  4497. * Return value of the callback on success and FALSE on failure.
  4498. */
  4499. function webform_component_invoke($type, $callback) {
  4500. $args = func_get_args();
  4501. $type = array_shift($args);
  4502. $callback = array_shift($args);
  4503. $function = '_webform_' . $callback . '_' . $type;
  4504. webform_component_include($type);
  4505. if (function_exists($function)) {
  4506. return call_user_func_array($function, $args);
  4507. }
  4508. }
  4509. /**
  4510. * Check if a component implements a particular hook.
  4511. *
  4512. * @param $type
  4513. * The component type as a string.
  4514. * @param $callback
  4515. * The callback to check.
  4516. *
  4517. * @return bool
  4518. * Whether or not the hook is implemented.
  4519. */
  4520. function webform_component_implements($type, $callback) {
  4521. $function = '_webform_' . $callback . '_' . $type;
  4522. webform_component_include($type);
  4523. return function_exists($function);
  4524. }
  4525. /**
  4526. * Form API #process function to expand a webform conditional element.
  4527. */
  4528. function webform_conditional_expand($element) {
  4529. module_load_include('inc', 'webform', 'includes/webform.conditionals');
  4530. return _webform_conditional_expand($element);
  4531. }
  4532. /**
  4533. * Add class and wrapper class attributes to an element.
  4534. */
  4535. function _webform_component_classes(&$element, $component) {
  4536. if (isset($component['extra']['css_classes']) && drupal_strlen($component['extra']['css_classes'])) {
  4537. $element['#attributes']['class'] = isset($element['#attributes']['class']) ? $element['#attributes']['class'] : array();
  4538. $element['#attributes']['class'] = array_merge($element['#attributes']['class'], explode(' ', $component['extra']['css_classes']));
  4539. }
  4540. if (isset($component['extra']['wrapper_classes']) && drupal_strlen($component['extra']['wrapper_classes'])) {
  4541. $element['#wrapper_attributes']['class'] = isset($element['#wrapper_attributes']['class']) ? $element['#wrapper_attributes']['class'] : array();
  4542. $element['#wrapper_attributes']['class'] = array_merge($element['#wrapper_attributes']['class'], explode(' ', $component['extra']['wrapper_classes']));
  4543. }
  4544. }
  4545. /**
  4546. * Disable the Drupal page cache.
  4547. */
  4548. function webform_disable_page_cache() {
  4549. drupal_page_is_cacheable(FALSE);
  4550. }
  4551. /**
  4552. * Set the necessary breadcrumb for the page we are on.
  4553. *
  4554. * @param object $node
  4555. * The loaded webform node.
  4556. * @param bool|object $submission
  4557. * The submission if the current page is viewing or dealing with a submission,
  4558. * or TRUE to just include the webform node in the breadcrumbs (used for
  4559. * the submission completion confirmation page), or NULL for no extra
  4560. * processing.
  4561. */
  4562. function webform_set_breadcrumb($node, $submission = NULL) {
  4563. $node_path = "node/{$node->nid}";
  4564. // Set the href of the current menu item to be the node's path. This has two
  4565. // effects. The active trail will be to the node's prefered menu tree
  4566. // location, expanding the menu as appropriate. And the breadcrumbs will be
  4567. // set as if the current page were under the node's preferred location.
  4568. // Note that menu_tree_set_path() could be used to set the path for the menu,
  4569. // but it will not affect the breadcrumbs when the webform is not in the
  4570. // default menu.
  4571. menu_set_item(NULL, array('href' => $node_path) + menu_get_item());
  4572. if ($submission) {
  4573. $breadcrumb = menu_get_active_breadcrumb();
  4574. // Append the node title (or its menu name), in case it isn't in the path
  4575. // already.
  4576. $active_trail = menu_get_active_trail();
  4577. $last_active = end($active_trail);
  4578. $breadcrumb[] = $last_active['href'] === $node_path && !empty($last_active['in_active_trail'])
  4579. ? l($last_active['title'], $node_path, $last_active['localized_options'])
  4580. : l($node->title, $node_path);
  4581. // Setting the current menu href will cause the submission title and current
  4582. // tab (if not the default tab) to be added to the active path when the
  4583. // webform is in the default location in the menu (node/NID). The title
  4584. // is desirable, but the tab name (for example Edit or Delete) isn't.
  4585. if (preg_match('/href=".*"/', end($breadcrumb), $matches)) {
  4586. foreach ($breadcrumb as $index => $link) {
  4587. if (stripos($link, $matches[0]) !== FALSE) {
  4588. $breadcrumb = array_slice($breadcrumb, 0, $index + 1);
  4589. break;
  4590. }
  4591. }
  4592. }
  4593. // If the user is dealing with a submission, then the breadcrumb should
  4594. // be fudged to allow them to return to a likely list of webforms.
  4595. // Note that this isn't necessarily where they came from, but it's the
  4596. // best guess available.
  4597. if (is_object($submission)) {
  4598. if (webform_results_access($node)) {
  4599. $breadcrumb[] = l(t('Webform results'), $node_path . '/webform-results');
  4600. }
  4601. elseif (user_access('access own webform results')) {
  4602. $breadcrumb[] = l(t('Submissions'), $node_path . '/submissions');
  4603. }
  4604. }
  4605. drupal_set_breadcrumb($breadcrumb);
  4606. }
  4607. }
  4608. /**
  4609. * Convert an ISO 8601 date or time into an array.
  4610. *
  4611. * This converts full format dates or times. Either a date or time may be
  4612. * provided, in which case only those portions will be returned. Dashes and
  4613. * colons must be used, never implied.
  4614. *
  4615. * Formats:
  4616. * Dates: YYYY-MM-DD
  4617. * Times: HH:MM:SS
  4618. * Datetimes: YYYY-MM-DDTHH:MM:SS
  4619. *
  4620. * @param $string
  4621. * An ISO 8601 date, time, or datetime.
  4622. * @param $type
  4623. * If wanting only specific fields back, specify either "date" or "time".
  4624. * Leaving empty will return an array with both date and time keys, even if
  4625. * some are empty. Returns an array with the following keys:
  4626. * - year
  4627. * - month
  4628. * - day
  4629. * - hour (in 24hr notation)
  4630. * - minute
  4631. * - second
  4632. *
  4633. * @return array
  4634. * Date in array formate.
  4635. */
  4636. function webform_date_array($string, $type = NULL) {
  4637. $pattern = '/((\d{4}?)-(\d{2}?)-(\d{2}?))?(T?(\d{2}?):(\d{2}?):(\d{2}?))?/';
  4638. $matches = array();
  4639. preg_match($pattern, $string, $matches);
  4640. $matches += array_fill(0, 9, '');
  4641. $return = array();
  4642. // Check for a date string.
  4643. if ($type == 'date' || !isset($type)) {
  4644. $return['year'] = $matches[2] !== '' ? (int) $matches[2] : '';
  4645. $return['month'] = $matches[3] !== '' ? (int) $matches[3] : '';
  4646. $return['day'] = $matches[4] !== '' ? (int) $matches[4] : '';
  4647. }
  4648. // Check for a time string.
  4649. if ($type == 'time' || !isset($type)) {
  4650. $return['hour'] = $matches[6] !== '' ? (int) $matches[6] : '';
  4651. $return['minute'] = $matches[7] !== '' ? (int) $matches[7] : '';
  4652. $return['second'] = $matches[8] !== '' ? (int) $matches[8] : '';
  4653. }
  4654. return $return;
  4655. }
  4656. /**
  4657. * Convert an array of a date or time into an ISO 8601 compatible string.
  4658. *
  4659. * @param $array
  4660. * The array to convert to a date or time string.
  4661. * @param $type
  4662. * If wanting a specific string format back specify either "date" or "time".
  4663. * Otherwise a full ISO 8601 date and time string will be returned.
  4664. *
  4665. * @return string
  4666. * Date in string format
  4667. */
  4668. function webform_date_string($array, $type = NULL) {
  4669. $string = '';
  4670. if ($type == 'date' || !isset($type)) {
  4671. $string .= empty($array['year']) ? '0000' : sprintf('%04d', $array['year']);
  4672. $string .= '-';
  4673. $string .= empty($array['month']) ? '00' : sprintf('%02d', $array['month']);
  4674. $string .= '-';
  4675. $string .= empty($array['day']) ? '00' : sprintf('%02d', $array['day']);
  4676. }
  4677. if (!isset($type)) {
  4678. $string .= 'T';
  4679. }
  4680. if ($type == 'time' || !isset($type)) {
  4681. $string .= empty($array['hour']) ? '00' : sprintf('%02d', $array['hour']);
  4682. $string .= ':';
  4683. $string .= empty($array['minute']) ? '00' : sprintf('%02d', $array['minute']);
  4684. $string .= ':';
  4685. $string .= empty($array['second']) ? '00' : sprintf('%02d', $array['second']);
  4686. }
  4687. return $string;
  4688. }
  4689. /**
  4690. * Get a date format according to the site settings.
  4691. *
  4692. * @param $type
  4693. * A choice of 'short', 'medium', 'long' , or other user-defined date formats.
  4694. * Use NULL for the webform-specific date format choosen in the webform
  4695. * settings.
  4696. * @param array $exclude
  4697. * An array containing 'day', 'month', and/or 'year' if they should be
  4698. * removed from the format.
  4699. *
  4700. * @return string
  4701. * A date/time format string.
  4702. */
  4703. function webform_date_format($type = NULL, array $exclude = array()) {
  4704. static $formats = array();
  4705. $id = $type . ':' . implode('', $exclude);
  4706. if (!isset($formats[$id])) {
  4707. $type_name = $type ? $type : webform_variable_get('webform_date_type');
  4708. // Format date according to site's given format.
  4709. $format = variable_get('date_format_' . $type_name, 'D, m/d/Y');
  4710. // Date/Time formatting characters
  4711. // WHAT REQUIRED (at least 1) OPTIONAL (allowed but insufficient)
  4712. // -------------------------------------------------------------------------
  4713. // Day-of-week DlNw
  4714. // Day dj Stz
  4715. // Month FmMn
  4716. // Year oYy L
  4717. //
  4718. // NOT ALLOWED
  4719. // -------------------------------------------------------------------------
  4720. // Time aABgGhHisueIOPTZ
  4721. // Special /.,-: <space>
  4722. //
  4723. // Strip Time and Special characters from the beginning and end of format.
  4724. $date_format = trim($format, 'aABgGhHisueIOPTZ/.,-: ');
  4725. // Ensure that a day, month, and year value are present. Use a default
  4726. // format if all the values are not found. This regular expression uses
  4727. // (?= ), the positive lookahead assertion. It asserts that there are some
  4728. // optional characters (.*) followed by one of the day, month, or year
  4729. // characters. Because it is an assertion, it doesn't consume the
  4730. // characters, so the day, month, and year can be in any order.
  4731. if (!preg_match('/(?=.*[dj])(?=.*[FmMn])(?=.*[oYy])/', $date_format)) {
  4732. $date_format = 'm/d/Y';
  4733. }
  4734. // Remove any excluded portions.
  4735. $strip = array(
  4736. 'day' => 'DlNwdjStz',
  4737. 'month' => 'FmMn',
  4738. 'year' => 'oYyL',
  4739. );
  4740. foreach ($exclude as $field) {
  4741. // Strip the format and any trailing /.,-: or space.
  4742. $date_format = preg_replace('#[' . $strip[$field] . ']+[/\.,\-: ]*#', '', $date_format);
  4743. $date_format = trim($date_format, '/.,-: ');
  4744. }
  4745. $formats[$id] = $date_format;
  4746. }
  4747. return $formats[$id];
  4748. }
  4749. /**
  4750. * Return a date in the desired format taking into consideration user timezones.
  4751. */
  4752. function webform_strtodate($format, $string, $timezone_name = NULL, $reference_timestamp = NULL) {
  4753. global $user;
  4754. // Adjust the time based on the user or site timezone.
  4755. if (variable_get('configurable_timezones', 1) && $timezone_name == 'user' && $user->uid) {
  4756. $timezone_name = isset($GLOBALS['user']->timezone) ? $GLOBALS['user']->timezone : 'UTC';
  4757. }
  4758. // If the timezone is still empty or not set, use the site timezone.
  4759. if (empty($timezone_name) || $timezone_name == 'user') {
  4760. $timezone_name = variable_get('date_default_timezone', 'UTC');
  4761. }
  4762. if (!empty($timezone_name) && class_exists('DateTimeZone')) {
  4763. // Suppress errors if encountered during string conversion. Exceptions are
  4764. // only supported for DateTime in PHP 5.3 and higher.
  4765. try {
  4766. @$timezone = new DateTimeZone($timezone_name);
  4767. if (isset($reference_timestamp)) {
  4768. // A reference for relative dates has been provided.
  4769. // 1. Convert the reference timestamp (in UTC) to a DateTime.
  4770. // 2. Set to time zone to the user or system timezone, recreating the
  4771. // reference time in the appropriate time zone.
  4772. // 3. Set the time to midnight because when a non-referenced relative
  4773. // date is created without a time, it is created at midnight (0:00).
  4774. // 4. Adjust to the specified relative (or absolute) time.
  4775. @$datetime = new DateTime('@' . $reference_timestamp);
  4776. @$datetime->setTimezone($timezone)
  4777. ->setTime(0, 0, 0)
  4778. ->modify($string);
  4779. }
  4780. else {
  4781. @$datetime = new DateTime($string, $timezone);
  4782. }
  4783. return @$datetime->format($format);
  4784. }
  4785. catch (Exception $e) {
  4786. return '';
  4787. }
  4788. }
  4789. else {
  4790. return date($format, isset($reference_timestamp) ? strtotime($string, $reference_timestamp) : strtotime($string));
  4791. }
  4792. }
  4793. /**
  4794. * Get a timestamp in GMT time, ensuring timezone accuracy.
  4795. */
  4796. function webform_strtotime($date) {
  4797. $current_tz = date_default_timezone_get();
  4798. date_default_timezone_set('UTC');
  4799. $timestamp = strtotime($date);
  4800. date_default_timezone_set($current_tz);
  4801. return $timestamp;
  4802. }
  4803. /**
  4804. * Wrapper function for i18n_string() if i18nstrings enabled.
  4805. */
  4806. function webform_tt($name, $string, $langcode = NULL, $update = FALSE) {
  4807. if (function_exists('i18n_string')) {
  4808. $options = array(
  4809. 'langcode' => $langcode,
  4810. 'update' => $update,
  4811. );
  4812. return i18n_string($name, $string, $options);
  4813. }
  4814. else {
  4815. return $string;
  4816. }
  4817. }
  4818. /**
  4819. * Returns an IP Address or anonymized IP Address for confidential webforms.
  4820. */
  4821. function webform_ip_address($node) {
  4822. return $node->webform['confidential'] ? t('(unknown)') : ip_address();
  4823. }
  4824. /**
  4825. * Implements hook_views_api().
  4826. */
  4827. function webform_views_api() {
  4828. return array(
  4829. 'api' => 3.0,
  4830. 'path' => drupal_get_path('module', 'webform') . '/views',
  4831. );
  4832. }
  4833. /**
  4834. * Implements hook_views_default_views().
  4835. */
  4836. function webform_views_default_views() {
  4837. $path = './' . drupal_get_path('module', 'webform') . '/views/default_views/*.inc';
  4838. $views = array();
  4839. foreach (glob($path) as $views_filename) {
  4840. require_once $views_filename;
  4841. }
  4842. return $views;
  4843. }
  4844. /**
  4845. * Implements hook_field_extra_fields().
  4846. */
  4847. function webform_field_extra_fields() {
  4848. $extra = array();
  4849. foreach (webform_node_types() as $type) {
  4850. $extra['node'][$type]['display']['webform'] = array(
  4851. 'label' => t('Webform'),
  4852. 'description' => t('Webform client form.'),
  4853. 'weight' => 10,
  4854. );
  4855. }
  4856. return $extra;
  4857. }
  4858. /**
  4859. * Implements hook_date_views_extra_tables().
  4860. */
  4861. function webform_date_views_extra_tables() {
  4862. return array('webform_submissions' => 'webform_submissions');
  4863. }
  4864. /**
  4865. * Returns the next serial number for a given node and increments it.
  4866. *
  4867. * @param int $nid
  4868. * The nid of the node.
  4869. *
  4870. * @return int
  4871. * The next value of the serial number.
  4872. */
  4873. function _webform_submission_serial_next_value($nid) {
  4874. // Use a transaction with SELECT ... FOR UPDATE to lock the row between
  4875. // the SELECT and the UPDATE, ensuring that multiple Webform submissions
  4876. // at the same time do not have duplicate numbers. FOR UPDATE must be inside
  4877. // a transaction. The return value of db_transaction() must be assigned or the
  4878. // transaction will commit immediately. The transaction will commit when $txn
  4879. // goes out-of-scope.
  4880. $transaction = db_transaction();
  4881. // Get the next_serial value.
  4882. $next_serial = db_select('webform', 'w')
  4883. // Only add FOR UPDATE when incrementing.
  4884. ->forUpdate()
  4885. ->fields('w', array('next_serial'))
  4886. ->condition('nid', $nid)
  4887. ->execute()
  4888. ->fetchField();
  4889. // $next_serial must be greater than any existing serial number.
  4890. $next_serial = max($next_serial, _webform_submission_serial_next_value_used($nid));
  4891. // Increment the next_value.
  4892. db_update('webform')
  4893. ->fields(array('next_serial' => $next_serial + 1))
  4894. ->condition('nid', $nid)
  4895. ->execute();
  4896. return $next_serial;
  4897. }
  4898. /**
  4899. * Returns the next submission serial number to be used.
  4900. *
  4901. * This is based on the submissions in the database.
  4902. *
  4903. * @param int $nid
  4904. * The Node ID of the Webform.
  4905. *
  4906. * @return int
  4907. * The largest serial number used by a submission plus 1 for the specified
  4908. * node or 1 when there are no submissions.
  4909. */
  4910. function _webform_submission_serial_next_value_used($nid) {
  4911. $max_serial = db_select('webform_submissions');
  4912. $max_serial->addExpression('MAX(serial)');
  4913. $max_serial = $max_serial
  4914. ->condition('nid', $nid)
  4915. ->execute()
  4916. ->fetchField();
  4917. // $max_serial will be a numeric string or NULL.
  4918. return $max_serial + 1;
  4919. }
  4920. /**
  4921. * Alter the node before saving a clone.
  4922. *
  4923. * @param object $node
  4924. * Reference to the fully loaded node object being saved (the clone) that
  4925. * can be altered as needed.
  4926. * @param array $context
  4927. * An array of context describing the clone operation. The keys are:
  4928. * - 'method' : Can be either 'prepopulate' or 'save-edit'.
  4929. * - 'original_node' : The original fully loaded node object being cloned.
  4930. *
  4931. * @see clone_node_save()
  4932. * @see drupal_alter()
  4933. */
  4934. function webform_clone_node_alter(&$node, array $context) {
  4935. if (isset($node->webform)) {
  4936. $defaults = webform_node_defaults();
  4937. $node->webform['next_serial'] = $defaults['next_serial'];
  4938. }
  4939. }
  4940. /**
  4941. * Check if the last form submission exceeded the servers max_input_vars limit.
  4942. *
  4943. * Optionally preflight the current form to be returned in this request.
  4944. *
  4945. * @param array $form
  4946. * Reference to the form, which will be changed if $parent_key is set.
  4947. * @param array $form_state
  4948. * Form's state or NULL for no form state check.
  4949. * @param string $detect_key
  4950. * A key that will always be present in the posted data when an actual form
  4951. * submission has been made.
  4952. * @param string $parent_key
  4953. * Omit to not preflight the form, or the array key for the parent of where
  4954. * the preflight warning should be inserted into the form.
  4955. */
  4956. function webform_input_vars_check(array &$form, array $form_state, $detect_key, $parent_key = NULL) {
  4957. if (isset($parent_key)) {
  4958. $form['#pre_render'] = array('webform_pre_render_input_vars');
  4959. $form['#input_var_waring_parent'] = $parent_key;
  4960. }
  4961. if (!empty($form_state['input']) && array_key_exists($detect_key, $form_state['input']) && !array_key_exists('form_id', $form_state['input'])) {
  4962. // A form was submitted with POST, but the form_id was missing. The most
  4963. // likely cause of this is that the POST was truncated because PHP exceeded
  4964. // its max_input_vars limit.
  4965. $subs = array(
  4966. '@count' => webform_count_terminals($_POST),
  4967. '@limit' => (int) ini_get('max_input_vars'),
  4968. );
  4969. drupal_set_message(user_access('administer site configuration')
  4970. ? t('This form could not be submitted because $_POST was truncated to @count input vars. PHP max_input_vars is @limit and needs to be increased.', $subs)
  4971. : t('This form could not be submitted because it exceeds the server configuration. Contact the administrator.'),
  4972. 'error');
  4973. watchdog('webform',
  4974. 'POST truncated to @count input vars. PHP max_input_vars is @limit. Increase max_input_vars.',
  4975. $subs,
  4976. WATCHDOG_ERROR);
  4977. }
  4978. }
  4979. /**
  4980. * Checks the number of input form elements on this page.
  4981. *
  4982. * This ensures that the PHP max_input_vars limit is not exceeded.
  4983. *
  4984. * Install this function as a #pre_render function.
  4985. */
  4986. function webform_pre_render_input_vars($element) {
  4987. // Determine the limit on input vars for this server configuration.
  4988. $limit = ini_get('max_input_vars');
  4989. if ($limit) {
  4990. // Estimate the number of input vars needed to see if the PHP limit has been
  4991. // exceeded. Additional input_vars: op.
  4992. $count = 1 + webform_count_input_vars($element);
  4993. if ($count > $limit * 0.95) {
  4994. $subs = array(
  4995. '@count' => $count,
  4996. '@limit' => $limit,
  4997. );
  4998. $warning = array(
  4999. '#markup' => '<div class="messages warning">' .
  5000. (user_access('administer site configuration')
  5001. ? t('This form contains @count input elements. PHP max_input_vars is @limit and should be increased.', $subs)
  5002. : t('This form may be too long to work properly. Contact the administrator.'))
  5003. . '</div>',
  5004. '#weight' => -1,
  5005. );
  5006. if ($element['#input_var_waring_parent']) {
  5007. $element[$element['#input_var_waring_parent']]['input_vars_warning'] = $warning;
  5008. }
  5009. else {
  5010. $element['input_vars_warning'] = $warning;
  5011. }
  5012. watchdog('webform',
  5013. 'Page contains @count input elements but PHP max_input_vars is only @limit. Increase max_input_vars.',
  5014. $subs,
  5015. WATCHDOG_ERROR);
  5016. }
  5017. }
  5018. return $element;
  5019. }
  5020. /**
  5021. * Counts the number of input form elements.
  5022. *
  5023. * Note that this is somewhat imprecise. The number of input vars returned in
  5024. * $_POST can vary with the form element. For example, a multiple-select
  5025. * listbox returns one input var for each selection actually made.
  5026. *
  5027. * The primary use for this count is for the conditionals page, where only
  5028. * select, textfield, hidden, and token elements are used. If a more accurate
  5029. * count for webform_client_form is needed, a mechanism to predict the number
  5030. * of input elements for each component type and each component instance would
  5031. * be needed.
  5032. *
  5033. * @param array $element
  5034. * The form whose elements should be counted.
  5035. *
  5036. * @return int
  5037. * The number of elements in the form that will result in $_POST entries.
  5038. */
  5039. function webform_count_input_vars(array $element) {
  5040. static $input_types = array(
  5041. 'checkbox' => 1,
  5042. 'date' => 1,
  5043. 'file' => 1,
  5044. 'managed_file' => 1,
  5045. 'password' => 1,
  5046. 'password_confirm' => 1,
  5047. 'radios' => 1,
  5048. 'select' => 1,
  5049. 'textfield' => 1,
  5050. 'textarea' => 1,
  5051. 'token' => 1,
  5052. 'weight' => 1,
  5053. 'hidden' => 1,
  5054. 'value' => 1,
  5055. 'webform_email' => 1,
  5056. 'webform_number' => 1,
  5057. );
  5058. $children = array_intersect_key($element, array_flip(element_children($element)));
  5059. return $children
  5060. ? array_reduce($children, function ($carry, $item) {
  5061. return $carry + webform_count_input_vars($item);
  5062. }, 0)
  5063. : (isset($element['#type']) && isset($input_types[$element['#type']]) ? $input_types[$element['#type']] : 0);
  5064. }
  5065. /**
  5066. * Counts terminals in an array.
  5067. *
  5068. * Useful for counting how many input_vars were returned in $_POST.
  5069. *
  5070. * @param $a
  5071. * Array or array element to be counted
  5072. *
  5073. * @return int
  5074. * Number of non-array elements within $a.
  5075. */
  5076. function webform_count_terminals($a) {
  5077. return is_array($a)
  5078. ? array_reduce($a, function ($carry, $item) {
  5079. return $carry + webform_count_terminals($item);
  5080. }, 0)
  5081. : 1;
  5082. }