moxie.js 292 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713
  1. ;var MXI_DEBUG = true;
  2. /**
  3. * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
  4. * v1.5.5
  5. *
  6. * Copyright 2013, Moxiecode Systems AB
  7. * Released under GPL License.
  8. *
  9. * License: http://www.plupload.com/license
  10. * Contributing: http://www.plupload.com/contributing
  11. *
  12. * Date: 2017-08-26
  13. */
  14. ;(function (global, factory) {
  15. var extract = function() {
  16. var ctx = {};
  17. factory.apply(ctx, arguments);
  18. return ctx.moxie;
  19. };
  20. if (typeof define === "function" && define.amd) {
  21. define("moxie", [], extract);
  22. } else if (typeof module === "object" && module.exports) {
  23. module.exports = extract();
  24. } else {
  25. global.moxie = extract();
  26. }
  27. }(this || window, function() {
  28. /**
  29. * Compiled inline version. (Library mode)
  30. */
  31. /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
  32. /*globals $code */
  33. (function(exports, undefined) {
  34. "use strict";
  35. var modules = {};
  36. function require(ids, callback) {
  37. var module, defs = [];
  38. for (var i = 0; i < ids.length; ++i) {
  39. module = modules[ids[i]] || resolve(ids[i]);
  40. if (!module) {
  41. throw 'module definition dependecy not found: ' + ids[i];
  42. }
  43. defs.push(module);
  44. }
  45. callback.apply(null, defs);
  46. }
  47. function define(id, dependencies, definition) {
  48. if (typeof id !== 'string') {
  49. throw 'invalid module definition, module id must be defined and be a string';
  50. }
  51. if (dependencies === undefined) {
  52. throw 'invalid module definition, dependencies must be specified';
  53. }
  54. if (definition === undefined) {
  55. throw 'invalid module definition, definition function must be specified';
  56. }
  57. require(dependencies, function() {
  58. modules[id] = definition.apply(null, arguments);
  59. });
  60. }
  61. function defined(id) {
  62. return !!modules[id];
  63. }
  64. function resolve(id) {
  65. var target = exports;
  66. var fragments = id.split(/[.\/]/);
  67. for (var fi = 0; fi < fragments.length; ++fi) {
  68. if (!target[fragments[fi]]) {
  69. return;
  70. }
  71. target = target[fragments[fi]];
  72. }
  73. return target;
  74. }
  75. function expose(ids) {
  76. for (var i = 0; i < ids.length; i++) {
  77. var target = exports;
  78. var id = ids[i];
  79. var fragments = id.split(/[.\/]/);
  80. for (var fi = 0; fi < fragments.length - 1; ++fi) {
  81. if (target[fragments[fi]] === undefined) {
  82. target[fragments[fi]] = {};
  83. }
  84. target = target[fragments[fi]];
  85. }
  86. target[fragments[fragments.length - 1]] = modules[id];
  87. }
  88. }
  89. // Included from: src/javascript/core/utils/Basic.js
  90. /**
  91. * Basic.js
  92. *
  93. * Copyright 2013, Moxiecode Systems AB
  94. * Released under GPL License.
  95. *
  96. * License: http://www.plupload.com/license
  97. * Contributing: http://www.plupload.com/contributing
  98. */
  99. /**
  100. @class moxie/core/utils/Basic
  101. @public
  102. @static
  103. */
  104. define('moxie/core/utils/Basic', [], function() {
  105. /**
  106. Gets the true type of the built-in object (better version of typeof).
  107. @author Angus Croll (http://javascriptweblog.wordpress.com/)
  108. @method typeOf
  109. @static
  110. @param {Object} o Object to check.
  111. @return {String} Object [[Class]]
  112. */
  113. function typeOf(o) {
  114. var undef;
  115. if (o === undef) {
  116. return 'undefined';
  117. } else if (o === null) {
  118. return 'null';
  119. } else if (o.nodeType) {
  120. return 'node';
  121. }
  122. // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
  123. return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
  124. }
  125. /**
  126. Extends the specified object with another object(s).
  127. @method extend
  128. @static
  129. @param {Object} target Object to extend.
  130. @param {Object} [obj]* Multiple objects to extend with.
  131. @return {Object} Same as target, the extended object.
  132. */
  133. function extend() {
  134. return merge(false, false, arguments);
  135. }
  136. /**
  137. Extends the specified object with another object(s), but only if the property exists in the target.
  138. @method extendIf
  139. @static
  140. @param {Object} target Object to extend.
  141. @param {Object} [obj]* Multiple objects to extend with.
  142. @return {Object} Same as target, the extended object.
  143. */
  144. function extendIf() {
  145. return merge(true, false, arguments);
  146. }
  147. function extendImmutable() {
  148. return merge(false, true, arguments);
  149. }
  150. function extendImmutableIf() {
  151. return merge(true, true, arguments);
  152. }
  153. function clone(value) {
  154. switch (typeOf(value)) {
  155. case 'array':
  156. return merge(false, true, [[], value]);
  157. case 'object':
  158. return merge(false, true, [{}, value]);
  159. default:
  160. return value;
  161. }
  162. }
  163. function shallowCopy(obj) {
  164. switch (typeOf(obj)) {
  165. case 'array':
  166. return Array.prototype.slice.call(obj);
  167. case 'object':
  168. return extend({}, obj);
  169. }
  170. return obj;
  171. }
  172. function merge(strict, immutable, args) {
  173. var undef;
  174. var target = args[0];
  175. each(args, function(arg, i) {
  176. if (i > 0) {
  177. each(arg, function(value, key) {
  178. var isComplex = inArray(typeOf(value), ['array', 'object']) !== -1;
  179. if (value === undef || strict && target[key] === undef) {
  180. return true;
  181. }
  182. if (isComplex && immutable) {
  183. value = shallowCopy(value);
  184. }
  185. if (typeOf(target[key]) === typeOf(value) && isComplex) {
  186. merge(strict, immutable, [target[key], value]);
  187. } else {
  188. target[key] = value;
  189. }
  190. });
  191. }
  192. });
  193. return target;
  194. }
  195. /**
  196. A way to inherit one `class` from another in a consisstent way (more or less)
  197. @method inherit
  198. @static
  199. @since >1.4.1
  200. @param {Function} child
  201. @param {Function} parent
  202. @return {Function} Prepared constructor
  203. */
  204. function inherit(child, parent) {
  205. // copy over all parent properties
  206. for (var key in parent) {
  207. if ({}.hasOwnProperty.call(parent, key)) {
  208. child[key] = parent[key];
  209. }
  210. }
  211. // give child `class` a place to define its own methods
  212. function ctor() {
  213. this.constructor = child;
  214. if (MXI_DEBUG) {
  215. var getCtorName = function(fn) {
  216. var m = fn.toString().match(/^function\s([^\(\s]+)/);
  217. return m ? m[1] : false;
  218. };
  219. this.ctorName = getCtorName(child);
  220. }
  221. }
  222. ctor.prototype = parent.prototype;
  223. child.prototype = new ctor();
  224. // keep a way to reference parent methods
  225. child.super = parent.prototype;
  226. return child;
  227. }
  228. /**
  229. Executes the callback function for each item in array/object. If you return false in the
  230. callback it will break the loop.
  231. @method each
  232. @static
  233. @param {Object} obj Object to iterate.
  234. @param {function} callback Callback function to execute for each item.
  235. */
  236. function each(obj, callback) {
  237. var length, key, i, undef;
  238. if (obj) {
  239. try {
  240. length = obj.length;
  241. } catch(ex) {
  242. length = undef;
  243. }
  244. if (length === undef || typeof(length) !== 'number') {
  245. // Loop object items
  246. for (key in obj) {
  247. if (obj.hasOwnProperty(key)) {
  248. if (callback(obj[key], key) === false) {
  249. return;
  250. }
  251. }
  252. }
  253. } else {
  254. // Loop array items
  255. for (i = 0; i < length; i++) {
  256. if (callback(obj[i], i) === false) {
  257. return;
  258. }
  259. }
  260. }
  261. }
  262. }
  263. /**
  264. Checks if object is empty.
  265. @method isEmptyObj
  266. @static
  267. @param {Object} o Object to check.
  268. @return {Boolean}
  269. */
  270. function isEmptyObj(obj) {
  271. var prop;
  272. if (!obj || typeOf(obj) !== 'object') {
  273. return true;
  274. }
  275. for (prop in obj) {
  276. return false;
  277. }
  278. return true;
  279. }
  280. /**
  281. Recieve an array of functions (usually async) to call in sequence, each function
  282. receives a callback as first argument that it should call, when it completes. Finally,
  283. after everything is complete, main callback is called. Passing truthy value to the
  284. callback as a first argument will interrupt the sequence and invoke main callback
  285. immediately.
  286. @method inSeries
  287. @static
  288. @param {Array} queue Array of functions to call in sequence
  289. @param {Function} cb Main callback that is called in the end, or in case of error
  290. */
  291. function inSeries(queue, cb) {
  292. var i = 0, length = queue.length;
  293. if (typeOf(cb) !== 'function') {
  294. cb = function() {};
  295. }
  296. if (!queue || !queue.length) {
  297. cb();
  298. }
  299. function callNext(i) {
  300. if (typeOf(queue[i]) === 'function') {
  301. queue[i](function(error) {
  302. /*jshint expr:true */
  303. ++i < length && !error ? callNext(i) : cb(error);
  304. });
  305. }
  306. }
  307. callNext(i);
  308. }
  309. /**
  310. Recieve an array of functions (usually async) to call in parallel, each function
  311. receives a callback as first argument that it should call, when it completes. After
  312. everything is complete, main callback is called. Passing truthy value to the
  313. callback as a first argument will interrupt the process and invoke main callback
  314. immediately.
  315. @method inParallel
  316. @static
  317. @param {Array} queue Array of functions to call in sequence
  318. @param {Function} cb Main callback that is called in the end, or in case of erro
  319. */
  320. function inParallel(queue, cb) {
  321. var count = 0, num = queue.length, cbArgs = new Array(num);
  322. each(queue, function(fn, i) {
  323. fn(function(error) {
  324. if (error) {
  325. return cb(error);
  326. }
  327. var args = [].slice.call(arguments);
  328. args.shift(); // strip error - undefined or not
  329. cbArgs[i] = args;
  330. count++;
  331. if (count === num) {
  332. cbArgs.unshift(null);
  333. cb.apply(this, cbArgs);
  334. }
  335. });
  336. });
  337. }
  338. /**
  339. Find an element in array and return it's index if present, otherwise return -1.
  340. @method inArray
  341. @static
  342. @param {Mixed} needle Element to find
  343. @param {Array} array
  344. @return {Int} Index of the element, or -1 if not found
  345. */
  346. function inArray(needle, array) {
  347. if (array) {
  348. if (Array.prototype.indexOf) {
  349. return Array.prototype.indexOf.call(array, needle);
  350. }
  351. for (var i = 0, length = array.length; i < length; i++) {
  352. if (array[i] === needle) {
  353. return i;
  354. }
  355. }
  356. }
  357. return -1;
  358. }
  359. /**
  360. Returns elements of first array if they are not present in second. And false - otherwise.
  361. @private
  362. @method arrayDiff
  363. @param {Array} needles
  364. @param {Array} array
  365. @return {Array|Boolean}
  366. */
  367. function arrayDiff(needles, array) {
  368. var diff = [];
  369. if (typeOf(needles) !== 'array') {
  370. needles = [needles];
  371. }
  372. if (typeOf(array) !== 'array') {
  373. array = [array];
  374. }
  375. for (var i in needles) {
  376. if (inArray(needles[i], array) === -1) {
  377. diff.push(needles[i]);
  378. }
  379. }
  380. return diff.length ? diff : false;
  381. }
  382. /**
  383. Find intersection of two arrays.
  384. @private
  385. @method arrayIntersect
  386. @param {Array} array1
  387. @param {Array} array2
  388. @return {Array} Intersection of two arrays or null if there is none
  389. */
  390. function arrayIntersect(array1, array2) {
  391. var result = [];
  392. each(array1, function(item) {
  393. if (inArray(item, array2) !== -1) {
  394. result.push(item);
  395. }
  396. });
  397. return result.length ? result : null;
  398. }
  399. /**
  400. Forces anything into an array.
  401. @method toArray
  402. @static
  403. @param {Object} obj Object with length field.
  404. @return {Array} Array object containing all items.
  405. */
  406. function toArray(obj) {
  407. var i, arr = [];
  408. for (i = 0; i < obj.length; i++) {
  409. arr[i] = obj[i];
  410. }
  411. return arr;
  412. }
  413. /**
  414. Generates an unique ID. The only way a user would be able to get the same ID is if the two persons
  415. at the same exact millisecond manage to get the same 5 random numbers between 0-65535; it also uses
  416. a counter so each ID is guaranteed to be unique for the given page. It is more probable for the earth
  417. to be hit with an asteroid.
  418. @method guid
  419. @static
  420. @param {String} prefix to prepend (by default 'o' will be prepended).
  421. @method guid
  422. @return {String} Virtually unique id.
  423. */
  424. var guid = (function() {
  425. var counter = 0;
  426. return function(prefix) {
  427. var guid = new Date().getTime().toString(32), i;
  428. for (i = 0; i < 5; i++) {
  429. guid += Math.floor(Math.random() * 65535).toString(32);
  430. }
  431. return (prefix || 'o_') + guid + (counter++).toString(32);
  432. };
  433. }());
  434. /**
  435. Trims white spaces around the string
  436. @method trim
  437. @static
  438. @param {String} str
  439. @return {String}
  440. */
  441. function trim(str) {
  442. if (!str) {
  443. return str;
  444. }
  445. return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
  446. }
  447. /**
  448. Parses the specified size string into a byte value. For example 10kb becomes 10240.
  449. @method parseSizeStr
  450. @static
  451. @param {String/Number} size String to parse or number to just pass through.
  452. @return {Number} Size in bytes.
  453. */
  454. function parseSizeStr(size) {
  455. if (typeof(size) !== 'string') {
  456. return size;
  457. }
  458. var muls = {
  459. t: 1099511627776,
  460. g: 1073741824,
  461. m: 1048576,
  462. k: 1024
  463. },
  464. mul;
  465. size = /^([0-9\.]+)([tmgk]?)$/.exec(size.toLowerCase().replace(/[^0-9\.tmkg]/g, ''));
  466. mul = size[2];
  467. size = +size[1];
  468. if (muls.hasOwnProperty(mul)) {
  469. size *= muls[mul];
  470. }
  471. return Math.floor(size);
  472. }
  473. /**
  474. * Pseudo sprintf implementation - simple way to replace tokens with specified values.
  475. *
  476. * @param {String} str String with tokens
  477. * @return {String} String with replaced tokens
  478. */
  479. function sprintf(str) {
  480. var args = [].slice.call(arguments, 1);
  481. return str.replace(/%([a-z])/g, function($0, $1) {
  482. var value = args.shift();
  483. switch ($1) {
  484. case 's':
  485. return value + '';
  486. case 'd':
  487. return parseInt(value, 10);
  488. case 'f':
  489. return parseFloat(value);
  490. case 'c':
  491. return '';
  492. default:
  493. return value;
  494. }
  495. });
  496. }
  497. function delay(cb, timeout) {
  498. var self = this;
  499. setTimeout(function() {
  500. cb.call(self);
  501. }, timeout || 1);
  502. }
  503. return {
  504. guid: guid,
  505. typeOf: typeOf,
  506. extend: extend,
  507. extendIf: extendIf,
  508. extendImmutable: extendImmutable,
  509. extendImmutableIf: extendImmutableIf,
  510. clone: clone,
  511. inherit: inherit,
  512. each: each,
  513. isEmptyObj: isEmptyObj,
  514. inSeries: inSeries,
  515. inParallel: inParallel,
  516. inArray: inArray,
  517. arrayDiff: arrayDiff,
  518. arrayIntersect: arrayIntersect,
  519. toArray: toArray,
  520. trim: trim,
  521. sprintf: sprintf,
  522. parseSizeStr: parseSizeStr,
  523. delay: delay
  524. };
  525. });
  526. // Included from: src/javascript/core/utils/Encode.js
  527. /**
  528. * Encode.js
  529. *
  530. * Copyright 2013, Moxiecode Systems AB
  531. * Released under GPL License.
  532. *
  533. * License: http://www.plupload.com/license
  534. * Contributing: http://www.plupload.com/contributing
  535. */
  536. /**
  537. @class moxie/core/utils/Encode
  538. @public
  539. @static
  540. */
  541. define('moxie/core/utils/Encode', [], function() {
  542. /**
  543. Encode string with UTF-8
  544. @method utf8_encode
  545. @static
  546. @param {String} str String to encode
  547. @return {String} UTF-8 encoded string
  548. */
  549. var utf8_encode = function(str) {
  550. return unescape(encodeURIComponent(str));
  551. };
  552. /**
  553. Decode UTF-8 encoded string
  554. @method utf8_decode
  555. @static
  556. @param {String} str String to decode
  557. @return {String} Decoded string
  558. */
  559. var utf8_decode = function(str_data) {
  560. return decodeURIComponent(escape(str_data));
  561. };
  562. /**
  563. Decode Base64 encoded string (uses browser's default method if available),
  564. from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js
  565. @method atob
  566. @static
  567. @param {String} data String to decode
  568. @return {String} Decoded string
  569. */
  570. var atob = function(data, utf8) {
  571. if (typeof(window.atob) === 'function') {
  572. return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
  573. }
  574. // http://kevin.vanzonneveld.net
  575. // + original by: Tyler Akins (http://rumkin.com)
  576. // + improved by: Thunder.m
  577. // + input by: Aman Gupta
  578. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  579. // + bugfixed by: Onno Marsman
  580. // + bugfixed by: Pellentesque Malesuada
  581. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  582. // + input by: Brett Zamir (http://brett-zamir.me)
  583. // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  584. // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
  585. // * returns 1: 'Kevin van Zonneveld'
  586. // mozilla has this native
  587. // - but breaks in 2.0.0.12!
  588. //if (typeof this.window.atob == 'function') {
  589. // return atob(data);
  590. //}
  591. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  592. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  593. ac = 0,
  594. dec = "",
  595. tmp_arr = [];
  596. if (!data) {
  597. return data;
  598. }
  599. data += '';
  600. do { // unpack four hexets into three octets using index points in b64
  601. h1 = b64.indexOf(data.charAt(i++));
  602. h2 = b64.indexOf(data.charAt(i++));
  603. h3 = b64.indexOf(data.charAt(i++));
  604. h4 = b64.indexOf(data.charAt(i++));
  605. bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
  606. o1 = bits >> 16 & 0xff;
  607. o2 = bits >> 8 & 0xff;
  608. o3 = bits & 0xff;
  609. if (h3 == 64) {
  610. tmp_arr[ac++] = String.fromCharCode(o1);
  611. } else if (h4 == 64) {
  612. tmp_arr[ac++] = String.fromCharCode(o1, o2);
  613. } else {
  614. tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
  615. }
  616. } while (i < data.length);
  617. dec = tmp_arr.join('');
  618. return utf8 ? utf8_decode(dec) : dec;
  619. };
  620. /**
  621. Base64 encode string (uses browser's default method if available),
  622. from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js
  623. @method btoa
  624. @static
  625. @param {String} data String to encode
  626. @return {String} Base64 encoded string
  627. */
  628. var btoa = function(data, utf8) {
  629. if (utf8) {
  630. data = utf8_encode(data);
  631. }
  632. if (typeof(window.btoa) === 'function') {
  633. return window.btoa(data);
  634. }
  635. // http://kevin.vanzonneveld.net
  636. // + original by: Tyler Akins (http://rumkin.com)
  637. // + improved by: Bayron Guevara
  638. // + improved by: Thunder.m
  639. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  640. // + bugfixed by: Pellentesque Malesuada
  641. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  642. // + improved by: Rafał Kukawski (http://kukawski.pl)
  643. // * example 1: base64_encode('Kevin van Zonneveld');
  644. // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
  645. // mozilla has this native
  646. // - but breaks in 2.0.0.12!
  647. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  648. var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
  649. ac = 0,
  650. enc = "",
  651. tmp_arr = [];
  652. if (!data) {
  653. return data;
  654. }
  655. do { // pack three octets into four hexets
  656. o1 = data.charCodeAt(i++);
  657. o2 = data.charCodeAt(i++);
  658. o3 = data.charCodeAt(i++);
  659. bits = o1 << 16 | o2 << 8 | o3;
  660. h1 = bits >> 18 & 0x3f;
  661. h2 = bits >> 12 & 0x3f;
  662. h3 = bits >> 6 & 0x3f;
  663. h4 = bits & 0x3f;
  664. // use hexets to index into b64, and append result to encoded string
  665. tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
  666. } while (i < data.length);
  667. enc = tmp_arr.join('');
  668. var r = data.length % 3;
  669. return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
  670. };
  671. return {
  672. utf8_encode: utf8_encode,
  673. utf8_decode: utf8_decode,
  674. atob: atob,
  675. btoa: btoa
  676. };
  677. });
  678. // Included from: src/javascript/core/utils/Env.js
  679. /**
  680. * Env.js
  681. *
  682. * Copyright 2013, Moxiecode Systems AB
  683. * Released under GPL License.
  684. *
  685. * License: http://www.plupload.com/license
  686. * Contributing: http://www.plupload.com/contributing
  687. */
  688. /**
  689. @class moxie/core/utils/Env
  690. @public
  691. @static
  692. */
  693. define("moxie/core/utils/Env", [
  694. "moxie/core/utils/Basic"
  695. ], function(Basic) {
  696. /**
  697. * UAParser.js v0.7.7
  698. * Lightweight JavaScript-based User-Agent string parser
  699. * https://github.com/faisalman/ua-parser-js
  700. *
  701. * Copyright © 2012-2015 Faisal Salman <fyzlman@gmail.com>
  702. * Dual licensed under GPLv2 & MIT
  703. */
  704. var UAParser = (function (undefined) {
  705. //////////////
  706. // Constants
  707. /////////////
  708. var EMPTY = '',
  709. UNKNOWN = '?',
  710. FUNC_TYPE = 'function',
  711. UNDEF_TYPE = 'undefined',
  712. OBJ_TYPE = 'object',
  713. MAJOR = 'major',
  714. MODEL = 'model',
  715. NAME = 'name',
  716. TYPE = 'type',
  717. VENDOR = 'vendor',
  718. VERSION = 'version',
  719. ARCHITECTURE= 'architecture',
  720. CONSOLE = 'console',
  721. MOBILE = 'mobile',
  722. TABLET = 'tablet';
  723. ///////////
  724. // Helper
  725. //////////
  726. var util = {
  727. has : function (str1, str2) {
  728. return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
  729. },
  730. lowerize : function (str) {
  731. return str.toLowerCase();
  732. }
  733. };
  734. ///////////////
  735. // Map helper
  736. //////////////
  737. var mapper = {
  738. rgx : function () {
  739. // loop through all regexes maps
  740. for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {
  741. var regex = args[i], // even sequence (0,2,4,..)
  742. props = args[i + 1]; // odd sequence (1,3,5,..)
  743. // construct object barebones
  744. if (typeof(result) === UNDEF_TYPE) {
  745. result = {};
  746. for (p in props) {
  747. q = props[p];
  748. if (typeof(q) === OBJ_TYPE) {
  749. result[q[0]] = undefined;
  750. } else {
  751. result[q] = undefined;
  752. }
  753. }
  754. }
  755. // try matching uastring with regexes
  756. for (j = k = 0; j < regex.length; j++) {
  757. matches = regex[j].exec(this.getUA());
  758. if (!!matches) {
  759. for (p = 0; p < props.length; p++) {
  760. match = matches[++k];
  761. q = props[p];
  762. // check if given property is actually array
  763. if (typeof(q) === OBJ_TYPE && q.length > 0) {
  764. if (q.length == 2) {
  765. if (typeof(q[1]) == FUNC_TYPE) {
  766. // assign modified match
  767. result[q[0]] = q[1].call(this, match);
  768. } else {
  769. // assign given value, ignore regex match
  770. result[q[0]] = q[1];
  771. }
  772. } else if (q.length == 3) {
  773. // check whether function or regex
  774. if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
  775. // call function (usually string mapper)
  776. result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
  777. } else {
  778. // sanitize match using given regex
  779. result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
  780. }
  781. } else if (q.length == 4) {
  782. result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
  783. }
  784. } else {
  785. result[q] = match ? match : undefined;
  786. }
  787. }
  788. break;
  789. }
  790. }
  791. if(!!matches) break; // break the loop immediately if match found
  792. }
  793. return result;
  794. },
  795. str : function (str, map) {
  796. for (var i in map) {
  797. // check if array
  798. if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
  799. for (var j = 0; j < map[i].length; j++) {
  800. if (util.has(map[i][j], str)) {
  801. return (i === UNKNOWN) ? undefined : i;
  802. }
  803. }
  804. } else if (util.has(map[i], str)) {
  805. return (i === UNKNOWN) ? undefined : i;
  806. }
  807. }
  808. return str;
  809. }
  810. };
  811. ///////////////
  812. // String map
  813. //////////////
  814. var maps = {
  815. browser : {
  816. oldsafari : {
  817. major : {
  818. '1' : ['/8', '/1', '/3'],
  819. '2' : '/4',
  820. '?' : '/'
  821. },
  822. version : {
  823. '1.0' : '/8',
  824. '1.2' : '/1',
  825. '1.3' : '/3',
  826. '2.0' : '/412',
  827. '2.0.2' : '/416',
  828. '2.0.3' : '/417',
  829. '2.0.4' : '/419',
  830. '?' : '/'
  831. }
  832. }
  833. },
  834. device : {
  835. sprint : {
  836. model : {
  837. 'Evo Shift 4G' : '7373KT'
  838. },
  839. vendor : {
  840. 'HTC' : 'APA',
  841. 'Sprint' : 'Sprint'
  842. }
  843. }
  844. },
  845. os : {
  846. windows : {
  847. version : {
  848. 'ME' : '4.90',
  849. 'NT 3.11' : 'NT3.51',
  850. 'NT 4.0' : 'NT4.0',
  851. '2000' : 'NT 5.0',
  852. 'XP' : ['NT 5.1', 'NT 5.2'],
  853. 'Vista' : 'NT 6.0',
  854. '7' : 'NT 6.1',
  855. '8' : 'NT 6.2',
  856. '8.1' : 'NT 6.3',
  857. 'RT' : 'ARM'
  858. }
  859. }
  860. }
  861. };
  862. //////////////
  863. // Regex map
  864. /////////////
  865. var regexes = {
  866. browser : [[
  867. // Presto based
  868. /(opera\smini)\/([\w\.-]+)/i, // Opera Mini
  869. /(opera\s[mobiletab]+).+version\/([\w\.-]+)/i, // Opera Mobi/Tablet
  870. /(opera).+version\/([\w\.]+)/i, // Opera > 9.80
  871. /(opera)[\/\s]+([\w\.]+)/i // Opera < 9.80
  872. ], [NAME, VERSION], [
  873. /\s(opr)\/([\w\.]+)/i // Opera Webkit
  874. ], [[NAME, 'Opera'], VERSION], [
  875. // Mixed
  876. /(kindle)\/([\w\.]+)/i, // Kindle
  877. /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?([\w\.]+)*/i,
  878. // Lunascape/Maxthon/Netfront/Jasmine/Blazer
  879. // Trident based
  880. /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?([\w\.]*)/i,
  881. // Avant/IEMobile/SlimBrowser/Baidu
  882. /(?:ms|\()(ie)\s([\w\.]+)/i, // Internet Explorer
  883. // Webkit/KHTML based
  884. /(rekonq)\/([\w\.]+)*/i, // Rekonq
  885. /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi)\/([\w\.-]+)/i
  886. // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
  887. ], [NAME, VERSION], [
  888. /(trident).+rv[:\s]([\w\.]+).+like\sgecko/i // IE11
  889. ], [[NAME, 'IE'], VERSION], [
  890. /(edge)\/((\d+)?[\w\.]+)/i // Microsoft Edge
  891. ], [NAME, VERSION], [
  892. /(yabrowser)\/([\w\.]+)/i // Yandex
  893. ], [[NAME, 'Yandex'], VERSION], [
  894. /(comodo_dragon)\/([\w\.]+)/i // Comodo Dragon
  895. ], [[NAME, /_/g, ' '], VERSION], [
  896. /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?([\w\.]+)/i,
  897. // Chrome/OmniWeb/Arora/Tizen/Nokia
  898. /(uc\s?browser|qqbrowser)[\/\s]?([\w\.]+)/i
  899. // UCBrowser/QQBrowser
  900. ], [NAME, VERSION], [
  901. /(dolfin)\/([\w\.]+)/i // Dolphin
  902. ], [[NAME, 'Dolphin'], VERSION], [
  903. /((?:android.+)crmo|crios)\/([\w\.]+)/i // Chrome for Android/iOS
  904. ], [[NAME, 'Chrome'], VERSION], [
  905. /XiaoMi\/MiuiBrowser\/([\w\.]+)/i // MIUI Browser
  906. ], [VERSION, [NAME, 'MIUI Browser']], [
  907. /android.+version\/([\w\.]+)\s+(?:mobile\s?safari|safari)/i // Android Browser
  908. ], [VERSION, [NAME, 'Android Browser']], [
  909. /FBAV\/([\w\.]+);/i // Facebook App for iOS
  910. ], [VERSION, [NAME, 'Facebook']], [
  911. /version\/([\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
  912. ], [VERSION, [NAME, 'Mobile Safari']], [
  913. /version\/([\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
  914. ], [VERSION, NAME], [
  915. /webkit.+?(mobile\s?safari|safari)(\/[\w\.]+)/i // Safari < 3.0
  916. ], [NAME, [VERSION, mapper.str, maps.browser.oldsafari.version]], [
  917. /(konqueror)\/([\w\.]+)/i, // Konqueror
  918. /(webkit|khtml)\/([\w\.]+)/i
  919. ], [NAME, VERSION], [
  920. // Gecko based
  921. /(navigator|netscape)\/([\w\.-]+)/i // Netscape
  922. ], [[NAME, 'Netscape'], VERSION], [
  923. /(swiftfox)/i, // Swiftfox
  924. /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?([\w\.\+]+)/i,
  925. // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
  926. /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/([\w\.-]+)/i,
  927. // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
  928. /(mozilla)\/([\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
  929. // Other
  930. /(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf)[\/\s]?([\w\.]+)/i,
  931. // Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf
  932. /(links)\s\(([\w\.]+)/i, // Links
  933. /(gobrowser)\/?([\w\.]+)*/i, // GoBrowser
  934. /(ice\s?browser)\/v?([\w\._]+)/i, // ICE Browser
  935. /(mosaic)[\/\s]([\w\.]+)/i // Mosaic
  936. ], [NAME, VERSION]
  937. ],
  938. engine : [[
  939. /windows.+\sedge\/([\w\.]+)/i // EdgeHTML
  940. ], [VERSION, [NAME, 'EdgeHTML']], [
  941. /(presto)\/([\w\.]+)/i, // Presto
  942. /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
  943. /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
  944. /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
  945. ], [NAME, VERSION], [
  946. /rv\:([\w\.]+).*(gecko)/i // Gecko
  947. ], [VERSION, NAME]
  948. ],
  949. os : [[
  950. // Windows based
  951. /microsoft\s(windows)\s(vista|xp)/i // Windows (iTunes)
  952. ], [NAME, VERSION], [
  953. /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
  954. /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
  955. ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
  956. /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
  957. ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
  958. // Mobile/Embedded OS
  959. /\((bb)(10);/i // BlackBerry 10
  960. ], [[NAME, 'BlackBerry'], VERSION], [
  961. /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
  962. /(tizen)[\/\s]([\w\.]+)/i, // Tizen
  963. /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego|contiki)[\/\s-]?([\w\.]+)*/i,
  964. // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo/Contiki
  965. /linux;.+(sailfish);/i // Sailfish OS
  966. ], [NAME, VERSION], [
  967. /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
  968. ], [[NAME, 'Symbian'], VERSION], [
  969. /\((series40);/i // Series 40
  970. ], [NAME], [
  971. /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
  972. ], [[NAME, 'Firefox OS'], VERSION], [
  973. // Console
  974. /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation
  975. // GNU/Linux based
  976. /(mint)[\/\s\(]?(\w+)*/i, // Mint
  977. /(mageia|vectorlinux)[;\s]/i, // Mageia/VectorLinux
  978. /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk|linpus)[\/\s-]?([\w\.-]+)*/i,
  979. // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
  980. // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk/Linpus
  981. /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
  982. /(gnu)\s?([\w\.]+)*/i // GNU
  983. ], [NAME, VERSION], [
  984. /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
  985. ], [[NAME, 'Chromium OS'], VERSION],[
  986. // Solaris
  987. /(sunos)\s?([\w\.]+\d)*/i // Solaris
  988. ], [[NAME, 'Solaris'], VERSION], [
  989. // BSD based
  990. /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
  991. ], [NAME, VERSION],[
  992. /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS
  993. ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
  994. /(mac\sos\sx)\s?([\w\s\.]+\w)*/i,
  995. /(macintosh|mac(?=_powerpc)\s)/i // Mac OS
  996. ], [[NAME, 'Mac OS'], [VERSION, /_/g, '.']], [
  997. // Other
  998. /((?:open)?solaris)[\/\s-]?([\w\.]+)*/i, // Solaris
  999. /(haiku)\s(\w+)/i, // Haiku
  1000. /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
  1001. /(plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos|openvms)/i,
  1002. // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS/OpenVMS
  1003. /(unix)\s?([\w\.]+)*/i // UNIX
  1004. ], [NAME, VERSION]
  1005. ]
  1006. };
  1007. /////////////////
  1008. // Constructor
  1009. ////////////////
  1010. var UAParser = function (uastring) {
  1011. var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
  1012. this.getBrowser = function () {
  1013. return mapper.rgx.apply(this, regexes.browser);
  1014. };
  1015. this.getEngine = function () {
  1016. return mapper.rgx.apply(this, regexes.engine);
  1017. };
  1018. this.getOS = function () {
  1019. return mapper.rgx.apply(this, regexes.os);
  1020. };
  1021. this.getResult = function() {
  1022. return {
  1023. ua : this.getUA(),
  1024. browser : this.getBrowser(),
  1025. engine : this.getEngine(),
  1026. os : this.getOS()
  1027. };
  1028. };
  1029. this.getUA = function () {
  1030. return ua;
  1031. };
  1032. this.setUA = function (uastring) {
  1033. ua = uastring;
  1034. return this;
  1035. };
  1036. this.setUA(ua);
  1037. };
  1038. return UAParser;
  1039. })();
  1040. function version_compare(v1, v2, operator) {
  1041. // From: http://phpjs.org/functions
  1042. // + original by: Philippe Jausions (http://pear.php.net/user/jausions)
  1043. // + original by: Aidan Lister (http://aidanlister.com/)
  1044. // + reimplemented by: Kankrelune (http://www.webfaktory.info/)
  1045. // + improved by: Brett Zamir (http://brett-zamir.me)
  1046. // + improved by: Scott Baker
  1047. // + improved by: Theriault
  1048. // * example 1: version_compare('8.2.5rc', '8.2.5a');
  1049. // * returns 1: 1
  1050. // * example 2: version_compare('8.2.50', '8.2.52', '<');
  1051. // * returns 2: true
  1052. // * example 3: version_compare('5.3.0-dev', '5.3.0');
  1053. // * returns 3: -1
  1054. // * example 4: version_compare('4.1.0.52','4.01.0.51');
  1055. // * returns 4: 1
  1056. // Important: compare must be initialized at 0.
  1057. var i = 0,
  1058. x = 0,
  1059. compare = 0,
  1060. // vm maps textual PHP versions to negatives so they're less than 0.
  1061. // PHP currently defines these as CASE-SENSITIVE. It is important to
  1062. // leave these as negatives so that they can come before numerical versions
  1063. // and as if no letters were there to begin with.
  1064. // (1alpha is < 1 and < 1.1 but > 1dev1)
  1065. // If a non-numerical value can't be mapped to this table, it receives
  1066. // -7 as its value.
  1067. vm = {
  1068. 'dev': -6,
  1069. 'alpha': -5,
  1070. 'a': -5,
  1071. 'beta': -4,
  1072. 'b': -4,
  1073. 'RC': -3,
  1074. 'rc': -3,
  1075. '#': -2,
  1076. 'p': 1,
  1077. 'pl': 1
  1078. },
  1079. // This function will be called to prepare each version argument.
  1080. // It replaces every _, -, and + with a dot.
  1081. // It surrounds any nonsequence of numbers/dots with dots.
  1082. // It replaces sequences of dots with a single dot.
  1083. // version_compare('4..0', '4.0') == 0
  1084. // Important: A string of 0 length needs to be converted into a value
  1085. // even less than an unexisting value in vm (-7), hence [-8].
  1086. // It's also important to not strip spaces because of this.
  1087. // version_compare('', ' ') == 1
  1088. prepVersion = function (v) {
  1089. v = ('' + v).replace(/[_\-+]/g, '.');
  1090. v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
  1091. return (!v.length ? [-8] : v.split('.'));
  1092. },
  1093. // This converts a version component to a number.
  1094. // Empty component becomes 0.
  1095. // Non-numerical component becomes a negative number.
  1096. // Numerical component becomes itself as an integer.
  1097. numVersion = function (v) {
  1098. return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
  1099. };
  1100. v1 = prepVersion(v1);
  1101. v2 = prepVersion(v2);
  1102. x = Math.max(v1.length, v2.length);
  1103. for (i = 0; i < x; i++) {
  1104. if (v1[i] == v2[i]) {
  1105. continue;
  1106. }
  1107. v1[i] = numVersion(v1[i]);
  1108. v2[i] = numVersion(v2[i]);
  1109. if (v1[i] < v2[i]) {
  1110. compare = -1;
  1111. break;
  1112. } else if (v1[i] > v2[i]) {
  1113. compare = 1;
  1114. break;
  1115. }
  1116. }
  1117. if (!operator) {
  1118. return compare;
  1119. }
  1120. // Important: operator is CASE-SENSITIVE.
  1121. // "No operator" seems to be treated as "<."
  1122. // Any other values seem to make the function return null.
  1123. switch (operator) {
  1124. case '>':
  1125. case 'gt':
  1126. return (compare > 0);
  1127. case '>=':
  1128. case 'ge':
  1129. return (compare >= 0);
  1130. case '<=':
  1131. case 'le':
  1132. return (compare <= 0);
  1133. case '==':
  1134. case '=':
  1135. case 'eq':
  1136. return (compare === 0);
  1137. case '<>':
  1138. case '!=':
  1139. case 'ne':
  1140. return (compare !== 0);
  1141. case '':
  1142. case '<':
  1143. case 'lt':
  1144. return (compare < 0);
  1145. default:
  1146. return null;
  1147. }
  1148. }
  1149. var can = (function() {
  1150. var caps = {
  1151. access_global_ns: function () {
  1152. return !!window.moxie;
  1153. },
  1154. define_property: (function() {
  1155. /* // currently too much extra code required, not exactly worth it
  1156. try { // as of IE8, getters/setters are supported only on DOM elements
  1157. var obj = {};
  1158. if (Object.defineProperty) {
  1159. Object.defineProperty(obj, 'prop', {
  1160. enumerable: true,
  1161. configurable: true
  1162. });
  1163. return true;
  1164. }
  1165. } catch(ex) {}
  1166. if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
  1167. return true;
  1168. }*/
  1169. return false;
  1170. }()),
  1171. create_canvas: function() {
  1172. // On the S60 and BB Storm, getContext exists, but always returns undefined
  1173. // so we actually have to call getContext() to verify
  1174. // github.com/Modernizr/Modernizr/issues/issue/97/
  1175. var el = document.createElement('canvas');
  1176. var isSupported = !!(el.getContext && el.getContext('2d'));
  1177. caps.create_canvas = isSupported;
  1178. return isSupported;
  1179. },
  1180. return_response_type: function(responseType) {
  1181. try {
  1182. if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
  1183. return true;
  1184. } else if (window.XMLHttpRequest) {
  1185. var xhr = new XMLHttpRequest();
  1186. xhr.open('get', '/'); // otherwise Gecko throws an exception
  1187. if ('responseType' in xhr) {
  1188. xhr.responseType = responseType;
  1189. // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
  1190. if (xhr.responseType !== responseType) {
  1191. return false;
  1192. }
  1193. return true;
  1194. }
  1195. }
  1196. } catch (ex) {}
  1197. return false;
  1198. },
  1199. use_blob_uri: (function() {
  1200. var URL = window.URL;
  1201. return URL && 'createObjectURL' in URL && 'revokeObjectURL' in URL;
  1202. }()),
  1203. // ideas for this heavily come from Modernizr (http://modernizr.com/)
  1204. use_data_uri: (function() {
  1205. var du = new Image();
  1206. du.onload = function() {
  1207. caps.use_data_uri = (du.width === 1 && du.height === 1);
  1208. };
  1209. setTimeout(function() {
  1210. du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
  1211. }, 1);
  1212. return false;
  1213. }()),
  1214. use_data_uri_over32kb: function() { // IE8
  1215. return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
  1216. },
  1217. use_data_uri_of: function(bytes) {
  1218. return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
  1219. },
  1220. use_fileinput: function() {
  1221. if (navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/)) {
  1222. return false;
  1223. }
  1224. var el = document.createElement('input');
  1225. el.setAttribute('type', 'file');
  1226. return caps.use_fileinput = !el.disabled;
  1227. },
  1228. use_webgl: function() {
  1229. var canvas = document.createElement('canvas');
  1230. var gl = null, isSupported;
  1231. try {
  1232. gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
  1233. }
  1234. catch(e) {}
  1235. if (!gl) { // it seems that sometimes it doesn't throw exception, but still fails to get context
  1236. gl = null;
  1237. }
  1238. isSupported = !!gl;
  1239. caps.use_webgl = isSupported; // save result of our check
  1240. canvas = undefined;
  1241. return isSupported;
  1242. }
  1243. };
  1244. return function(cap) {
  1245. var args = [].slice.call(arguments);
  1246. args.shift(); // shift of cap
  1247. return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
  1248. };
  1249. }());
  1250. var uaResult = new UAParser().getResult();
  1251. var Env = {
  1252. can: can,
  1253. uaParser: UAParser,
  1254. browser: uaResult.browser.name,
  1255. version: uaResult.browser.version,
  1256. os: uaResult.os.name, // everybody intuitively types it in a lowercase for some reason
  1257. osVersion: uaResult.os.version,
  1258. verComp: version_compare,
  1259. swf_url: "../flash/Moxie.swf",
  1260. xap_url: "../silverlight/Moxie.xap",
  1261. global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
  1262. };
  1263. // for backward compatibility
  1264. // @deprecated Use `Env.os` instead
  1265. Env.OS = Env.os;
  1266. if (MXI_DEBUG) {
  1267. Env.debug = {
  1268. runtime: true,
  1269. events: false
  1270. };
  1271. Env.log = function() {
  1272. function logObj(data) {
  1273. // TODO: this should recursively print out the object in a pretty way
  1274. console.appendChild(document.createTextNode(data + "\n"));
  1275. }
  1276. if (window && window.console && window.console.log) {
  1277. window.console.log.apply(window.console, arguments);
  1278. } else if (document) {
  1279. var console = document.getElementById('moxie-console');
  1280. if (!console) {
  1281. console = document.createElement('pre');
  1282. console.id = 'moxie-console';
  1283. //console.style.display = 'none';
  1284. document.body.appendChild(console);
  1285. }
  1286. var data = arguments[0];
  1287. if (Basic.typeOf(data) === 'string') {
  1288. data = Basic.sprintf.apply(this, arguments);
  1289. } else if (Basic.inArray(Basic.typeOf(data), ['object', 'array']) !== -1) {
  1290. logObj(data);
  1291. return;
  1292. }
  1293. console.appendChild(document.createTextNode(data + "\n"));
  1294. }
  1295. };
  1296. }
  1297. return Env;
  1298. });
  1299. // Included from: src/javascript/core/Exceptions.js
  1300. /**
  1301. * Exceptions.js
  1302. *
  1303. * Copyright 2013, Moxiecode Systems AB
  1304. * Released under GPL License.
  1305. *
  1306. * License: http://www.plupload.com/license
  1307. * Contributing: http://www.plupload.com/contributing
  1308. */
  1309. define('moxie/core/Exceptions', [
  1310. 'moxie/core/utils/Basic'
  1311. ], function(Basic) {
  1312. function _findKey(obj, value) {
  1313. var key;
  1314. for (key in obj) {
  1315. if (obj[key] === value) {
  1316. return key;
  1317. }
  1318. }
  1319. return null;
  1320. }
  1321. /**
  1322. @class moxie/core/Exception
  1323. */
  1324. return {
  1325. RuntimeError: (function() {
  1326. var namecodes = {
  1327. NOT_INIT_ERR: 1,
  1328. EXCEPTION_ERR: 3,
  1329. NOT_SUPPORTED_ERR: 9,
  1330. JS_ERR: 4
  1331. };
  1332. function RuntimeError(code, message) {
  1333. this.code = code;
  1334. this.name = _findKey(namecodes, code);
  1335. this.message = this.name + (message || ": RuntimeError " + this.code);
  1336. }
  1337. Basic.extend(RuntimeError, namecodes);
  1338. RuntimeError.prototype = Error.prototype;
  1339. return RuntimeError;
  1340. }()),
  1341. OperationNotAllowedException: (function() {
  1342. function OperationNotAllowedException(code) {
  1343. this.code = code;
  1344. this.name = 'OperationNotAllowedException';
  1345. }
  1346. Basic.extend(OperationNotAllowedException, {
  1347. NOT_ALLOWED_ERR: 1
  1348. });
  1349. OperationNotAllowedException.prototype = Error.prototype;
  1350. return OperationNotAllowedException;
  1351. }()),
  1352. ImageError: (function() {
  1353. var namecodes = {
  1354. WRONG_FORMAT: 1,
  1355. MAX_RESOLUTION_ERR: 2,
  1356. INVALID_META_ERR: 3
  1357. };
  1358. function ImageError(code) {
  1359. this.code = code;
  1360. this.name = _findKey(namecodes, code);
  1361. this.message = this.name + ": ImageError " + this.code;
  1362. }
  1363. Basic.extend(ImageError, namecodes);
  1364. ImageError.prototype = Error.prototype;
  1365. return ImageError;
  1366. }()),
  1367. FileException: (function() {
  1368. var namecodes = {
  1369. NOT_FOUND_ERR: 1,
  1370. SECURITY_ERR: 2,
  1371. ABORT_ERR: 3,
  1372. NOT_READABLE_ERR: 4,
  1373. ENCODING_ERR: 5,
  1374. NO_MODIFICATION_ALLOWED_ERR: 6,
  1375. INVALID_STATE_ERR: 7,
  1376. SYNTAX_ERR: 8
  1377. };
  1378. function FileException(code) {
  1379. this.code = code;
  1380. this.name = _findKey(namecodes, code);
  1381. this.message = this.name + ": FileException " + this.code;
  1382. }
  1383. Basic.extend(FileException, namecodes);
  1384. FileException.prototype = Error.prototype;
  1385. return FileException;
  1386. }()),
  1387. DOMException: (function() {
  1388. var namecodes = {
  1389. INDEX_SIZE_ERR: 1,
  1390. DOMSTRING_SIZE_ERR: 2,
  1391. HIERARCHY_REQUEST_ERR: 3,
  1392. WRONG_DOCUMENT_ERR: 4,
  1393. INVALID_CHARACTER_ERR: 5,
  1394. NO_DATA_ALLOWED_ERR: 6,
  1395. NO_MODIFICATION_ALLOWED_ERR: 7,
  1396. NOT_FOUND_ERR: 8,
  1397. NOT_SUPPORTED_ERR: 9,
  1398. INUSE_ATTRIBUTE_ERR: 10,
  1399. INVALID_STATE_ERR: 11,
  1400. SYNTAX_ERR: 12,
  1401. INVALID_MODIFICATION_ERR: 13,
  1402. NAMESPACE_ERR: 14,
  1403. INVALID_ACCESS_ERR: 15,
  1404. VALIDATION_ERR: 16,
  1405. TYPE_MISMATCH_ERR: 17,
  1406. SECURITY_ERR: 18,
  1407. NETWORK_ERR: 19,
  1408. ABORT_ERR: 20,
  1409. URL_MISMATCH_ERR: 21,
  1410. QUOTA_EXCEEDED_ERR: 22,
  1411. TIMEOUT_ERR: 23,
  1412. INVALID_NODE_TYPE_ERR: 24,
  1413. DATA_CLONE_ERR: 25
  1414. };
  1415. function DOMException(code) {
  1416. this.code = code;
  1417. this.name = _findKey(namecodes, code);
  1418. this.message = this.name + ": DOMException " + this.code;
  1419. }
  1420. Basic.extend(DOMException, namecodes);
  1421. DOMException.prototype = Error.prototype;
  1422. return DOMException;
  1423. }()),
  1424. EventException: (function() {
  1425. function EventException(code) {
  1426. this.code = code;
  1427. this.name = 'EventException';
  1428. }
  1429. Basic.extend(EventException, {
  1430. UNSPECIFIED_EVENT_TYPE_ERR: 0
  1431. });
  1432. EventException.prototype = Error.prototype;
  1433. return EventException;
  1434. }())
  1435. };
  1436. });
  1437. // Included from: src/javascript/core/utils/Dom.js
  1438. /**
  1439. * Dom.js
  1440. *
  1441. * Copyright 2013, Moxiecode Systems AB
  1442. * Released under GPL License.
  1443. *
  1444. * License: http://www.plupload.com/license
  1445. * Contributing: http://www.plupload.com/contributing
  1446. */
  1447. /**
  1448. @class moxie/core/utils/Dom
  1449. @public
  1450. @static
  1451. */
  1452. define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {
  1453. /**
  1454. Get DOM Element by it's id.
  1455. @method get
  1456. @param {String} id Identifier of the DOM Element
  1457. @return {DOMElement}
  1458. */
  1459. var get = function(id) {
  1460. if (typeof id !== 'string') {
  1461. return id;
  1462. }
  1463. return document.getElementById(id);
  1464. };
  1465. /**
  1466. Checks if specified DOM element has specified class.
  1467. @method hasClass
  1468. @static
  1469. @param {Object} obj DOM element like object to add handler to.
  1470. @param {String} name Class name
  1471. */
  1472. var hasClass = function(obj, name) {
  1473. if (!obj.className) {
  1474. return false;
  1475. }
  1476. var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
  1477. return regExp.test(obj.className);
  1478. };
  1479. /**
  1480. Adds specified className to specified DOM element.
  1481. @method addClass
  1482. @static
  1483. @param {Object} obj DOM element like object to add handler to.
  1484. @param {String} name Class name
  1485. */
  1486. var addClass = function(obj, name) {
  1487. if (!hasClass(obj, name)) {
  1488. obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
  1489. }
  1490. };
  1491. /**
  1492. Removes specified className from specified DOM element.
  1493. @method removeClass
  1494. @static
  1495. @param {Object} obj DOM element like object to add handler to.
  1496. @param {String} name Class name
  1497. */
  1498. var removeClass = function(obj, name) {
  1499. if (obj.className) {
  1500. var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
  1501. obj.className = obj.className.replace(regExp, function($0, $1, $2) {
  1502. return $1 === ' ' && $2 === ' ' ? ' ' : '';
  1503. });
  1504. }
  1505. };
  1506. /**
  1507. Returns a given computed style of a DOM element.
  1508. @method getStyle
  1509. @static
  1510. @param {Object} obj DOM element like object.
  1511. @param {String} name Style you want to get from the DOM element
  1512. */
  1513. var getStyle = function(obj, name) {
  1514. if (obj.currentStyle) {
  1515. return obj.currentStyle[name];
  1516. } else if (window.getComputedStyle) {
  1517. return window.getComputedStyle(obj, null)[name];
  1518. }
  1519. };
  1520. /**
  1521. Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
  1522. @method getPos
  1523. @static
  1524. @param {Element} node HTML element or element id to get x, y position from.
  1525. @param {Element} root Optional root element to stop calculations at.
  1526. @return {object} Absolute position of the specified element object with x, y fields.
  1527. */
  1528. var getPos = function(node, root) {
  1529. var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
  1530. node = node;
  1531. root = root || doc.body;
  1532. // Returns the x, y cordinate for an element on IE 6 and IE 7
  1533. function getIEPos(node) {
  1534. var bodyElm, rect, x = 0, y = 0;
  1535. if (node) {
  1536. rect = node.getBoundingClientRect();
  1537. bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
  1538. x = rect.left + bodyElm.scrollLeft;
  1539. y = rect.top + bodyElm.scrollTop;
  1540. }
  1541. return {
  1542. x : x,
  1543. y : y
  1544. };
  1545. }
  1546. // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
  1547. if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
  1548. nodeRect = getIEPos(node);
  1549. rootRect = getIEPos(root);
  1550. return {
  1551. x : nodeRect.x - rootRect.x,
  1552. y : nodeRect.y - rootRect.y
  1553. };
  1554. }
  1555. parent = node;
  1556. while (parent && parent != root && parent.nodeType) {
  1557. x += parent.offsetLeft || 0;
  1558. y += parent.offsetTop || 0;
  1559. parent = parent.offsetParent;
  1560. }
  1561. parent = node.parentNode;
  1562. while (parent && parent != root && parent.nodeType) {
  1563. x -= parent.scrollLeft || 0;
  1564. y -= parent.scrollTop || 0;
  1565. parent = parent.parentNode;
  1566. }
  1567. return {
  1568. x : x,
  1569. y : y
  1570. };
  1571. };
  1572. /**
  1573. Returns the size of the specified node in pixels.
  1574. @method getSize
  1575. @static
  1576. @param {Node} node Node to get the size of.
  1577. @return {Object} Object with a w and h property.
  1578. */
  1579. var getSize = function(node) {
  1580. return {
  1581. w : node.offsetWidth || node.clientWidth,
  1582. h : node.offsetHeight || node.clientHeight
  1583. };
  1584. };
  1585. return {
  1586. get: get,
  1587. hasClass: hasClass,
  1588. addClass: addClass,
  1589. removeClass: removeClass,
  1590. getStyle: getStyle,
  1591. getPos: getPos,
  1592. getSize: getSize
  1593. };
  1594. });
  1595. // Included from: src/javascript/core/EventTarget.js
  1596. /**
  1597. * EventTarget.js
  1598. *
  1599. * Copyright 2013, Moxiecode Systems AB
  1600. * Released under GPL License.
  1601. *
  1602. * License: http://www.plupload.com/license
  1603. * Contributing: http://www.plupload.com/contributing
  1604. */
  1605. define('moxie/core/EventTarget', [
  1606. 'moxie/core/utils/Env',
  1607. 'moxie/core/Exceptions',
  1608. 'moxie/core/utils/Basic'
  1609. ], function(Env, x, Basic) {
  1610. // hash of event listeners by object uid
  1611. var eventpool = {};
  1612. /**
  1613. Parent object for all event dispatching components and objects
  1614. @class moxie/core/EventTarget
  1615. @constructor EventTarget
  1616. */
  1617. function EventTarget() {
  1618. /**
  1619. Unique id of the event dispatcher, usually overriden by children
  1620. @property uid
  1621. @type String
  1622. */
  1623. this.uid = Basic.guid();
  1624. }
  1625. Basic.extend(EventTarget.prototype, {
  1626. /**
  1627. Can be called from within a child in order to acquire uniqie id in automated manner
  1628. @method init
  1629. */
  1630. init: function() {
  1631. if (!this.uid) {
  1632. this.uid = Basic.guid('uid_');
  1633. }
  1634. },
  1635. /**
  1636. Register a handler to a specific event dispatched by the object
  1637. @method addEventListener
  1638. @param {String} type Type or basically a name of the event to subscribe to
  1639. @param {Function} fn Callback function that will be called when event happens
  1640. @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
  1641. @param {Object} [scope=this] A scope to invoke event handler in
  1642. */
  1643. addEventListener: function(type, fn, priority, scope) {
  1644. var self = this, list;
  1645. // without uid no event handlers can be added, so make sure we got one
  1646. if (!this.hasOwnProperty('uid')) {
  1647. this.uid = Basic.guid('uid_');
  1648. }
  1649. type = Basic.trim(type);
  1650. if (/\s/.test(type)) {
  1651. // multiple event types were passed for one handler
  1652. Basic.each(type.split(/\s+/), function(type) {
  1653. self.addEventListener(type, fn, priority, scope);
  1654. });
  1655. return;
  1656. }
  1657. type = type.toLowerCase();
  1658. priority = parseInt(priority, 10) || 0;
  1659. list = eventpool[this.uid] && eventpool[this.uid][type] || [];
  1660. list.push({fn : fn, priority : priority, scope : scope || this});
  1661. if (!eventpool[this.uid]) {
  1662. eventpool[this.uid] = {};
  1663. }
  1664. eventpool[this.uid][type] = list;
  1665. },
  1666. /**
  1667. Check if any handlers were registered to the specified event
  1668. @method hasEventListener
  1669. @param {String} [type] Type or basically a name of the event to check
  1670. @return {Mixed} Returns a handler if it was found and false, if - not
  1671. */
  1672. hasEventListener: function(type) {
  1673. var list;
  1674. if (type) {
  1675. type = type.toLowerCase();
  1676. list = eventpool[this.uid] && eventpool[this.uid][type];
  1677. } else {
  1678. list = eventpool[this.uid];
  1679. }
  1680. return list ? list : false;
  1681. },
  1682. /**
  1683. Unregister the handler from the event, or if former was not specified - unregister all handlers
  1684. @method removeEventListener
  1685. @param {String} type Type or basically a name of the event
  1686. @param {Function} [fn] Handler to unregister
  1687. */
  1688. removeEventListener: function(type, fn) {
  1689. var self = this, list, i;
  1690. type = type.toLowerCase();
  1691. if (/\s/.test(type)) {
  1692. // multiple event types were passed for one handler
  1693. Basic.each(type.split(/\s+/), function(type) {
  1694. self.removeEventListener(type, fn);
  1695. });
  1696. return;
  1697. }
  1698. list = eventpool[this.uid] && eventpool[this.uid][type];
  1699. if (list) {
  1700. if (fn) {
  1701. for (i = list.length - 1; i >= 0; i--) {
  1702. if (list[i].fn === fn) {
  1703. list.splice(i, 1);
  1704. break;
  1705. }
  1706. }
  1707. } else {
  1708. list = [];
  1709. }
  1710. // delete event list if it has become empty
  1711. if (!list.length) {
  1712. delete eventpool[this.uid][type];
  1713. // and object specific entry in a hash if it has no more listeners attached
  1714. if (Basic.isEmptyObj(eventpool[this.uid])) {
  1715. delete eventpool[this.uid];
  1716. }
  1717. }
  1718. }
  1719. },
  1720. /**
  1721. Remove all event handlers from the object
  1722. @method removeAllEventListeners
  1723. */
  1724. removeAllEventListeners: function() {
  1725. if (eventpool[this.uid]) {
  1726. delete eventpool[this.uid];
  1727. }
  1728. },
  1729. /**
  1730. Dispatch the event
  1731. @method dispatchEvent
  1732. @param {String/Object} Type of event or event object to dispatch
  1733. @param {Mixed} [...] Variable number of arguments to be passed to a handlers
  1734. @return {Boolean} true by default and false if any handler returned false
  1735. */
  1736. dispatchEvent: function(type) {
  1737. var uid, list, args, tmpEvt, evt = {}, result = true, undef;
  1738. if (Basic.typeOf(type) !== 'string') {
  1739. // we can't use original object directly (because of Silverlight)
  1740. tmpEvt = type;
  1741. if (Basic.typeOf(tmpEvt.type) === 'string') {
  1742. type = tmpEvt.type;
  1743. if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
  1744. evt.total = tmpEvt.total;
  1745. evt.loaded = tmpEvt.loaded;
  1746. }
  1747. evt.async = tmpEvt.async || false;
  1748. } else {
  1749. throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
  1750. }
  1751. }
  1752. // check if event is meant to be dispatched on an object having specific uid
  1753. if (type.indexOf('::') !== -1) {
  1754. (function(arr) {
  1755. uid = arr[0];
  1756. type = arr[1];
  1757. }(type.split('::')));
  1758. } else {
  1759. uid = this.uid;
  1760. }
  1761. type = type.toLowerCase();
  1762. list = eventpool[uid] && eventpool[uid][type];
  1763. if (list) {
  1764. // sort event list by prority
  1765. list.sort(function(a, b) { return b.priority - a.priority; });
  1766. args = [].slice.call(arguments);
  1767. // first argument will be pseudo-event object
  1768. args.shift();
  1769. evt.type = type;
  1770. args.unshift(evt);
  1771. if (MXI_DEBUG && Env.debug.events) {
  1772. Env.log("%cEvent '%s' fired on %s", 'color: #999;', evt.type, (this.ctorName ? this.ctorName + '::' : '') + uid);
  1773. }
  1774. // Dispatch event to all listeners
  1775. var queue = [];
  1776. Basic.each(list, function(handler) {
  1777. // explicitly set the target, otherwise events fired from shims do not get it
  1778. args[0].target = handler.scope;
  1779. // if event is marked as async, detach the handler
  1780. if (evt.async) {
  1781. queue.push(function(cb) {
  1782. setTimeout(function() {
  1783. cb(handler.fn.apply(handler.scope, args) === false);
  1784. }, 1);
  1785. });
  1786. } else {
  1787. queue.push(function(cb) {
  1788. cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
  1789. });
  1790. }
  1791. });
  1792. if (queue.length) {
  1793. Basic.inSeries(queue, function(err) {
  1794. result = !err;
  1795. });
  1796. }
  1797. }
  1798. return result;
  1799. },
  1800. /**
  1801. Register a handler to the event type that will run only once
  1802. @method bindOnce
  1803. @since >1.4.1
  1804. @param {String} type Type or basically a name of the event to subscribe to
  1805. @param {Function} fn Callback function that will be called when event happens
  1806. @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
  1807. @param {Object} [scope=this] A scope to invoke event handler in
  1808. */
  1809. bindOnce: function(type, fn, priority, scope) {
  1810. var self = this;
  1811. self.bind.call(this, type, function cb() {
  1812. self.unbind(type, cb);
  1813. return fn.apply(this, arguments);
  1814. }, priority, scope);
  1815. },
  1816. /**
  1817. Alias for addEventListener
  1818. @method bind
  1819. @protected
  1820. */
  1821. bind: function() {
  1822. this.addEventListener.apply(this, arguments);
  1823. },
  1824. /**
  1825. Alias for removeEventListener
  1826. @method unbind
  1827. @protected
  1828. */
  1829. unbind: function() {
  1830. this.removeEventListener.apply(this, arguments);
  1831. },
  1832. /**
  1833. Alias for removeAllEventListeners
  1834. @method unbindAll
  1835. @protected
  1836. */
  1837. unbindAll: function() {
  1838. this.removeAllEventListeners.apply(this, arguments);
  1839. },
  1840. /**
  1841. Alias for dispatchEvent
  1842. @method trigger
  1843. @protected
  1844. */
  1845. trigger: function() {
  1846. return this.dispatchEvent.apply(this, arguments);
  1847. },
  1848. /**
  1849. Handle properties of on[event] type.
  1850. @method handleEventProps
  1851. @private
  1852. */
  1853. handleEventProps: function(dispatches) {
  1854. var self = this;
  1855. this.bind(dispatches.join(' '), function(e) {
  1856. var prop = 'on' + e.type.toLowerCase();
  1857. if (Basic.typeOf(this[prop]) === 'function') {
  1858. this[prop].apply(this, arguments);
  1859. }
  1860. });
  1861. // object must have defined event properties, even if it doesn't make use of them
  1862. Basic.each(dispatches, function(prop) {
  1863. prop = 'on' + prop.toLowerCase(prop);
  1864. if (Basic.typeOf(self[prop]) === 'undefined') {
  1865. self[prop] = null;
  1866. }
  1867. });
  1868. }
  1869. });
  1870. EventTarget.instance = new EventTarget();
  1871. return EventTarget;
  1872. });
  1873. // Included from: src/javascript/runtime/Runtime.js
  1874. /**
  1875. * Runtime.js
  1876. *
  1877. * Copyright 2013, Moxiecode Systems AB
  1878. * Released under GPL License.
  1879. *
  1880. * License: http://www.plupload.com/license
  1881. * Contributing: http://www.plupload.com/contributing
  1882. */
  1883. define('moxie/runtime/Runtime', [
  1884. "moxie/core/utils/Env",
  1885. "moxie/core/utils/Basic",
  1886. "moxie/core/utils/Dom",
  1887. "moxie/core/EventTarget"
  1888. ], function(Env, Basic, Dom, EventTarget) {
  1889. var runtimeConstructors = {}, runtimes = {};
  1890. /**
  1891. Common set of methods and properties for every runtime instance
  1892. @class moxie/runtime/Runtime
  1893. @param {Object} options
  1894. @param {String} type Sanitized name of the runtime
  1895. @param {Object} [caps] Set of capabilities that differentiate specified runtime
  1896. @param {Object} [modeCaps] Set of capabilities that do require specific operational mode
  1897. @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
  1898. */
  1899. function Runtime(options, type, caps, modeCaps, preferredMode) {
  1900. /**
  1901. Dispatched when runtime is initialized and ready.
  1902. Results in RuntimeInit on a connected component.
  1903. @event Init
  1904. */
  1905. /**
  1906. Dispatched when runtime fails to initialize.
  1907. Results in RuntimeError on a connected component.
  1908. @event Error
  1909. */
  1910. var self = this
  1911. , _shim
  1912. , _uid = Basic.guid(type + '_')
  1913. , defaultMode = preferredMode || 'browser'
  1914. ;
  1915. options = options || {};
  1916. // register runtime in private hash
  1917. runtimes[_uid] = this;
  1918. /**
  1919. Default set of capabilities, which can be redifined later by specific runtime
  1920. @private
  1921. @property caps
  1922. @type Object
  1923. */
  1924. caps = Basic.extend({
  1925. // Runtime can:
  1926. // provide access to raw binary data of the file
  1927. access_binary: false,
  1928. // provide access to raw binary data of the image (image extension is optional)
  1929. access_image_binary: false,
  1930. // display binary data as thumbs for example
  1931. display_media: false,
  1932. // make cross-domain requests
  1933. do_cors: false,
  1934. // accept files dragged and dropped from the desktop
  1935. drag_and_drop: false,
  1936. // filter files in selection dialog by their extensions
  1937. filter_by_extension: true,
  1938. // resize image (and manipulate it raw data of any file in general)
  1939. resize_image: false,
  1940. // periodically report how many bytes of total in the file were uploaded (loaded)
  1941. report_upload_progress: false,
  1942. // provide access to the headers of http response
  1943. return_response_headers: false,
  1944. // support response of specific type, which should be passed as an argument
  1945. // e.g. runtime.can('return_response_type', 'blob')
  1946. return_response_type: false,
  1947. // return http status code of the response
  1948. return_status_code: true,
  1949. // send custom http header with the request
  1950. send_custom_headers: false,
  1951. // pick up the files from a dialog
  1952. select_file: false,
  1953. // select whole folder in file browse dialog
  1954. select_folder: false,
  1955. // select multiple files at once in file browse dialog
  1956. select_multiple: true,
  1957. // send raw binary data, that is generated after image resizing or manipulation of other kind
  1958. send_binary_string: false,
  1959. // send cookies with http request and therefore retain session
  1960. send_browser_cookies: true,
  1961. // send data formatted as multipart/form-data
  1962. send_multipart: true,
  1963. // slice the file or blob to smaller parts
  1964. slice_blob: false,
  1965. // upload file without preloading it to memory, stream it out directly from disk
  1966. stream_upload: false,
  1967. // programmatically trigger file browse dialog
  1968. summon_file_dialog: false,
  1969. // upload file of specific size, size should be passed as argument
  1970. // e.g. runtime.can('upload_filesize', '500mb')
  1971. upload_filesize: true,
  1972. // initiate http request with specific http method, method should be passed as argument
  1973. // e.g. runtime.can('use_http_method', 'put')
  1974. use_http_method: true
  1975. }, caps);
  1976. // default to the mode that is compatible with preferred caps
  1977. if (options.preferred_caps) {
  1978. defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
  1979. }
  1980. if (MXI_DEBUG && Env.debug.runtime) {
  1981. Env.log("\tdefault mode: %s", defaultMode);
  1982. }
  1983. // small extension factory here (is meant to be extended with actual extensions constructors)
  1984. _shim = (function() {
  1985. var objpool = {};
  1986. return {
  1987. exec: function(uid, comp, fn, args) {
  1988. if (_shim[comp]) {
  1989. if (!objpool[uid]) {
  1990. objpool[uid] = {
  1991. context: this,
  1992. instance: new _shim[comp]()
  1993. };
  1994. }
  1995. if (objpool[uid].instance[fn]) {
  1996. return objpool[uid].instance[fn].apply(this, args);
  1997. }
  1998. }
  1999. },
  2000. removeInstance: function(uid) {
  2001. delete objpool[uid];
  2002. },
  2003. removeAllInstances: function() {
  2004. var self = this;
  2005. Basic.each(objpool, function(obj, uid) {
  2006. if (Basic.typeOf(obj.instance.destroy) === 'function') {
  2007. obj.instance.destroy.call(obj.context);
  2008. }
  2009. self.removeInstance(uid);
  2010. });
  2011. }
  2012. };
  2013. }());
  2014. // public methods
  2015. Basic.extend(this, {
  2016. /**
  2017. Specifies whether runtime instance was initialized or not
  2018. @property initialized
  2019. @type {Boolean}
  2020. @default false
  2021. */
  2022. initialized: false, // shims require this flag to stop initialization retries
  2023. /**
  2024. Unique ID of the runtime
  2025. @property uid
  2026. @type {String}
  2027. */
  2028. uid: _uid,
  2029. /**
  2030. Runtime type (e.g. flash, html5, etc)
  2031. @property type
  2032. @type {String}
  2033. */
  2034. type: type,
  2035. /**
  2036. Runtime (not native one) may operate in browser or client mode.
  2037. @property mode
  2038. @private
  2039. @type {String|Boolean} current mode or false, if none possible
  2040. */
  2041. mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),
  2042. /**
  2043. id of the DOM container for the runtime (if available)
  2044. @property shimid
  2045. @type {String}
  2046. */
  2047. shimid: _uid + '_container',
  2048. /**
  2049. Number of connected clients. If equal to zero, runtime can be destroyed
  2050. @property clients
  2051. @type {Number}
  2052. */
  2053. clients: 0,
  2054. /**
  2055. Runtime initialization options
  2056. @property options
  2057. @type {Object}
  2058. */
  2059. options: options,
  2060. /**
  2061. Checks if the runtime has specific capability
  2062. @method can
  2063. @param {String} cap Name of capability to check
  2064. @param {Mixed} [value] If passed, capability should somehow correlate to the value
  2065. @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
  2066. @return {Boolean} true if runtime has such capability and false, if - not
  2067. */
  2068. can: function(cap, value) {
  2069. var refCaps = arguments[2] || caps;
  2070. // if cap var is a comma-separated list of caps, convert it to object (key/value)
  2071. if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
  2072. cap = Runtime.parseCaps(cap);
  2073. }
  2074. if (Basic.typeOf(cap) === 'object') {
  2075. for (var key in cap) {
  2076. if (!this.can(key, cap[key], refCaps)) {
  2077. return false;
  2078. }
  2079. }
  2080. return true;
  2081. }
  2082. // check the individual cap
  2083. if (Basic.typeOf(refCaps[cap]) === 'function') {
  2084. return refCaps[cap].call(this, value);
  2085. } else {
  2086. return (value === refCaps[cap]);
  2087. }
  2088. },
  2089. /**
  2090. Returns container for the runtime as DOM element
  2091. @method getShimContainer
  2092. @return {DOMElement}
  2093. */
  2094. getShimContainer: function() {
  2095. var container, shimContainer = Dom.get(this.shimid);
  2096. // if no container for shim, create one
  2097. if (!shimContainer) {
  2098. container = Dom.get(this.options.container) || document.body;
  2099. // create shim container and insert it at an absolute position into the outer container
  2100. shimContainer = document.createElement('div');
  2101. shimContainer.id = this.shimid;
  2102. shimContainer.className = 'moxie-shim moxie-shim-' + this.type;
  2103. Basic.extend(shimContainer.style, {
  2104. position: 'absolute',
  2105. top: '0px',
  2106. left: '0px',
  2107. width: '1px',
  2108. height: '1px',
  2109. overflow: 'hidden'
  2110. });
  2111. container.appendChild(shimContainer);
  2112. container = null;
  2113. }
  2114. return shimContainer;
  2115. },
  2116. /**
  2117. Returns runtime as DOM element (if appropriate)
  2118. @method getShim
  2119. @return {DOMElement}
  2120. */
  2121. getShim: function() {
  2122. return _shim;
  2123. },
  2124. /**
  2125. Invokes a method within the runtime itself (might differ across the runtimes)
  2126. @method shimExec
  2127. @param {Mixed} []
  2128. @protected
  2129. @return {Mixed} Depends on the action and component
  2130. */
  2131. shimExec: function(component, action) {
  2132. var args = [].slice.call(arguments, 2);
  2133. return self.getShim().exec.call(this, this.uid, component, action, args);
  2134. },
  2135. /**
  2136. Operaional interface that is used by components to invoke specific actions on the runtime
  2137. (is invoked in the scope of component)
  2138. @method exec
  2139. @param {Mixed} []*
  2140. @protected
  2141. @return {Mixed} Depends on the action and component
  2142. */
  2143. exec: function(component, action) { // this is called in the context of component, not runtime
  2144. var args = [].slice.call(arguments, 2);
  2145. if (self[component] && self[component][action]) {
  2146. return self[component][action].apply(this, args);
  2147. }
  2148. return self.shimExec.apply(this, arguments);
  2149. },
  2150. /**
  2151. Destroys the runtime (removes all events and deletes DOM structures)
  2152. @method destroy
  2153. */
  2154. destroy: function() {
  2155. if (!self) {
  2156. return; // obviously already destroyed
  2157. }
  2158. var shimContainer = Dom.get(this.shimid);
  2159. if (shimContainer) {
  2160. shimContainer.parentNode.removeChild(shimContainer);
  2161. }
  2162. if (_shim) {
  2163. _shim.removeAllInstances();
  2164. }
  2165. this.unbindAll();
  2166. delete runtimes[this.uid];
  2167. this.uid = null; // mark this runtime as destroyed
  2168. _uid = self = _shim = shimContainer = null;
  2169. }
  2170. });
  2171. // once we got the mode, test against all caps
  2172. if (this.mode && options.required_caps && !this.can(options.required_caps)) {
  2173. this.mode = false;
  2174. }
  2175. }
  2176. /**
  2177. Default order to try different runtime types
  2178. @property order
  2179. @type String
  2180. @static
  2181. */
  2182. Runtime.order = 'html5,flash,silverlight,html4';
  2183. /**
  2184. Retrieves runtime from private hash by it's uid
  2185. @method getRuntime
  2186. @private
  2187. @static
  2188. @param {String} uid Unique identifier of the runtime
  2189. @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
  2190. */
  2191. Runtime.getRuntime = function(uid) {
  2192. return runtimes[uid] ? runtimes[uid] : false;
  2193. };
  2194. /**
  2195. Register constructor for the Runtime of new (or perhaps modified) type
  2196. @method addConstructor
  2197. @static
  2198. @param {String} type Runtime type (e.g. flash, html5, etc)
  2199. @param {Function} construct Constructor for the Runtime type
  2200. */
  2201. Runtime.addConstructor = function(type, constructor) {
  2202. constructor.prototype = EventTarget.instance;
  2203. runtimeConstructors[type] = constructor;
  2204. };
  2205. /**
  2206. Get the constructor for the specified type.
  2207. method getConstructor
  2208. @static
  2209. @param {String} type Runtime type (e.g. flash, html5, etc)
  2210. @return {Function} Constructor for the Runtime type
  2211. */
  2212. Runtime.getConstructor = function(type) {
  2213. return runtimeConstructors[type] || null;
  2214. };
  2215. /**
  2216. Get info about the runtime (uid, type, capabilities)
  2217. @method getInfo
  2218. @static
  2219. @param {String} uid Unique identifier of the runtime
  2220. @return {Mixed} Info object or null if runtime doesn't exist
  2221. */
  2222. Runtime.getInfo = function(uid) {
  2223. var runtime = Runtime.getRuntime(uid);
  2224. if (runtime) {
  2225. return {
  2226. uid: runtime.uid,
  2227. type: runtime.type,
  2228. mode: runtime.mode,
  2229. can: function() {
  2230. return runtime.can.apply(runtime, arguments);
  2231. }
  2232. };
  2233. }
  2234. return null;
  2235. };
  2236. /**
  2237. Convert caps represented by a comma-separated string to the object representation.
  2238. @method parseCaps
  2239. @static
  2240. @param {String} capStr Comma-separated list of capabilities
  2241. @return {Object}
  2242. */
  2243. Runtime.parseCaps = function(capStr) {
  2244. var capObj = {};
  2245. if (Basic.typeOf(capStr) !== 'string') {
  2246. return capStr || {};
  2247. }
  2248. Basic.each(capStr.split(','), function(key) {
  2249. capObj[key] = true; // we assume it to be - true
  2250. });
  2251. return capObj;
  2252. };
  2253. /**
  2254. Test the specified runtime for specific capabilities.
  2255. @method can
  2256. @static
  2257. @param {String} type Runtime type (e.g. flash, html5, etc)
  2258. @param {String|Object} caps Set of capabilities to check
  2259. @return {Boolean} Result of the test
  2260. */
  2261. Runtime.can = function(type, caps) {
  2262. var runtime
  2263. , constructor = Runtime.getConstructor(type)
  2264. , mode
  2265. ;
  2266. if (constructor) {
  2267. runtime = new constructor({
  2268. required_caps: caps
  2269. });
  2270. mode = runtime.mode;
  2271. runtime.destroy();
  2272. return !!mode;
  2273. }
  2274. return false;
  2275. };
  2276. /**
  2277. Figure out a runtime that supports specified capabilities.
  2278. @method thatCan
  2279. @static
  2280. @param {String|Object} caps Set of capabilities to check
  2281. @param {String} [runtimeOrder] Comma-separated list of runtimes to check against
  2282. @return {String} Usable runtime identifier or null
  2283. */
  2284. Runtime.thatCan = function(caps, runtimeOrder) {
  2285. var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
  2286. for (var i in types) {
  2287. if (Runtime.can(types[i], caps)) {
  2288. return types[i];
  2289. }
  2290. }
  2291. return null;
  2292. };
  2293. /**
  2294. Figure out an operational mode for the specified set of capabilities.
  2295. @method getMode
  2296. @static
  2297. @param {Object} modeCaps Set of capabilities that depend on particular runtime mode
  2298. @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
  2299. @param {String|Boolean} [defaultMode='browser'] Default mode to use
  2300. @return {String|Boolean} Compatible operational mode
  2301. */
  2302. Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
  2303. var mode = null;
  2304. if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
  2305. defaultMode = 'browser';
  2306. }
  2307. if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
  2308. // loop over required caps and check if they do require the same mode
  2309. Basic.each(requiredCaps, function(value, cap) {
  2310. if (modeCaps.hasOwnProperty(cap)) {
  2311. var capMode = modeCaps[cap](value);
  2312. // make sure we always have an array
  2313. if (typeof(capMode) === 'string') {
  2314. capMode = [capMode];
  2315. }
  2316. if (!mode) {
  2317. mode = capMode;
  2318. } else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
  2319. // if cap requires conflicting mode - runtime cannot fulfill required caps
  2320. if (MXI_DEBUG && Env.debug.runtime) {
  2321. Env.log("\t\t%s: %s (conflicting mode requested: %s)", cap, value, capMode);
  2322. }
  2323. return (mode = false);
  2324. }
  2325. }
  2326. if (MXI_DEBUG && Env.debug.runtime) {
  2327. Env.log("\t\t%s: %s (compatible modes: %s)", cap, value, mode);
  2328. }
  2329. });
  2330. if (mode) {
  2331. return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
  2332. } else if (mode === false) {
  2333. return false;
  2334. }
  2335. }
  2336. return defaultMode;
  2337. };
  2338. /**
  2339. * Third party shims (Flash and Silverlight) require global event target against which they
  2340. * will fire their events. However when moxie is not loaded to global namespace, default
  2341. * event target is not accessible and we have to create artificial ones.
  2342. *
  2343. * @method getGlobalEventTarget
  2344. * @static
  2345. * @return {String} Name of the global event target
  2346. */
  2347. Runtime.getGlobalEventTarget = function() {
  2348. if (/^moxie\./.test(Env.global_event_dispatcher) && !Env.can('access_global_ns')) {
  2349. var uniqueCallbackName = Basic.guid('moxie_event_target_');
  2350. window[uniqueCallbackName] = function(e, data) {
  2351. EventTarget.instance.dispatchEvent(e, data);
  2352. };
  2353. Env.global_event_dispatcher = uniqueCallbackName;
  2354. }
  2355. return Env.global_event_dispatcher;
  2356. };
  2357. /**
  2358. Capability check that always returns true
  2359. @private
  2360. @static
  2361. @return {True}
  2362. */
  2363. Runtime.capTrue = function() {
  2364. return true;
  2365. };
  2366. /**
  2367. Capability check that always returns false
  2368. @private
  2369. @static
  2370. @return {False}
  2371. */
  2372. Runtime.capFalse = function() {
  2373. return false;
  2374. };
  2375. /**
  2376. Evaluate the expression to boolean value and create a function that always returns it.
  2377. @private
  2378. @static
  2379. @param {Mixed} expr Expression to evaluate
  2380. @return {Function} Function returning the result of evaluation
  2381. */
  2382. Runtime.capTest = function(expr) {
  2383. return function() {
  2384. return !!expr;
  2385. };
  2386. };
  2387. return Runtime;
  2388. });
  2389. // Included from: src/javascript/runtime/RuntimeClient.js
  2390. /**
  2391. * RuntimeClient.js
  2392. *
  2393. * Copyright 2013, Moxiecode Systems AB
  2394. * Released under GPL License.
  2395. *
  2396. * License: http://www.plupload.com/license
  2397. * Contributing: http://www.plupload.com/contributing
  2398. */
  2399. define('moxie/runtime/RuntimeClient', [
  2400. 'moxie/core/utils/Env',
  2401. 'moxie/core/Exceptions',
  2402. 'moxie/core/utils/Basic',
  2403. 'moxie/runtime/Runtime'
  2404. ], function(Env, x, Basic, Runtime) {
  2405. /**
  2406. Set of methods and properties, required by a component to acquire ability to connect to a runtime
  2407. @class moxie/runtime/RuntimeClient
  2408. */
  2409. return function RuntimeClient() {
  2410. var runtime;
  2411. Basic.extend(this, {
  2412. /**
  2413. Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
  2414. Increments number of clients connected to the specified runtime.
  2415. @private
  2416. @method connectRuntime
  2417. @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
  2418. */
  2419. connectRuntime: function(options) {
  2420. var comp = this, ruid;
  2421. function initialize(items) {
  2422. var type, constructor;
  2423. // if we ran out of runtimes
  2424. if (!items.length) {
  2425. comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  2426. runtime = null;
  2427. return;
  2428. }
  2429. type = items.shift().toLowerCase();
  2430. constructor = Runtime.getConstructor(type);
  2431. if (!constructor) {
  2432. if (MXI_DEBUG && Env.debug.runtime) {
  2433. Env.log("Constructor for '%s' runtime is not available.", type);
  2434. }
  2435. initialize(items);
  2436. return;
  2437. }
  2438. if (MXI_DEBUG && Env.debug.runtime) {
  2439. Env.log("Trying runtime: %s", type);
  2440. Env.log(options);
  2441. }
  2442. // try initializing the runtime
  2443. runtime = new constructor(options);
  2444. runtime.bind('Init', function() {
  2445. // mark runtime as initialized
  2446. runtime.initialized = true;
  2447. if (MXI_DEBUG && Env.debug.runtime) {
  2448. Env.log("Runtime '%s' initialized", runtime.type);
  2449. }
  2450. // jailbreak ...
  2451. setTimeout(function() {
  2452. runtime.clients++;
  2453. comp.ruid = runtime.uid;
  2454. // this will be triggered on component
  2455. comp.trigger('RuntimeInit', runtime);
  2456. }, 1);
  2457. });
  2458. runtime.bind('Error', function() {
  2459. if (MXI_DEBUG && Env.debug.runtime) {
  2460. Env.log("Runtime '%s' failed to initialize", runtime.type);
  2461. }
  2462. runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
  2463. initialize(items);
  2464. });
  2465. runtime.bind('Exception', function(e, err) {
  2466. var message = err.name + "(#" + err.code + ")" + (err.message ? ", from: " + err.message : '');
  2467. if (MXI_DEBUG && Env.debug.runtime) {
  2468. Env.log("Runtime '%s' has thrown an exception: %s", this.type, message);
  2469. }
  2470. comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.EXCEPTION_ERR, message));
  2471. });
  2472. if (MXI_DEBUG && Env.debug.runtime) {
  2473. Env.log("\tselected mode: %s", runtime.mode);
  2474. }
  2475. // check if runtime managed to pick-up operational mode
  2476. if (!runtime.mode) {
  2477. runtime.trigger('Error');
  2478. return;
  2479. }
  2480. runtime.init();
  2481. }
  2482. // check if a particular runtime was requested
  2483. if (Basic.typeOf(options) === 'string') {
  2484. ruid = options;
  2485. } else if (Basic.typeOf(options.ruid) === 'string') {
  2486. ruid = options.ruid;
  2487. }
  2488. if (ruid) {
  2489. runtime = Runtime.getRuntime(ruid);
  2490. if (runtime) {
  2491. comp.ruid = ruid;
  2492. runtime.clients++;
  2493. return runtime;
  2494. } else {
  2495. // there should be a runtime and there's none - weird case
  2496. throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
  2497. }
  2498. }
  2499. // initialize a fresh one, that fits runtime list and required features best
  2500. initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
  2501. },
  2502. /**
  2503. Disconnects from the runtime. Decrements number of clients connected to the specified runtime.
  2504. @private
  2505. @method disconnectRuntime
  2506. */
  2507. disconnectRuntime: function() {
  2508. if (runtime && --runtime.clients <= 0) {
  2509. runtime.destroy();
  2510. }
  2511. // once the component is disconnected, it shouldn't have access to the runtime
  2512. runtime = null;
  2513. },
  2514. /**
  2515. Returns the runtime to which the client is currently connected.
  2516. @method getRuntime
  2517. @return {Runtime} Runtime or null if client is not connected
  2518. */
  2519. getRuntime: function() {
  2520. if (runtime && runtime.uid) {
  2521. return runtime;
  2522. }
  2523. return runtime = null; // make sure we do not leave zombies rambling around
  2524. },
  2525. /**
  2526. Handy shortcut to safely invoke runtime extension methods.
  2527. @private
  2528. @method exec
  2529. @return {Mixed} Whatever runtime extension method returns
  2530. */
  2531. exec: function() {
  2532. return runtime ? runtime.exec.apply(this, arguments) : null;
  2533. },
  2534. /**
  2535. Test runtime client for specific capability
  2536. @method can
  2537. @param {String} cap
  2538. @return {Bool}
  2539. */
  2540. can: function(cap) {
  2541. return runtime ? runtime.can(cap) : false;
  2542. }
  2543. });
  2544. };
  2545. });
  2546. // Included from: src/javascript/file/Blob.js
  2547. /**
  2548. * Blob.js
  2549. *
  2550. * Copyright 2013, Moxiecode Systems AB
  2551. * Released under GPL License.
  2552. *
  2553. * License: http://www.plupload.com/license
  2554. * Contributing: http://www.plupload.com/contributing
  2555. */
  2556. define('moxie/file/Blob', [
  2557. 'moxie/core/utils/Basic',
  2558. 'moxie/core/utils/Encode',
  2559. 'moxie/runtime/RuntimeClient'
  2560. ], function(Basic, Encode, RuntimeClient) {
  2561. var blobpool = {};
  2562. /**
  2563. @class moxie/file/Blob
  2564. @constructor
  2565. @param {String} ruid Unique id of the runtime, to which this blob belongs to
  2566. @param {Object} blob Object "Native" blob object, as it is represented in the runtime
  2567. */
  2568. function Blob(ruid, blob) {
  2569. function _sliceDetached(start, end, type) {
  2570. var blob, data = blobpool[this.uid];
  2571. if (Basic.typeOf(data) !== 'string' || !data.length) {
  2572. return null; // or throw exception
  2573. }
  2574. blob = new Blob(null, {
  2575. type: type,
  2576. size: end - start
  2577. });
  2578. blob.detach(data.substr(start, blob.size));
  2579. return blob;
  2580. }
  2581. RuntimeClient.call(this);
  2582. if (ruid) {
  2583. this.connectRuntime(ruid);
  2584. }
  2585. if (!blob) {
  2586. blob = {};
  2587. } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
  2588. blob = { data: blob };
  2589. }
  2590. Basic.extend(this, {
  2591. /**
  2592. Unique id of the component
  2593. @property uid
  2594. @type {String}
  2595. */
  2596. uid: blob.uid || Basic.guid('uid_'),
  2597. /**
  2598. Unique id of the connected runtime, if falsy, then runtime will have to be initialized
  2599. before this Blob can be used, modified or sent
  2600. @property ruid
  2601. @type {String}
  2602. */
  2603. ruid: ruid,
  2604. /**
  2605. Size of blob
  2606. @property size
  2607. @type {Number}
  2608. @default 0
  2609. */
  2610. size: blob.size || 0,
  2611. /**
  2612. Mime type of blob
  2613. @property type
  2614. @type {String}
  2615. @default ''
  2616. */
  2617. type: blob.type || '',
  2618. /**
  2619. @method slice
  2620. @param {Number} [start=0]
  2621. */
  2622. slice: function(start, end, type) {
  2623. if (this.isDetached()) {
  2624. return _sliceDetached.apply(this, arguments);
  2625. }
  2626. return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
  2627. },
  2628. /**
  2629. Returns "native" blob object (as it is represented in connected runtime) or null if not found
  2630. @method getSource
  2631. @return {Blob} Returns "native" blob object or null if not found
  2632. */
  2633. getSource: function() {
  2634. if (!blobpool[this.uid]) {
  2635. return null;
  2636. }
  2637. return blobpool[this.uid];
  2638. },
  2639. /**
  2640. Detaches blob from any runtime that it depends on and initialize with standalone value
  2641. @method detach
  2642. @protected
  2643. @param {DOMString} [data=''] Standalone value
  2644. */
  2645. detach: function(data) {
  2646. if (this.ruid) {
  2647. this.getRuntime().exec.call(this, 'Blob', 'destroy');
  2648. this.disconnectRuntime();
  2649. this.ruid = null;
  2650. }
  2651. data = data || '';
  2652. // if dataUrl, convert to binary string
  2653. if (data.substr(0, 5) == 'data:') {
  2654. var base64Offset = data.indexOf(';base64,');
  2655. this.type = data.substring(5, base64Offset);
  2656. data = Encode.atob(data.substring(base64Offset + 8));
  2657. }
  2658. this.size = data.length;
  2659. blobpool[this.uid] = data;
  2660. },
  2661. /**
  2662. Checks if blob is standalone (detached of any runtime)
  2663. @method isDetached
  2664. @protected
  2665. @return {Boolean}
  2666. */
  2667. isDetached: function() {
  2668. return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
  2669. },
  2670. /**
  2671. Destroy Blob and free any resources it was using
  2672. @method destroy
  2673. */
  2674. destroy: function() {
  2675. this.detach();
  2676. delete blobpool[this.uid];
  2677. }
  2678. });
  2679. if (blob.data) {
  2680. this.detach(blob.data); // auto-detach if payload has been passed
  2681. } else {
  2682. blobpool[this.uid] = blob;
  2683. }
  2684. }
  2685. return Blob;
  2686. });
  2687. // Included from: src/javascript/core/I18n.js
  2688. /**
  2689. * I18n.js
  2690. *
  2691. * Copyright 2013, Moxiecode Systems AB
  2692. * Released under GPL License.
  2693. *
  2694. * License: http://www.plupload.com/license
  2695. * Contributing: http://www.plupload.com/contributing
  2696. */
  2697. define("moxie/core/I18n", [
  2698. "moxie/core/utils/Basic"
  2699. ], function(Basic) {
  2700. var i18n = {};
  2701. /**
  2702. @class moxie/core/I18n
  2703. */
  2704. return {
  2705. /**
  2706. * Extends the language pack object with new items.
  2707. *
  2708. * @param {Object} pack Language pack items to add.
  2709. * @return {Object} Extended language pack object.
  2710. */
  2711. addI18n: function(pack) {
  2712. return Basic.extend(i18n, pack);
  2713. },
  2714. /**
  2715. * Translates the specified string by checking for the english string in the language pack lookup.
  2716. *
  2717. * @param {String} str String to look for.
  2718. * @return {String} Translated string or the input string if it wasn't found.
  2719. */
  2720. translate: function(str) {
  2721. return i18n[str] || str;
  2722. },
  2723. /**
  2724. * Shortcut for translate function
  2725. *
  2726. * @param {String} str String to look for.
  2727. * @return {String} Translated string or the input string if it wasn't found.
  2728. */
  2729. _: function(str) {
  2730. return this.translate(str);
  2731. },
  2732. /**
  2733. * Pseudo sprintf implementation - simple way to replace tokens with specified values.
  2734. *
  2735. * @param {String} str String with tokens
  2736. * @return {String} String with replaced tokens
  2737. */
  2738. sprintf: function(str) {
  2739. var args = [].slice.call(arguments, 1);
  2740. return str.replace(/%[a-z]/g, function() {
  2741. var value = args.shift();
  2742. return Basic.typeOf(value) !== 'undefined' ? value : '';
  2743. });
  2744. }
  2745. };
  2746. });
  2747. // Included from: src/javascript/core/utils/Mime.js
  2748. /**
  2749. * Mime.js
  2750. *
  2751. * Copyright 2013, Moxiecode Systems AB
  2752. * Released under GPL License.
  2753. *
  2754. * License: http://www.plupload.com/license
  2755. * Contributing: http://www.plupload.com/contributing
  2756. */
  2757. /**
  2758. @class moxie/core/utils/Mime
  2759. @public
  2760. @static
  2761. */
  2762. define("moxie/core/utils/Mime", [
  2763. "moxie/core/utils/Basic",
  2764. "moxie/core/I18n"
  2765. ], function(Basic, I18n) {
  2766. var mimeData = "" +
  2767. "application/msword,doc dot," +
  2768. "application/pdf,pdf," +
  2769. "application/pgp-signature,pgp," +
  2770. "application/postscript,ps ai eps," +
  2771. "application/rtf,rtf," +
  2772. "application/vnd.ms-excel,xls xlb xlt xla," +
  2773. "application/vnd.ms-powerpoint,ppt pps pot ppa," +
  2774. "application/zip,zip," +
  2775. "application/x-shockwave-flash,swf swfl," +
  2776. "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
  2777. "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
  2778. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
  2779. "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
  2780. "application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
  2781. "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
  2782. "application/x-javascript,js," +
  2783. "application/json,json," +
  2784. "audio/mpeg,mp3 mpga mpega mp2," +
  2785. "audio/x-wav,wav," +
  2786. "audio/x-m4a,m4a," +
  2787. "audio/ogg,oga ogg," +
  2788. "audio/aiff,aiff aif," +
  2789. "audio/flac,flac," +
  2790. "audio/aac,aac," +
  2791. "audio/ac3,ac3," +
  2792. "audio/x-ms-wma,wma," +
  2793. "image/bmp,bmp," +
  2794. "image/gif,gif," +
  2795. "image/jpeg,jpg jpeg jpe," +
  2796. "image/photoshop,psd," +
  2797. "image/png,png," +
  2798. "image/svg+xml,svg svgz," +
  2799. "image/tiff,tiff tif," +
  2800. "text/plain,asc txt text diff log," +
  2801. "text/html,htm html xhtml," +
  2802. "text/css,css," +
  2803. "text/csv,csv," +
  2804. "text/rtf,rtf," +
  2805. "video/mpeg,mpeg mpg mpe m2v," +
  2806. "video/quicktime,qt mov," +
  2807. "video/mp4,mp4," +
  2808. "video/x-m4v,m4v," +
  2809. "video/x-flv,flv," +
  2810. "video/x-ms-wmv,wmv," +
  2811. "video/avi,avi," +
  2812. "video/webm,webm," +
  2813. "video/3gpp,3gpp 3gp," +
  2814. "video/3gpp2,3g2," +
  2815. "video/vnd.rn-realvideo,rv," +
  2816. "video/ogg,ogv," +
  2817. "video/x-matroska,mkv," +
  2818. "application/vnd.oasis.opendocument.formula-template,otf," +
  2819. "application/octet-stream,exe";
  2820. var Mime = {
  2821. /**
  2822. * Map of mimes to extensions
  2823. *
  2824. * @property mimes
  2825. * @type {Object}
  2826. */
  2827. mimes: {},
  2828. /**
  2829. * Map of extensions to mimes
  2830. *
  2831. * @property extensions
  2832. * @type {Object}
  2833. */
  2834. extensions: {},
  2835. /**
  2836. * Parses mimeData string into a mimes and extensions lookup maps. String should have the
  2837. * following format:
  2838. *
  2839. * application/msword,doc dot,application/pdf,pdf, ...
  2840. *
  2841. * so mime-type followed by comma and followed by space-separated list of associated extensions,
  2842. * then comma again and then another mime-type, etc.
  2843. *
  2844. * If invoked externally will replace override internal lookup maps with user-provided data.
  2845. *
  2846. * @method addMimeType
  2847. * @param {String} mimeData
  2848. */
  2849. addMimeType: function (mimeData) {
  2850. var items = mimeData.split(/,/), i, ii, ext;
  2851. for (i = 0; i < items.length; i += 2) {
  2852. ext = items[i + 1].split(/ /);
  2853. // extension to mime lookup
  2854. for (ii = 0; ii < ext.length; ii++) {
  2855. this.mimes[ext[ii]] = items[i];
  2856. }
  2857. // mime to extension lookup
  2858. this.extensions[items[i]] = ext;
  2859. }
  2860. },
  2861. extList2mimes: function (filters, addMissingExtensions) {
  2862. var self = this, ext, i, ii, type, mimes = [];
  2863. // convert extensions to mime types list
  2864. for (i = 0; i < filters.length; i++) {
  2865. ext = filters[i].extensions.toLowerCase().split(/\s*,\s*/);
  2866. for (ii = 0; ii < ext.length; ii++) {
  2867. // if there's an asterisk in the list, then accept attribute is not required
  2868. if (ext[ii] === '*') {
  2869. return [];
  2870. }
  2871. type = self.mimes[ext[ii]];
  2872. // future browsers should filter by extension, finally
  2873. if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
  2874. mimes.push('.' + ext[ii]);
  2875. } else if (type && Basic.inArray(type, mimes) === -1) {
  2876. mimes.push(type);
  2877. } else if (!type) {
  2878. // if we have no type in our map, then accept all
  2879. return [];
  2880. }
  2881. }
  2882. }
  2883. return mimes;
  2884. },
  2885. mimes2exts: function(mimes) {
  2886. var self = this, exts = [];
  2887. Basic.each(mimes, function(mime) {
  2888. mime = mime.toLowerCase();
  2889. if (mime === '*') {
  2890. exts = [];
  2891. return false;
  2892. }
  2893. // check if this thing looks like mime type
  2894. var m = mime.match(/^(\w+)\/(\*|\w+)$/);
  2895. if (m) {
  2896. if (m[2] === '*') {
  2897. // wildcard mime type detected
  2898. Basic.each(self.extensions, function(arr, mime) {
  2899. if ((new RegExp('^' + m[1] + '/')).test(mime)) {
  2900. [].push.apply(exts, self.extensions[mime]);
  2901. }
  2902. });
  2903. } else if (self.extensions[mime]) {
  2904. [].push.apply(exts, self.extensions[mime]);
  2905. }
  2906. }
  2907. });
  2908. return exts;
  2909. },
  2910. mimes2extList: function(mimes) {
  2911. var accept = [], exts = [];
  2912. if (Basic.typeOf(mimes) === 'string') {
  2913. mimes = Basic.trim(mimes).split(/\s*,\s*/);
  2914. }
  2915. exts = this.mimes2exts(mimes);
  2916. accept.push({
  2917. title: I18n.translate('Files'),
  2918. extensions: exts.length ? exts.join(',') : '*'
  2919. });
  2920. return accept;
  2921. },
  2922. /**
  2923. * Extract extension from the given filename
  2924. *
  2925. * @method getFileExtension
  2926. * @param {String} fileName
  2927. * @return {String} File extension
  2928. */
  2929. getFileExtension: function(fileName) {
  2930. var matches = fileName && fileName.match(/\.([^.]+)$/);
  2931. if (matches) {
  2932. return matches[1].toLowerCase();
  2933. }
  2934. return '';
  2935. },
  2936. /**
  2937. * Get file mime-type from it's filename - will try to match the extension
  2938. * against internal mime-type lookup map
  2939. *
  2940. * @method getFileMime
  2941. * @param {String} fileName
  2942. * @return File mime-type if found or an empty string if not
  2943. */
  2944. getFileMime: function(fileName) {
  2945. return this.mimes[this.getFileExtension(fileName)] || '';
  2946. }
  2947. };
  2948. Mime.addMimeType(mimeData);
  2949. return Mime;
  2950. });
  2951. // Included from: src/javascript/file/FileInput.js
  2952. /**
  2953. * FileInput.js
  2954. *
  2955. * Copyright 2013, Moxiecode Systems AB
  2956. * Released under GPL License.
  2957. *
  2958. * License: http://www.plupload.com/license
  2959. * Contributing: http://www.plupload.com/contributing
  2960. */
  2961. define('moxie/file/FileInput', [
  2962. 'moxie/core/utils/Basic',
  2963. 'moxie/core/utils/Env',
  2964. 'moxie/core/utils/Mime',
  2965. 'moxie/core/utils/Dom',
  2966. 'moxie/core/Exceptions',
  2967. 'moxie/core/EventTarget',
  2968. 'moxie/core/I18n',
  2969. 'moxie/runtime/Runtime',
  2970. 'moxie/runtime/RuntimeClient'
  2971. ], function(Basic, Env, Mime, Dom, x, EventTarget, I18n, Runtime, RuntimeClient) {
  2972. /**
  2973. Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
  2974. converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
  2975. with _FileReader_ or uploaded to a server through _XMLHttpRequest_.
  2976. @class moxie/file/FileInput
  2977. @constructor
  2978. @extends EventTarget
  2979. @uses RuntimeClient
  2980. @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
  2981. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
  2982. @param {Array} [options.accept] Array of mime types to accept. By default accepts all.
  2983. @param {Boolean} [options.multiple=false] Enable selection of multiple files.
  2984. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
  2985. @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode
  2986. for _browse\_button_.
  2987. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.
  2988. @example
  2989. <div id="container">
  2990. <a id="file-picker" href="javascript:;">Browse...</a>
  2991. </div>
  2992. <script>
  2993. var fileInput = new moxie.file.FileInput({
  2994. browse_button: 'file-picker', // or document.getElementById('file-picker')
  2995. container: 'container',
  2996. accept: [
  2997. {title: "Image files", extensions: "jpg,gif,png"} // accept only images
  2998. ],
  2999. multiple: true // allow multiple file selection
  3000. });
  3001. fileInput.onchange = function(e) {
  3002. // do something to files array
  3003. console.info(e.target.files); // or this.files or fileInput.files
  3004. };
  3005. fileInput.init(); // initialize
  3006. </script>
  3007. */
  3008. var dispatches = [
  3009. /**
  3010. Dispatched when runtime is connected and file-picker is ready to be used.
  3011. @event ready
  3012. @param {Object} event
  3013. */
  3014. 'ready',
  3015. /**
  3016. Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked.
  3017. Check [corresponding documentation entry](#method_refresh) for more info.
  3018. @event refresh
  3019. @param {Object} event
  3020. */
  3021. /**
  3022. Dispatched when selection of files in the dialog is complete.
  3023. @event change
  3024. @param {Object} event
  3025. */
  3026. 'change',
  3027. 'cancel', // TODO: might be useful
  3028. /**
  3029. Dispatched when mouse cursor enters file-picker area. Can be used to style element
  3030. accordingly.
  3031. @event mouseenter
  3032. @param {Object} event
  3033. */
  3034. 'mouseenter',
  3035. /**
  3036. Dispatched when mouse cursor leaves file-picker area. Can be used to style element
  3037. accordingly.
  3038. @event mouseleave
  3039. @param {Object} event
  3040. */
  3041. 'mouseleave',
  3042. /**
  3043. Dispatched when functional mouse button is pressed on top of file-picker area.
  3044. @event mousedown
  3045. @param {Object} event
  3046. */
  3047. 'mousedown',
  3048. /**
  3049. Dispatched when functional mouse button is released on top of file-picker area.
  3050. @event mouseup
  3051. @param {Object} event
  3052. */
  3053. 'mouseup'
  3054. ];
  3055. function FileInput(options) {
  3056. if (MXI_DEBUG) {
  3057. Env.log("Instantiating FileInput...");
  3058. }
  3059. var container, browseButton, defaults;
  3060. // if flat argument passed it should be browse_button id
  3061. if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
  3062. options = { browse_button : options };
  3063. }
  3064. // this will help us to find proper default container
  3065. browseButton = Dom.get(options.browse_button);
  3066. if (!browseButton) {
  3067. // browse button is required
  3068. throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
  3069. }
  3070. // figure out the options
  3071. defaults = {
  3072. accept: [{
  3073. title: I18n.translate('All Files'),
  3074. extensions: '*'
  3075. }],
  3076. multiple: false,
  3077. required_caps: false,
  3078. container: browseButton.parentNode || document.body
  3079. };
  3080. options = Basic.extend({}, defaults, options);
  3081. // convert to object representation
  3082. if (typeof(options.required_caps) === 'string') {
  3083. options.required_caps = Runtime.parseCaps(options.required_caps);
  3084. }
  3085. // normalize accept option (could be list of mime types or array of title/extensions pairs)
  3086. if (typeof(options.accept) === 'string') {
  3087. options.accept = Mime.mimes2extList(options.accept);
  3088. }
  3089. container = Dom.get(options.container);
  3090. // make sure we have container
  3091. if (!container) {
  3092. container = document.body;
  3093. }
  3094. // make container relative, if it's not
  3095. if (Dom.getStyle(container, 'position') === 'static') {
  3096. container.style.position = 'relative';
  3097. }
  3098. container = browseButton = null; // IE
  3099. RuntimeClient.call(this);
  3100. Basic.extend(this, {
  3101. /**
  3102. Unique id of the component
  3103. @property uid
  3104. @protected
  3105. @readOnly
  3106. @type {String}
  3107. @default UID
  3108. */
  3109. uid: Basic.guid('uid_'),
  3110. /**
  3111. Unique id of the connected runtime, if any.
  3112. @property ruid
  3113. @protected
  3114. @type {String}
  3115. */
  3116. ruid: null,
  3117. /**
  3118. Unique id of the runtime container. Useful to get hold of it for various manipulations.
  3119. @property shimid
  3120. @protected
  3121. @type {String}
  3122. */
  3123. shimid: null,
  3124. /**
  3125. Array of selected moxie.file.File objects
  3126. @property files
  3127. @type {Array}
  3128. @default null
  3129. */
  3130. files: null,
  3131. /**
  3132. Initializes the file-picker, connects it to runtime and dispatches event ready when done.
  3133. @method init
  3134. */
  3135. init: function() {
  3136. var self = this;
  3137. self.bind('RuntimeInit', function(e, runtime) {
  3138. self.ruid = runtime.uid;
  3139. self.shimid = runtime.shimid;
  3140. self.bind("Ready", function() {
  3141. self.trigger("Refresh");
  3142. }, 999);
  3143. // re-position and resize shim container
  3144. self.bind('Refresh', function() {
  3145. var pos, size, browseButton, shimContainer, zIndex;
  3146. browseButton = Dom.get(options.browse_button);
  3147. shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
  3148. if (browseButton) {
  3149. pos = Dom.getPos(browseButton, Dom.get(options.container));
  3150. size = Dom.getSize(browseButton);
  3151. zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 0;
  3152. if (shimContainer) {
  3153. Basic.extend(shimContainer.style, {
  3154. top: pos.y + 'px',
  3155. left: pos.x + 'px',
  3156. width: size.w + 'px',
  3157. height: size.h + 'px',
  3158. zIndex: zIndex + 1
  3159. });
  3160. }
  3161. }
  3162. shimContainer = browseButton = null;
  3163. });
  3164. runtime.exec.call(self, 'FileInput', 'init', options);
  3165. });
  3166. // runtime needs: options.required_features, options.runtime_order and options.container
  3167. self.connectRuntime(Basic.extend({}, options, {
  3168. required_caps: {
  3169. select_file: true
  3170. }
  3171. }));
  3172. },
  3173. /**
  3174. * Get current option value by its name
  3175. *
  3176. * @method getOption
  3177. * @param name
  3178. * @return {Mixed}
  3179. */
  3180. getOption: function(name) {
  3181. return options[name];
  3182. },
  3183. /**
  3184. * Sets a new value for the option specified by name
  3185. *
  3186. * @method setOption
  3187. * @param name
  3188. * @param value
  3189. */
  3190. setOption: function(name, value) {
  3191. if (!options.hasOwnProperty(name)) {
  3192. return;
  3193. }
  3194. var oldValue = options[name];
  3195. switch (name) {
  3196. case 'accept':
  3197. if (typeof(value) === 'string') {
  3198. value = Mime.mimes2extList(value);
  3199. }
  3200. break;
  3201. case 'container':
  3202. case 'required_caps':
  3203. throw new x.FileException(x.FileException.NO_MODIFICATION_ALLOWED_ERR);
  3204. }
  3205. options[name] = value;
  3206. this.exec('FileInput', 'setOption', name, value);
  3207. this.trigger('OptionChanged', name, value, oldValue);
  3208. },
  3209. /**
  3210. Disables file-picker element, so that it doesn't react to mouse clicks.
  3211. @method disable
  3212. @param {Boolean} [state=true] Disable component if - true, enable if - false
  3213. */
  3214. disable: function(state) {
  3215. var runtime = this.getRuntime();
  3216. if (runtime) {
  3217. this.exec('FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
  3218. }
  3219. },
  3220. /**
  3221. Reposition and resize dialog trigger to match the position and size of browse_button element.
  3222. @method refresh
  3223. */
  3224. refresh: function() {
  3225. this.trigger("Refresh");
  3226. },
  3227. /**
  3228. Destroy component.
  3229. @method destroy
  3230. */
  3231. destroy: function() {
  3232. var runtime = this.getRuntime();
  3233. if (runtime) {
  3234. runtime.exec.call(this, 'FileInput', 'destroy');
  3235. this.disconnectRuntime();
  3236. }
  3237. if (Basic.typeOf(this.files) === 'array') {
  3238. // no sense in leaving associated files behind
  3239. Basic.each(this.files, function(file) {
  3240. file.destroy();
  3241. });
  3242. }
  3243. this.files = null;
  3244. this.unbindAll();
  3245. }
  3246. });
  3247. this.handleEventProps(dispatches);
  3248. }
  3249. FileInput.prototype = EventTarget.instance;
  3250. return FileInput;
  3251. });
  3252. // Included from: src/javascript/file/File.js
  3253. /**
  3254. * File.js
  3255. *
  3256. * Copyright 2013, Moxiecode Systems AB
  3257. * Released under GPL License.
  3258. *
  3259. * License: http://www.plupload.com/license
  3260. * Contributing: http://www.plupload.com/contributing
  3261. */
  3262. define('moxie/file/File', [
  3263. 'moxie/core/utils/Basic',
  3264. 'moxie/core/utils/Mime',
  3265. 'moxie/file/Blob'
  3266. ], function(Basic, Mime, Blob) {
  3267. /**
  3268. @class moxie/file/File
  3269. @extends Blob
  3270. @constructor
  3271. @param {String} ruid Unique id of the runtime, to which this blob belongs to
  3272. @param {Object} file Object "Native" file object, as it is represented in the runtime
  3273. */
  3274. function File(ruid, file) {
  3275. if (!file) { // avoid extra errors in case we overlooked something
  3276. file = {};
  3277. }
  3278. Blob.apply(this, arguments);
  3279. if (!this.type) {
  3280. this.type = Mime.getFileMime(file.name);
  3281. }
  3282. // sanitize file name or generate new one
  3283. var name;
  3284. if (file.name) {
  3285. name = file.name.replace(/\\/g, '/');
  3286. name = name.substr(name.lastIndexOf('/') + 1);
  3287. } else if (this.type) {
  3288. var prefix = this.type.split('/')[0];
  3289. name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
  3290. if (Mime.extensions[this.type]) {
  3291. name += '.' + Mime.extensions[this.type][0]; // append proper extension if possible
  3292. }
  3293. }
  3294. Basic.extend(this, {
  3295. /**
  3296. File name
  3297. @property name
  3298. @type {String}
  3299. @default UID
  3300. */
  3301. name: name || Basic.guid('file_'),
  3302. /**
  3303. Relative path to the file inside a directory
  3304. @property relativePath
  3305. @type {String}
  3306. @default ''
  3307. */
  3308. relativePath: '',
  3309. /**
  3310. Date of last modification
  3311. @property lastModifiedDate
  3312. @type {String}
  3313. @default now
  3314. */
  3315. lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
  3316. });
  3317. }
  3318. File.prototype = Blob.prototype;
  3319. return File;
  3320. });
  3321. // Included from: src/javascript/file/FileDrop.js
  3322. /**
  3323. * FileDrop.js
  3324. *
  3325. * Copyright 2013, Moxiecode Systems AB
  3326. * Released under GPL License.
  3327. *
  3328. * License: http://www.plupload.com/license
  3329. * Contributing: http://www.plupload.com/contributing
  3330. */
  3331. define('moxie/file/FileDrop', [
  3332. 'moxie/core/I18n',
  3333. 'moxie/core/utils/Dom',
  3334. 'moxie/core/Exceptions',
  3335. 'moxie/core/utils/Basic',
  3336. 'moxie/core/utils/Env',
  3337. 'moxie/file/File',
  3338. 'moxie/runtime/RuntimeClient',
  3339. 'moxie/core/EventTarget',
  3340. 'moxie/core/utils/Mime'
  3341. ], function(I18n, Dom, x, Basic, Env, File, RuntimeClient, EventTarget, Mime) {
  3342. /**
  3343. Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used
  3344. in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through
  3345. _XMLHttpRequest_.
  3346. @example
  3347. <div id="drop_zone">
  3348. Drop files here
  3349. </div>
  3350. <br />
  3351. <div id="filelist"></div>
  3352. <script type="text/javascript">
  3353. var fileDrop = new moxie.file.FileDrop('drop_zone'), fileList = moxie.utils.Dom.get('filelist');
  3354. fileDrop.ondrop = function() {
  3355. moxie.utils.Basic.each(this.files, function(file) {
  3356. fileList.innerHTML += '<div>' + file.name + '</div>';
  3357. });
  3358. };
  3359. fileDrop.init();
  3360. </script>
  3361. @class moxie/file/FileDrop
  3362. @constructor
  3363. @extends EventTarget
  3364. @uses RuntimeClient
  3365. @param {Object|String} options If options has typeof string, argument is considered as options.drop_zone
  3366. @param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone
  3367. @param {Array} [options.accept] Array of mime types to accept. By default accepts all
  3368. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support
  3369. */
  3370. var dispatches = [
  3371. /**
  3372. Dispatched when runtime is connected and drop zone is ready to accept files.
  3373. @event ready
  3374. @param {Object} event
  3375. */
  3376. 'ready',
  3377. /**
  3378. Dispatched when dragging cursor enters the drop zone.
  3379. @event dragenter
  3380. @param {Object} event
  3381. */
  3382. 'dragenter',
  3383. /**
  3384. Dispatched when dragging cursor leaves the drop zone.
  3385. @event dragleave
  3386. @param {Object} event
  3387. */
  3388. 'dragleave',
  3389. /**
  3390. Dispatched when file is dropped onto the drop zone.
  3391. @event drop
  3392. @param {Object} event
  3393. */
  3394. 'drop',
  3395. /**
  3396. Dispatched if error occurs.
  3397. @event error
  3398. @param {Object} event
  3399. */
  3400. 'error'
  3401. ];
  3402. function FileDrop(options) {
  3403. if (MXI_DEBUG) {
  3404. Env.log("Instantiating FileDrop...");
  3405. }
  3406. var self = this, defaults;
  3407. // if flat argument passed it should be drop_zone id
  3408. if (typeof(options) === 'string') {
  3409. options = { drop_zone : options };
  3410. }
  3411. // figure out the options
  3412. defaults = {
  3413. accept: [{
  3414. title: I18n.translate('All Files'),
  3415. extensions: '*'
  3416. }],
  3417. required_caps: {
  3418. drag_and_drop: true
  3419. }
  3420. };
  3421. options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults;
  3422. // this will help us to find proper default container
  3423. options.container = Dom.get(options.drop_zone) || document.body;
  3424. // make container relative, if it is not
  3425. if (Dom.getStyle(options.container, 'position') === 'static') {
  3426. options.container.style.position = 'relative';
  3427. }
  3428. // normalize accept option (could be list of mime types or array of title/extensions pairs)
  3429. if (typeof(options.accept) === 'string') {
  3430. options.accept = Mime.mimes2extList(options.accept);
  3431. }
  3432. RuntimeClient.call(self);
  3433. Basic.extend(self, {
  3434. uid: Basic.guid('uid_'),
  3435. ruid: null,
  3436. files: null,
  3437. init: function() {
  3438. self.bind('RuntimeInit', function(e, runtime) {
  3439. self.ruid = runtime.uid;
  3440. runtime.exec.call(self, 'FileDrop', 'init', options);
  3441. self.dispatchEvent('ready');
  3442. });
  3443. // runtime needs: options.required_features, options.runtime_order and options.container
  3444. self.connectRuntime(options); // throws RuntimeError
  3445. },
  3446. destroy: function() {
  3447. var runtime = this.getRuntime();
  3448. if (runtime) {
  3449. runtime.exec.call(this, 'FileDrop', 'destroy');
  3450. this.disconnectRuntime();
  3451. }
  3452. this.files = null;
  3453. this.unbindAll();
  3454. }
  3455. });
  3456. this.handleEventProps(dispatches);
  3457. }
  3458. FileDrop.prototype = EventTarget.instance;
  3459. return FileDrop;
  3460. });
  3461. // Included from: src/javascript/file/FileReader.js
  3462. /**
  3463. * FileReader.js
  3464. *
  3465. * Copyright 2013, Moxiecode Systems AB
  3466. * Released under GPL License.
  3467. *
  3468. * License: http://www.plupload.com/license
  3469. * Contributing: http://www.plupload.com/contributing
  3470. */
  3471. define('moxie/file/FileReader', [
  3472. 'moxie/core/utils/Basic',
  3473. 'moxie/core/utils/Encode',
  3474. 'moxie/core/Exceptions',
  3475. 'moxie/core/EventTarget',
  3476. 'moxie/file/Blob',
  3477. 'moxie/runtime/RuntimeClient'
  3478. ], function(Basic, Encode, x, EventTarget, Blob, RuntimeClient) {
  3479. /**
  3480. Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
  3481. interface. Where possible uses native FileReader, where - not falls back to shims.
  3482. @class moxie/file/FileReader
  3483. @constructor FileReader
  3484. @extends EventTarget
  3485. @uses RuntimeClient
  3486. */
  3487. var dispatches = [
  3488. /**
  3489. Dispatched when the read starts.
  3490. @event loadstart
  3491. @param {Object} event
  3492. */
  3493. 'loadstart',
  3494. /**
  3495. Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).
  3496. @event progress
  3497. @param {Object} event
  3498. */
  3499. 'progress',
  3500. /**
  3501. Dispatched when the read has successfully completed.
  3502. @event load
  3503. @param {Object} event
  3504. */
  3505. 'load',
  3506. /**
  3507. Dispatched when the read has been aborted. For instance, by invoking the abort() method.
  3508. @event abort
  3509. @param {Object} event
  3510. */
  3511. 'abort',
  3512. /**
  3513. Dispatched when the read has failed.
  3514. @event error
  3515. @param {Object} event
  3516. */
  3517. 'error',
  3518. /**
  3519. Dispatched when the request has completed (either in success or failure).
  3520. @event loadend
  3521. @param {Object} event
  3522. */
  3523. 'loadend'
  3524. ];
  3525. function FileReader() {
  3526. RuntimeClient.call(this);
  3527. Basic.extend(this, {
  3528. /**
  3529. UID of the component instance.
  3530. @property uid
  3531. @type {String}
  3532. */
  3533. uid: Basic.guid('uid_'),
  3534. /**
  3535. Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
  3536. and FileReader.DONE.
  3537. @property readyState
  3538. @type {Number}
  3539. @default FileReader.EMPTY
  3540. */
  3541. readyState: FileReader.EMPTY,
  3542. /**
  3543. Result of the successful read operation.
  3544. @property result
  3545. @type {String}
  3546. */
  3547. result: null,
  3548. /**
  3549. Stores the error of failed asynchronous read operation.
  3550. @property error
  3551. @type {DOMError}
  3552. */
  3553. error: null,
  3554. /**
  3555. Initiates reading of File/Blob object contents to binary string.
  3556. @method readAsBinaryString
  3557. @param {Blob|File} blob Object to preload
  3558. */
  3559. readAsBinaryString: function(blob) {
  3560. _read.call(this, 'readAsBinaryString', blob);
  3561. },
  3562. /**
  3563. Initiates reading of File/Blob object contents to dataURL string.
  3564. @method readAsDataURL
  3565. @param {Blob|File} blob Object to preload
  3566. */
  3567. readAsDataURL: function(blob) {
  3568. _read.call(this, 'readAsDataURL', blob);
  3569. },
  3570. /**
  3571. Initiates reading of File/Blob object contents to string.
  3572. @method readAsText
  3573. @param {Blob|File} blob Object to preload
  3574. */
  3575. readAsText: function(blob) {
  3576. _read.call(this, 'readAsText', blob);
  3577. },
  3578. /**
  3579. Aborts preloading process.
  3580. @method abort
  3581. */
  3582. abort: function() {
  3583. this.result = null;
  3584. if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
  3585. return;
  3586. } else if (this.readyState === FileReader.LOADING) {
  3587. this.readyState = FileReader.DONE;
  3588. }
  3589. this.exec('FileReader', 'abort');
  3590. this.trigger('abort');
  3591. this.trigger('loadend');
  3592. },
  3593. /**
  3594. Destroy component and release resources.
  3595. @method destroy
  3596. */
  3597. destroy: function() {
  3598. this.abort();
  3599. this.exec('FileReader', 'destroy');
  3600. this.disconnectRuntime();
  3601. this.unbindAll();
  3602. }
  3603. });
  3604. // uid must already be assigned
  3605. this.handleEventProps(dispatches);
  3606. this.bind('Error', function(e, err) {
  3607. this.readyState = FileReader.DONE;
  3608. this.error = err;
  3609. }, 999);
  3610. this.bind('Load', function(e) {
  3611. this.readyState = FileReader.DONE;
  3612. }, 999);
  3613. function _read(op, blob) {
  3614. var self = this;
  3615. this.trigger('loadstart');
  3616. if (this.readyState === FileReader.LOADING) {
  3617. this.trigger('error', new x.DOMException(x.DOMException.INVALID_STATE_ERR));
  3618. this.trigger('loadend');
  3619. return;
  3620. }
  3621. // if source is not o.Blob/o.File
  3622. if (!(blob instanceof Blob)) {
  3623. this.trigger('error', new x.DOMException(x.DOMException.NOT_FOUND_ERR));
  3624. this.trigger('loadend');
  3625. return;
  3626. }
  3627. this.result = null;
  3628. this.readyState = FileReader.LOADING;
  3629. if (blob.isDetached()) {
  3630. var src = blob.getSource();
  3631. switch (op) {
  3632. case 'readAsText':
  3633. case 'readAsBinaryString':
  3634. this.result = src;
  3635. break;
  3636. case 'readAsDataURL':
  3637. this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
  3638. break;
  3639. }
  3640. this.readyState = FileReader.DONE;
  3641. this.trigger('load');
  3642. this.trigger('loadend');
  3643. } else {
  3644. this.connectRuntime(blob.ruid);
  3645. this.exec('FileReader', 'read', op, blob);
  3646. }
  3647. }
  3648. }
  3649. /**
  3650. Initial FileReader state
  3651. @property EMPTY
  3652. @type {Number}
  3653. @final
  3654. @static
  3655. @default 0
  3656. */
  3657. FileReader.EMPTY = 0;
  3658. /**
  3659. FileReader switches to this state when it is preloading the source
  3660. @property LOADING
  3661. @type {Number}
  3662. @final
  3663. @static
  3664. @default 1
  3665. */
  3666. FileReader.LOADING = 1;
  3667. /**
  3668. Preloading is complete, this is a final state
  3669. @property DONE
  3670. @type {Number}
  3671. @final
  3672. @static
  3673. @default 2
  3674. */
  3675. FileReader.DONE = 2;
  3676. FileReader.prototype = EventTarget.instance;
  3677. return FileReader;
  3678. });
  3679. // Included from: src/javascript/core/utils/Url.js
  3680. /**
  3681. * Url.js
  3682. *
  3683. * Copyright 2013, Moxiecode Systems AB
  3684. * Released under GPL License.
  3685. *
  3686. * License: http://www.plupload.com/license
  3687. * Contributing: http://www.plupload.com/contributing
  3688. */
  3689. /**
  3690. @class moxie/core/utils/Url
  3691. @public
  3692. @static
  3693. */
  3694. define('moxie/core/utils/Url', [
  3695. 'moxie/core/utils/Basic'
  3696. ], function(Basic) {
  3697. /**
  3698. Parse url into separate components and fill in absent parts with parts from current url,
  3699. based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js
  3700. @method parseUrl
  3701. @static
  3702. @param {String} url Url to parse (defaults to empty string if undefined)
  3703. @return {Object} Hash containing extracted uri components
  3704. */
  3705. var parseUrl = function(url, currentUrl) {
  3706. var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
  3707. , i = key.length
  3708. , ports = {
  3709. http: 80,
  3710. https: 443
  3711. }
  3712. , uri = {}
  3713. , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@\/]*):?([^:@\/]*))?@)?(\[[\da-fA-F:]+\]|[^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
  3714. , m = regex.exec(url || '')
  3715. , isRelative
  3716. , isSchemeLess = /^\/\/\w/.test(url)
  3717. ;
  3718. switch (Basic.typeOf(currentUrl)) {
  3719. case 'undefined':
  3720. currentUrl = parseUrl(document.location.href, false);
  3721. break;
  3722. case 'string':
  3723. currentUrl = parseUrl(currentUrl, false);
  3724. break;
  3725. }
  3726. while (i--) {
  3727. if (m[i]) {
  3728. uri[key[i]] = m[i];
  3729. }
  3730. }
  3731. isRelative = !isSchemeLess && !uri.scheme;
  3732. if (isSchemeLess || isRelative) {
  3733. uri.scheme = currentUrl.scheme;
  3734. }
  3735. // when url is relative, we set the origin and the path ourselves
  3736. if (isRelative) {
  3737. uri.host = currentUrl.host;
  3738. uri.port = currentUrl.port;
  3739. var path = '';
  3740. // for urls without trailing slash we need to figure out the path
  3741. if (/^[^\/]/.test(uri.path)) {
  3742. path = currentUrl.path;
  3743. // if path ends with a filename, strip it
  3744. if (/\/[^\/]*\.[^\/]*$/.test(path)) {
  3745. path = path.replace(/\/[^\/]+$/, '/');
  3746. } else {
  3747. // avoid double slash at the end (see #127)
  3748. path = path.replace(/\/?$/, '/');
  3749. }
  3750. }
  3751. uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
  3752. }
  3753. if (!uri.port) {
  3754. uri.port = ports[uri.scheme] || 80;
  3755. }
  3756. uri.port = parseInt(uri.port, 10);
  3757. if (!uri.path) {
  3758. uri.path = "/";
  3759. }
  3760. delete uri.source;
  3761. return uri;
  3762. };
  3763. /**
  3764. Resolve url - among other things will turn relative url to absolute
  3765. @method resolveUrl
  3766. @static
  3767. @param {String|Object} url Either absolute or relative, or a result of parseUrl call
  3768. @return {String} Resolved, absolute url
  3769. */
  3770. var resolveUrl = function(url) {
  3771. var ports = { // we ignore default ports
  3772. http: 80,
  3773. https: 443
  3774. }
  3775. , urlp = typeof(url) === 'object' ? url : parseUrl(url);
  3776. ;
  3777. return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
  3778. };
  3779. /**
  3780. Check if specified url has the same origin as the current document
  3781. @method hasSameOrigin
  3782. @static
  3783. @param {String|Object} url
  3784. @return {Boolean}
  3785. */
  3786. var hasSameOrigin = function(url) {
  3787. function origin(url) {
  3788. return [url.scheme, url.host, url.port].join('/');
  3789. }
  3790. if (typeof url === 'string') {
  3791. url = parseUrl(url);
  3792. }
  3793. return origin(parseUrl()) === origin(url);
  3794. };
  3795. return {
  3796. parseUrl: parseUrl,
  3797. resolveUrl: resolveUrl,
  3798. hasSameOrigin: hasSameOrigin
  3799. };
  3800. });
  3801. // Included from: src/javascript/runtime/RuntimeTarget.js
  3802. /**
  3803. * RuntimeTarget.js
  3804. *
  3805. * Copyright 2013, Moxiecode Systems AB
  3806. * Released under GPL License.
  3807. *
  3808. * License: http://www.plupload.com/license
  3809. * Contributing: http://www.plupload.com/contributing
  3810. */
  3811. define('moxie/runtime/RuntimeTarget', [
  3812. 'moxie/core/utils/Basic',
  3813. 'moxie/runtime/RuntimeClient',
  3814. "moxie/core/EventTarget"
  3815. ], function(Basic, RuntimeClient, EventTarget) {
  3816. /**
  3817. Instance of this class can be used as a target for the events dispatched by shims,
  3818. when allowing them onto components is for either reason inappropriate
  3819. @class moxie/runtime/RuntimeTarget
  3820. @constructor
  3821. @protected
  3822. @extends EventTarget
  3823. */
  3824. function RuntimeTarget() {
  3825. this.uid = Basic.guid('uid_');
  3826. RuntimeClient.call(this);
  3827. this.destroy = function() {
  3828. this.disconnectRuntime();
  3829. this.unbindAll();
  3830. };
  3831. }
  3832. RuntimeTarget.prototype = EventTarget.instance;
  3833. return RuntimeTarget;
  3834. });
  3835. // Included from: src/javascript/file/FileReaderSync.js
  3836. /**
  3837. * FileReaderSync.js
  3838. *
  3839. * Copyright 2013, Moxiecode Systems AB
  3840. * Released under GPL License.
  3841. *
  3842. * License: http://www.plupload.com/license
  3843. * Contributing: http://www.plupload.com/contributing
  3844. */
  3845. define('moxie/file/FileReaderSync', [
  3846. 'moxie/core/utils/Basic',
  3847. 'moxie/runtime/RuntimeClient',
  3848. 'moxie/core/utils/Encode'
  3849. ], function(Basic, RuntimeClient, Encode) {
  3850. /**
  3851. Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
  3852. it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
  3853. but probably < 1mb). Not meant to be used directly by user.
  3854. @class moxie/file/FileReaderSync
  3855. @private
  3856. @constructor
  3857. */
  3858. return function() {
  3859. RuntimeClient.call(this);
  3860. Basic.extend(this, {
  3861. uid: Basic.guid('uid_'),
  3862. readAsBinaryString: function(blob) {
  3863. return _read.call(this, 'readAsBinaryString', blob);
  3864. },
  3865. readAsDataURL: function(blob) {
  3866. return _read.call(this, 'readAsDataURL', blob);
  3867. },
  3868. /*readAsArrayBuffer: function(blob) {
  3869. return _read.call(this, 'readAsArrayBuffer', blob);
  3870. },*/
  3871. readAsText: function(blob) {
  3872. return _read.call(this, 'readAsText', blob);
  3873. }
  3874. });
  3875. function _read(op, blob) {
  3876. if (blob.isDetached()) {
  3877. var src = blob.getSource();
  3878. switch (op) {
  3879. case 'readAsBinaryString':
  3880. return src;
  3881. case 'readAsDataURL':
  3882. return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
  3883. case 'readAsText':
  3884. var txt = '';
  3885. for (var i = 0, length = src.length; i < length; i++) {
  3886. txt += String.fromCharCode(src[i]);
  3887. }
  3888. return txt;
  3889. }
  3890. } else {
  3891. var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
  3892. this.disconnectRuntime();
  3893. return result;
  3894. }
  3895. }
  3896. };
  3897. });
  3898. // Included from: src/javascript/xhr/FormData.js
  3899. /**
  3900. * FormData.js
  3901. *
  3902. * Copyright 2013, Moxiecode Systems AB
  3903. * Released under GPL License.
  3904. *
  3905. * License: http://www.plupload.com/license
  3906. * Contributing: http://www.plupload.com/contributing
  3907. */
  3908. define("moxie/xhr/FormData", [
  3909. "moxie/core/Exceptions",
  3910. "moxie/core/utils/Basic",
  3911. "moxie/file/Blob"
  3912. ], function(x, Basic, Blob) {
  3913. /**
  3914. FormData
  3915. @class moxie/xhr/FormData
  3916. @constructor
  3917. */
  3918. function FormData() {
  3919. var _blob, _fields = [];
  3920. Basic.extend(this, {
  3921. /**
  3922. Append another key-value pair to the FormData object
  3923. @method append
  3924. @param {String} name Name for the new field
  3925. @param {String|Blob|Array|Object} value Value for the field
  3926. */
  3927. append: function(name, value) {
  3928. var self = this, valueType = Basic.typeOf(value);
  3929. // according to specs value might be either Blob or String
  3930. if (value instanceof Blob) {
  3931. _blob = {
  3932. name: name,
  3933. value: value // unfortunately we can only send single Blob in one FormData
  3934. };
  3935. } else if ('array' === valueType) {
  3936. name += '[]';
  3937. Basic.each(value, function(value) {
  3938. self.append(name, value);
  3939. });
  3940. } else if ('object' === valueType) {
  3941. Basic.each(value, function(value, key) {
  3942. self.append(name + '[' + key + ']', value);
  3943. });
  3944. } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
  3945. self.append(name, "false");
  3946. } else {
  3947. _fields.push({
  3948. name: name,
  3949. value: value.toString()
  3950. });
  3951. }
  3952. },
  3953. /**
  3954. Checks if FormData contains Blob.
  3955. @method hasBlob
  3956. @return {Boolean}
  3957. */
  3958. hasBlob: function() {
  3959. return !!this.getBlob();
  3960. },
  3961. /**
  3962. Retrieves blob.
  3963. @method getBlob
  3964. @return {Object} Either Blob if found or null
  3965. */
  3966. getBlob: function() {
  3967. return _blob && _blob.value || null;
  3968. },
  3969. /**
  3970. Retrieves blob field name.
  3971. @method getBlobName
  3972. @return {String} Either Blob field name or null
  3973. */
  3974. getBlobName: function() {
  3975. return _blob && _blob.name || null;
  3976. },
  3977. /**
  3978. Loop over the fields in FormData and invoke the callback for each of them.
  3979. @method each
  3980. @param {Function} cb Callback to call for each field
  3981. */
  3982. each: function(cb) {
  3983. Basic.each(_fields, function(field) {
  3984. cb(field.value, field.name);
  3985. });
  3986. if (_blob) {
  3987. cb(_blob.value, _blob.name);
  3988. }
  3989. },
  3990. destroy: function() {
  3991. _blob = null;
  3992. _fields = [];
  3993. }
  3994. });
  3995. }
  3996. return FormData;
  3997. });
  3998. // Included from: src/javascript/xhr/XMLHttpRequest.js
  3999. /**
  4000. * XMLHttpRequest.js
  4001. *
  4002. * Copyright 2013, Moxiecode Systems AB
  4003. * Released under GPL License.
  4004. *
  4005. * License: http://www.plupload.com/license
  4006. * Contributing: http://www.plupload.com/contributing
  4007. */
  4008. define("moxie/xhr/XMLHttpRequest", [
  4009. "moxie/core/utils/Basic",
  4010. "moxie/core/Exceptions",
  4011. "moxie/core/EventTarget",
  4012. "moxie/core/utils/Encode",
  4013. "moxie/core/utils/Url",
  4014. "moxie/runtime/Runtime",
  4015. "moxie/runtime/RuntimeTarget",
  4016. "moxie/file/Blob",
  4017. "moxie/file/FileReaderSync",
  4018. "moxie/xhr/FormData",
  4019. "moxie/core/utils/Env",
  4020. "moxie/core/utils/Mime"
  4021. ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {
  4022. var httpCode = {
  4023. 100: 'Continue',
  4024. 101: 'Switching Protocols',
  4025. 102: 'Processing',
  4026. 200: 'OK',
  4027. 201: 'Created',
  4028. 202: 'Accepted',
  4029. 203: 'Non-Authoritative Information',
  4030. 204: 'No Content',
  4031. 205: 'Reset Content',
  4032. 206: 'Partial Content',
  4033. 207: 'Multi-Status',
  4034. 226: 'IM Used',
  4035. 300: 'Multiple Choices',
  4036. 301: 'Moved Permanently',
  4037. 302: 'Found',
  4038. 303: 'See Other',
  4039. 304: 'Not Modified',
  4040. 305: 'Use Proxy',
  4041. 306: 'Reserved',
  4042. 307: 'Temporary Redirect',
  4043. 400: 'Bad Request',
  4044. 401: 'Unauthorized',
  4045. 402: 'Payment Required',
  4046. 403: 'Forbidden',
  4047. 404: 'Not Found',
  4048. 405: 'Method Not Allowed',
  4049. 406: 'Not Acceptable',
  4050. 407: 'Proxy Authentication Required',
  4051. 408: 'Request Timeout',
  4052. 409: 'Conflict',
  4053. 410: 'Gone',
  4054. 411: 'Length Required',
  4055. 412: 'Precondition Failed',
  4056. 413: 'Request Entity Too Large',
  4057. 414: 'Request-URI Too Long',
  4058. 415: 'Unsupported Media Type',
  4059. 416: 'Requested Range Not Satisfiable',
  4060. 417: 'Expectation Failed',
  4061. 422: 'Unprocessable Entity',
  4062. 423: 'Locked',
  4063. 424: 'Failed Dependency',
  4064. 426: 'Upgrade Required',
  4065. 500: 'Internal Server Error',
  4066. 501: 'Not Implemented',
  4067. 502: 'Bad Gateway',
  4068. 503: 'Service Unavailable',
  4069. 504: 'Gateway Timeout',
  4070. 505: 'HTTP Version Not Supported',
  4071. 506: 'Variant Also Negotiates',
  4072. 507: 'Insufficient Storage',
  4073. 510: 'Not Extended'
  4074. };
  4075. function XMLHttpRequestUpload() {
  4076. this.uid = Basic.guid('uid_');
  4077. }
  4078. XMLHttpRequestUpload.prototype = EventTarget.instance;
  4079. /**
  4080. Implementation of XMLHttpRequest
  4081. @class moxie/xhr/XMLHttpRequest
  4082. @constructor
  4083. @uses RuntimeClient
  4084. @extends EventTarget
  4085. */
  4086. var dispatches = [
  4087. 'loadstart',
  4088. 'progress',
  4089. 'abort',
  4090. 'error',
  4091. 'load',
  4092. 'timeout',
  4093. 'loadend'
  4094. // readystatechange (for historical reasons)
  4095. ];
  4096. var NATIVE = 1, RUNTIME = 2;
  4097. function XMLHttpRequest() {
  4098. var self = this,
  4099. // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
  4100. props = {
  4101. /**
  4102. The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.
  4103. @property timeout
  4104. @type Number
  4105. @default 0
  4106. */
  4107. timeout: 0,
  4108. /**
  4109. Current state, can take following values:
  4110. UNSENT (numeric value 0)
  4111. The object has been constructed.
  4112. OPENED (numeric value 1)
  4113. The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
  4114. HEADERS_RECEIVED (numeric value 2)
  4115. All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
  4116. LOADING (numeric value 3)
  4117. The response entity body is being received.
  4118. DONE (numeric value 4)
  4119. @property readyState
  4120. @type Number
  4121. @default 0 (UNSENT)
  4122. */
  4123. readyState: XMLHttpRequest.UNSENT,
  4124. /**
  4125. True when user credentials are to be included in a cross-origin request. False when they are to be excluded
  4126. in a cross-origin request and when cookies are to be ignored in its response. Initially false.
  4127. @property withCredentials
  4128. @type Boolean
  4129. @default false
  4130. */
  4131. withCredentials: false,
  4132. /**
  4133. Returns the HTTP status code.
  4134. @property status
  4135. @type Number
  4136. @default 0
  4137. */
  4138. status: 0,
  4139. /**
  4140. Returns the HTTP status text.
  4141. @property statusText
  4142. @type String
  4143. */
  4144. statusText: "",
  4145. /**
  4146. Returns the response type. Can be set to change the response type. Values are:
  4147. the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
  4148. @property responseType
  4149. @type String
  4150. */
  4151. responseType: "",
  4152. /**
  4153. Returns the document response entity body.
  4154. Throws an "InvalidStateError" exception if responseType is not the empty string or "document".
  4155. @property responseXML
  4156. @type Document
  4157. */
  4158. responseXML: null,
  4159. /**
  4160. Returns the text response entity body.
  4161. Throws an "InvalidStateError" exception if responseType is not the empty string or "text".
  4162. @property responseText
  4163. @type String
  4164. */
  4165. responseText: null,
  4166. /**
  4167. Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
  4168. Can become: ArrayBuffer, Blob, Document, JSON, Text
  4169. @property response
  4170. @type Mixed
  4171. */
  4172. response: null
  4173. },
  4174. _async = true,
  4175. _url,
  4176. _method,
  4177. _headers = {},
  4178. _user,
  4179. _password,
  4180. _encoding = null,
  4181. _mimeType = null,
  4182. // flags
  4183. _sync_flag = false,
  4184. _send_flag = false,
  4185. _upload_events_flag = false,
  4186. _upload_complete_flag = false,
  4187. _error_flag = false,
  4188. _same_origin_flag = false,
  4189. // times
  4190. _start_time,
  4191. _timeoutset_time,
  4192. _finalMime = null,
  4193. _finalCharset = null,
  4194. _options = {},
  4195. _xhr,
  4196. _responseHeaders = '',
  4197. _responseHeadersBag
  4198. ;
  4199. Basic.extend(this, props, {
  4200. /**
  4201. Unique id of the component
  4202. @property uid
  4203. @type String
  4204. */
  4205. uid: Basic.guid('uid_'),
  4206. /**
  4207. Target for Upload events
  4208. @property upload
  4209. @type XMLHttpRequestUpload
  4210. */
  4211. upload: new XMLHttpRequestUpload(),
  4212. /**
  4213. Sets the request method, request URL, synchronous flag, request username, and request password.
  4214. Throws a "SyntaxError" exception if one of the following is true:
  4215. method is not a valid HTTP method.
  4216. url cannot be resolved.
  4217. url contains the "user:password" format in the userinfo production.
  4218. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.
  4219. Throws an "InvalidAccessError" exception if one of the following is true:
  4220. Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
  4221. There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
  4222. the withCredentials attribute is true, or the responseType attribute is not the empty string.
  4223. @method open
  4224. @param {String} method HTTP method to use on request
  4225. @param {String} url URL to request
  4226. @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
  4227. @param {String} [user] Username to use in HTTP authentication process on server-side
  4228. @param {String} [password] Password to use in HTTP authentication process on server-side
  4229. */
  4230. open: function(method, url, async, user, password) {
  4231. var urlp;
  4232. // first two arguments are required
  4233. if (!method || !url) {
  4234. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4235. }
  4236. // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
  4237. if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
  4238. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4239. }
  4240. // 3
  4241. if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
  4242. _method = method.toUpperCase();
  4243. }
  4244. // 4 - allowing these methods poses a security risk
  4245. if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
  4246. throw new x.DOMException(x.DOMException.SECURITY_ERR);
  4247. }
  4248. // 5
  4249. url = Encode.utf8_encode(url);
  4250. // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
  4251. urlp = Url.parseUrl(url);
  4252. _same_origin_flag = Url.hasSameOrigin(urlp);
  4253. // 7 - manually build up absolute url
  4254. _url = Url.resolveUrl(url);
  4255. // 9-10, 12-13
  4256. if ((user || password) && !_same_origin_flag) {
  4257. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4258. }
  4259. _user = user || urlp.user;
  4260. _password = password || urlp.pass;
  4261. // 11
  4262. _async = async || true;
  4263. if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
  4264. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4265. }
  4266. // 14 - terminate abort()
  4267. // 15 - terminate send()
  4268. // 18
  4269. _sync_flag = !_async;
  4270. _send_flag = false;
  4271. _headers = {};
  4272. _reset.call(this);
  4273. // 19
  4274. _p('readyState', XMLHttpRequest.OPENED);
  4275. // 20
  4276. this.dispatchEvent('readystatechange');
  4277. },
  4278. /**
  4279. Appends an header to the list of author request headers, or if header is already
  4280. in the list of author request headers, combines its value with value.
  4281. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
  4282. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
  4283. is not a valid HTTP header field value.
  4284. @method setRequestHeader
  4285. @param {String} header
  4286. @param {String|Number} value
  4287. */
  4288. setRequestHeader: function(header, value) {
  4289. var uaHeaders = [ // these headers are controlled by the user agent
  4290. "accept-charset",
  4291. "accept-encoding",
  4292. "access-control-request-headers",
  4293. "access-control-request-method",
  4294. "connection",
  4295. "content-length",
  4296. "cookie",
  4297. "cookie2",
  4298. "content-transfer-encoding",
  4299. "date",
  4300. "expect",
  4301. "host",
  4302. "keep-alive",
  4303. "origin",
  4304. "referer",
  4305. "te",
  4306. "trailer",
  4307. "transfer-encoding",
  4308. "upgrade",
  4309. "user-agent",
  4310. "via"
  4311. ];
  4312. // 1-2
  4313. if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
  4314. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4315. }
  4316. // 3
  4317. if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
  4318. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4319. }
  4320. // 4
  4321. /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
  4322. if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
  4323. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4324. }*/
  4325. header = Basic.trim(header).toLowerCase();
  4326. // setting of proxy-* and sec-* headers is prohibited by spec
  4327. if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
  4328. return false;
  4329. }
  4330. // camelize
  4331. // browsers lowercase header names (at least for custom ones)
  4332. // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
  4333. if (!_headers[header]) {
  4334. _headers[header] = value;
  4335. } else {
  4336. // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
  4337. _headers[header] += ', ' + value;
  4338. }
  4339. return true;
  4340. },
  4341. /**
  4342. * Test if the specified header is already set on this request.
  4343. * Returns a header value or boolean false if it's not yet set.
  4344. *
  4345. * @method hasRequestHeader
  4346. * @param {String} header Name of the header to test
  4347. * @return {Boolean|String}
  4348. */
  4349. hasRequestHeader: function(header) {
  4350. return header && _headers[header.toLowerCase()] || false;
  4351. },
  4352. /**
  4353. Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
  4354. @method getAllResponseHeaders
  4355. @return {String} reponse headers or empty string
  4356. */
  4357. getAllResponseHeaders: function() {
  4358. return _responseHeaders || '';
  4359. },
  4360. /**
  4361. Returns the header field value from the response of which the field name matches header,
  4362. unless the field name is Set-Cookie or Set-Cookie2.
  4363. @method getResponseHeader
  4364. @param {String} header
  4365. @return {String} value(s) for the specified header or null
  4366. */
  4367. getResponseHeader: function(header) {
  4368. header = header.toLowerCase();
  4369. if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
  4370. return null;
  4371. }
  4372. if (_responseHeaders && _responseHeaders !== '') {
  4373. // if we didn't parse response headers until now, do it and keep for later
  4374. if (!_responseHeadersBag) {
  4375. _responseHeadersBag = {};
  4376. Basic.each(_responseHeaders.split(/\r\n/), function(line) {
  4377. var pair = line.split(/:\s+/);
  4378. if (pair.length === 2) { // last line might be empty, omit
  4379. pair[0] = Basic.trim(pair[0]); // just in case
  4380. _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
  4381. header: pair[0],
  4382. value: Basic.trim(pair[1])
  4383. };
  4384. }
  4385. });
  4386. }
  4387. if (_responseHeadersBag.hasOwnProperty(header)) {
  4388. return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
  4389. }
  4390. }
  4391. return null;
  4392. },
  4393. /**
  4394. Sets the Content-Type header for the response to mime.
  4395. Throws an "InvalidStateError" exception if the state is LOADING or DONE.
  4396. Throws a "SyntaxError" exception if mime is not a valid media type.
  4397. @method overrideMimeType
  4398. @param String mime Mime type to set
  4399. */
  4400. overrideMimeType: function(mime) {
  4401. var matches, charset;
  4402. // 1
  4403. if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
  4404. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4405. }
  4406. // 2
  4407. mime = Basic.trim(mime.toLowerCase());
  4408. if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
  4409. mime = matches[1];
  4410. if (matches[2]) {
  4411. charset = matches[2];
  4412. }
  4413. }
  4414. if (!Mime.mimes[mime]) {
  4415. throw new x.DOMException(x.DOMException.SYNTAX_ERR);
  4416. }
  4417. // 3-4
  4418. _finalMime = mime;
  4419. _finalCharset = charset;
  4420. },
  4421. /**
  4422. Initiates the request. The optional argument provides the request entity body.
  4423. The argument is ignored if request method is GET or HEAD.
  4424. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
  4425. @method send
  4426. @param {Blob|Document|String|FormData} [data] Request entity body
  4427. @param {Object} [options] Set of requirements and pre-requisities for runtime initialization
  4428. */
  4429. send: function(data, options) {
  4430. if (Basic.typeOf(options) === 'string') {
  4431. _options = { ruid: options };
  4432. } else if (!options) {
  4433. _options = {};
  4434. } else {
  4435. _options = options;
  4436. }
  4437. // 1-2
  4438. if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
  4439. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4440. }
  4441. // 3
  4442. // sending Blob
  4443. if (data instanceof Blob) {
  4444. _options.ruid = data.ruid;
  4445. _mimeType = data.type || 'application/octet-stream';
  4446. }
  4447. // FormData
  4448. else if (data instanceof FormData) {
  4449. if (data.hasBlob()) {
  4450. var blob = data.getBlob();
  4451. _options.ruid = blob.ruid;
  4452. _mimeType = blob.type || 'application/octet-stream';
  4453. }
  4454. }
  4455. // DOMString
  4456. else if (typeof data === 'string') {
  4457. _encoding = 'UTF-8';
  4458. _mimeType = 'text/plain;charset=UTF-8';
  4459. // data should be converted to Unicode and encoded as UTF-8
  4460. data = Encode.utf8_encode(data);
  4461. }
  4462. // if withCredentials not set, but requested, set it automatically
  4463. if (!this.withCredentials) {
  4464. this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
  4465. }
  4466. // 4 - storage mutex
  4467. // 5
  4468. _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
  4469. // 6
  4470. _error_flag = false;
  4471. // 7
  4472. _upload_complete_flag = !data;
  4473. // 8 - Asynchronous steps
  4474. if (!_sync_flag) {
  4475. // 8.1
  4476. _send_flag = true;
  4477. // 8.2
  4478. // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
  4479. // 8.3
  4480. //if (!_upload_complete_flag) {
  4481. // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
  4482. //}
  4483. }
  4484. // 8.5 - Return the send() method call, but continue running the steps in this algorithm.
  4485. _doXHR.call(this, data);
  4486. },
  4487. /**
  4488. Cancels any network activity.
  4489. @method abort
  4490. */
  4491. abort: function() {
  4492. _error_flag = true;
  4493. _sync_flag = false;
  4494. if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
  4495. _p('readyState', XMLHttpRequest.DONE);
  4496. _send_flag = false;
  4497. if (_xhr) {
  4498. _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
  4499. } else {
  4500. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4501. }
  4502. _upload_complete_flag = true;
  4503. } else {
  4504. _p('readyState', XMLHttpRequest.UNSENT);
  4505. }
  4506. },
  4507. destroy: function() {
  4508. if (_xhr) {
  4509. if (Basic.typeOf(_xhr.destroy) === 'function') {
  4510. _xhr.destroy();
  4511. }
  4512. _xhr = null;
  4513. }
  4514. this.unbindAll();
  4515. if (this.upload) {
  4516. this.upload.unbindAll();
  4517. this.upload = null;
  4518. }
  4519. }
  4520. });
  4521. this.handleEventProps(dispatches.concat(['readystatechange'])); // for historical reasons
  4522. this.upload.handleEventProps(dispatches);
  4523. /* this is nice, but maybe too lengthy
  4524. // if supported by JS version, set getters/setters for specific properties
  4525. o.defineProperty(this, 'readyState', {
  4526. configurable: false,
  4527. get: function() {
  4528. return _p('readyState');
  4529. }
  4530. });
  4531. o.defineProperty(this, 'timeout', {
  4532. configurable: false,
  4533. get: function() {
  4534. return _p('timeout');
  4535. },
  4536. set: function(value) {
  4537. if (_sync_flag) {
  4538. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4539. }
  4540. // timeout still should be measured relative to the start time of request
  4541. _timeoutset_time = (new Date).getTime();
  4542. _p('timeout', value);
  4543. }
  4544. });
  4545. // the withCredentials attribute has no effect when fetching same-origin resources
  4546. o.defineProperty(this, 'withCredentials', {
  4547. configurable: false,
  4548. get: function() {
  4549. return _p('withCredentials');
  4550. },
  4551. set: function(value) {
  4552. // 1-2
  4553. if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
  4554. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4555. }
  4556. // 3-4
  4557. if (_anonymous_flag || _sync_flag) {
  4558. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4559. }
  4560. // 5
  4561. _p('withCredentials', value);
  4562. }
  4563. });
  4564. o.defineProperty(this, 'status', {
  4565. configurable: false,
  4566. get: function() {
  4567. return _p('status');
  4568. }
  4569. });
  4570. o.defineProperty(this, 'statusText', {
  4571. configurable: false,
  4572. get: function() {
  4573. return _p('statusText');
  4574. }
  4575. });
  4576. o.defineProperty(this, 'responseType', {
  4577. configurable: false,
  4578. get: function() {
  4579. return _p('responseType');
  4580. },
  4581. set: function(value) {
  4582. // 1
  4583. if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
  4584. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4585. }
  4586. // 2
  4587. if (_sync_flag) {
  4588. throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
  4589. }
  4590. // 3
  4591. _p('responseType', value.toLowerCase());
  4592. }
  4593. });
  4594. o.defineProperty(this, 'responseText', {
  4595. configurable: false,
  4596. get: function() {
  4597. // 1
  4598. if (!~o.inArray(_p('responseType'), ['', 'text'])) {
  4599. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4600. }
  4601. // 2-3
  4602. if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
  4603. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4604. }
  4605. return _p('responseText');
  4606. }
  4607. });
  4608. o.defineProperty(this, 'responseXML', {
  4609. configurable: false,
  4610. get: function() {
  4611. // 1
  4612. if (!~o.inArray(_p('responseType'), ['', 'document'])) {
  4613. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4614. }
  4615. // 2-3
  4616. if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
  4617. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  4618. }
  4619. return _p('responseXML');
  4620. }
  4621. });
  4622. o.defineProperty(this, 'response', {
  4623. configurable: false,
  4624. get: function() {
  4625. if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
  4626. if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
  4627. return '';
  4628. }
  4629. }
  4630. if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
  4631. return null;
  4632. }
  4633. return _p('response');
  4634. }
  4635. });
  4636. */
  4637. function _p(prop, value) {
  4638. if (!props.hasOwnProperty(prop)) {
  4639. return;
  4640. }
  4641. if (arguments.length === 1) { // get
  4642. return Env.can('define_property') ? props[prop] : self[prop];
  4643. } else { // set
  4644. if (Env.can('define_property')) {
  4645. props[prop] = value;
  4646. } else {
  4647. self[prop] = value;
  4648. }
  4649. }
  4650. }
  4651. /*
  4652. function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
  4653. // TODO: http://tools.ietf.org/html/rfc3490#section-4.1
  4654. return str.toLowerCase();
  4655. }
  4656. */
  4657. function _doXHR(data) {
  4658. var self = this;
  4659. _start_time = new Date().getTime();
  4660. _xhr = new RuntimeTarget();
  4661. function loadEnd() {
  4662. if (_xhr) { // it could have been destroyed by now
  4663. _xhr.destroy();
  4664. _xhr = null;
  4665. }
  4666. self.dispatchEvent('loadend');
  4667. self = null;
  4668. }
  4669. function exec(runtime) {
  4670. _xhr.bind('LoadStart', function(e) {
  4671. _p('readyState', XMLHttpRequest.LOADING);
  4672. self.dispatchEvent('readystatechange');
  4673. self.dispatchEvent(e);
  4674. if (_upload_events_flag) {
  4675. self.upload.dispatchEvent(e);
  4676. }
  4677. });
  4678. _xhr.bind('Progress', function(e) {
  4679. if (_p('readyState') !== XMLHttpRequest.LOADING) {
  4680. _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
  4681. self.dispatchEvent('readystatechange');
  4682. }
  4683. self.dispatchEvent(e);
  4684. });
  4685. _xhr.bind('UploadProgress', function(e) {
  4686. if (_upload_events_flag) {
  4687. self.upload.dispatchEvent({
  4688. type: 'progress',
  4689. lengthComputable: false,
  4690. total: e.total,
  4691. loaded: e.loaded
  4692. });
  4693. }
  4694. });
  4695. _xhr.bind('Load', function(e) {
  4696. _p('readyState', XMLHttpRequest.DONE);
  4697. _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
  4698. _p('statusText', httpCode[_p('status')] || "");
  4699. _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));
  4700. if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
  4701. _p('responseText', _p('response'));
  4702. } else if (_p('responseType') === 'document') {
  4703. _p('responseXML', _p('response'));
  4704. }
  4705. _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');
  4706. self.dispatchEvent('readystatechange');
  4707. if (_p('status') > 0) { // status 0 usually means that server is unreachable
  4708. if (_upload_events_flag) {
  4709. self.upload.dispatchEvent(e);
  4710. }
  4711. self.dispatchEvent(e);
  4712. } else {
  4713. _error_flag = true;
  4714. self.dispatchEvent('error');
  4715. }
  4716. loadEnd();
  4717. });
  4718. _xhr.bind('Abort', function(e) {
  4719. self.dispatchEvent(e);
  4720. loadEnd();
  4721. });
  4722. _xhr.bind('Error', function(e) {
  4723. _error_flag = true;
  4724. _p('readyState', XMLHttpRequest.DONE);
  4725. self.dispatchEvent('readystatechange');
  4726. _upload_complete_flag = true;
  4727. self.dispatchEvent(e);
  4728. loadEnd();
  4729. });
  4730. runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
  4731. url: _url,
  4732. method: _method,
  4733. async: _async,
  4734. user: _user,
  4735. password: _password,
  4736. headers: _headers,
  4737. mimeType: _mimeType,
  4738. encoding: _encoding,
  4739. responseType: self.responseType,
  4740. withCredentials: self.withCredentials,
  4741. options: _options
  4742. }, data);
  4743. }
  4744. // clarify our requirements
  4745. if (typeof(_options.required_caps) === 'string') {
  4746. _options.required_caps = Runtime.parseCaps(_options.required_caps);
  4747. }
  4748. _options.required_caps = Basic.extend({}, _options.required_caps, {
  4749. return_response_type: self.responseType
  4750. });
  4751. if (data instanceof FormData) {
  4752. _options.required_caps.send_multipart = true;
  4753. }
  4754. if (!Basic.isEmptyObj(_headers)) {
  4755. _options.required_caps.send_custom_headers = true;
  4756. }
  4757. if (!_same_origin_flag) {
  4758. _options.required_caps.do_cors = true;
  4759. }
  4760. if (_options.ruid) { // we do not need to wait if we can connect directly
  4761. exec(_xhr.connectRuntime(_options));
  4762. } else {
  4763. _xhr.bind('RuntimeInit', function(e, runtime) {
  4764. exec(runtime);
  4765. });
  4766. _xhr.bind('RuntimeError', function(e, err) {
  4767. self.dispatchEvent('RuntimeError', err);
  4768. });
  4769. _xhr.connectRuntime(_options);
  4770. }
  4771. }
  4772. function _reset() {
  4773. _p('responseText', "");
  4774. _p('responseXML', null);
  4775. _p('response', null);
  4776. _p('status', 0);
  4777. _p('statusText', "");
  4778. _start_time = _timeoutset_time = null;
  4779. }
  4780. }
  4781. XMLHttpRequest.UNSENT = 0;
  4782. XMLHttpRequest.OPENED = 1;
  4783. XMLHttpRequest.HEADERS_RECEIVED = 2;
  4784. XMLHttpRequest.LOADING = 3;
  4785. XMLHttpRequest.DONE = 4;
  4786. XMLHttpRequest.prototype = EventTarget.instance;
  4787. return XMLHttpRequest;
  4788. });
  4789. // Included from: src/javascript/runtime/Transporter.js
  4790. /**
  4791. * Transporter.js
  4792. *
  4793. * Copyright 2013, Moxiecode Systems AB
  4794. * Released under GPL License.
  4795. *
  4796. * License: http://www.plupload.com/license
  4797. * Contributing: http://www.plupload.com/contributing
  4798. */
  4799. define("moxie/runtime/Transporter", [
  4800. "moxie/core/utils/Basic",
  4801. "moxie/core/utils/Encode",
  4802. "moxie/runtime/RuntimeClient",
  4803. "moxie/core/EventTarget"
  4804. ], function(Basic, Encode, RuntimeClient, EventTarget) {
  4805. /**
  4806. @class moxie/runtime/Transporter
  4807. @private
  4808. @constructor
  4809. */
  4810. function Transporter() {
  4811. var mod, _runtime, _data, _size, _pos, _chunk_size;
  4812. RuntimeClient.call(this);
  4813. Basic.extend(this, {
  4814. uid: Basic.guid('uid_'),
  4815. state: Transporter.IDLE,
  4816. result: null,
  4817. transport: function(data, type, options) {
  4818. var self = this;
  4819. options = Basic.extend({
  4820. chunk_size: 204798
  4821. }, options);
  4822. // should divide by three, base64 requires this
  4823. if ((mod = options.chunk_size % 3)) {
  4824. options.chunk_size += 3 - mod;
  4825. }
  4826. _chunk_size = options.chunk_size;
  4827. _reset.call(this);
  4828. _data = data;
  4829. _size = data.length;
  4830. if (Basic.typeOf(options) === 'string' || options.ruid) {
  4831. _run.call(self, type, this.connectRuntime(options));
  4832. } else {
  4833. // we require this to run only once
  4834. var cb = function(e, runtime) {
  4835. self.unbind("RuntimeInit", cb);
  4836. _run.call(self, type, runtime);
  4837. };
  4838. this.bind("RuntimeInit", cb);
  4839. this.connectRuntime(options);
  4840. }
  4841. },
  4842. abort: function() {
  4843. var self = this;
  4844. self.state = Transporter.IDLE;
  4845. if (_runtime) {
  4846. _runtime.exec.call(self, 'Transporter', 'clear');
  4847. self.trigger("TransportingAborted");
  4848. }
  4849. _reset.call(self);
  4850. },
  4851. destroy: function() {
  4852. this.unbindAll();
  4853. _runtime = null;
  4854. this.disconnectRuntime();
  4855. _reset.call(this);
  4856. }
  4857. });
  4858. function _reset() {
  4859. _size = _pos = 0;
  4860. _data = this.result = null;
  4861. }
  4862. function _run(type, runtime) {
  4863. var self = this;
  4864. _runtime = runtime;
  4865. //self.unbind("RuntimeInit");
  4866. self.bind("TransportingProgress", function(e) {
  4867. _pos = e.loaded;
  4868. if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
  4869. _transport.call(self);
  4870. }
  4871. }, 999);
  4872. self.bind("TransportingComplete", function() {
  4873. _pos = _size;
  4874. self.state = Transporter.DONE;
  4875. _data = null; // clean a bit
  4876. self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
  4877. }, 999);
  4878. self.state = Transporter.BUSY;
  4879. self.trigger("TransportingStarted");
  4880. _transport.call(self);
  4881. }
  4882. function _transport() {
  4883. var self = this,
  4884. chunk,
  4885. bytesLeft = _size - _pos;
  4886. if (_chunk_size > bytesLeft) {
  4887. _chunk_size = bytesLeft;
  4888. }
  4889. chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
  4890. _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
  4891. }
  4892. }
  4893. Transporter.IDLE = 0;
  4894. Transporter.BUSY = 1;
  4895. Transporter.DONE = 2;
  4896. Transporter.prototype = EventTarget.instance;
  4897. return Transporter;
  4898. });
  4899. // Included from: src/javascript/image/Image.js
  4900. /**
  4901. * Image.js
  4902. *
  4903. * Copyright 2013, Moxiecode Systems AB
  4904. * Released under GPL License.
  4905. *
  4906. * License: http://www.plupload.com/license
  4907. * Contributing: http://www.plupload.com/contributing
  4908. */
  4909. define("moxie/image/Image", [
  4910. "moxie/core/utils/Basic",
  4911. "moxie/core/utils/Dom",
  4912. "moxie/core/Exceptions",
  4913. "moxie/file/FileReaderSync",
  4914. "moxie/xhr/XMLHttpRequest",
  4915. "moxie/runtime/Runtime",
  4916. "moxie/runtime/RuntimeClient",
  4917. "moxie/runtime/Transporter",
  4918. "moxie/core/utils/Env",
  4919. "moxie/core/EventTarget",
  4920. "moxie/file/Blob",
  4921. "moxie/file/File",
  4922. "moxie/core/utils/Encode"
  4923. ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) {
  4924. /**
  4925. Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data.
  4926. @class moxie/image/Image
  4927. @constructor
  4928. @extends EventTarget
  4929. */
  4930. var dispatches = [
  4931. 'progress',
  4932. /**
  4933. Dispatched when loading is complete.
  4934. @event load
  4935. @param {Object} event
  4936. */
  4937. 'load',
  4938. 'error',
  4939. /**
  4940. Dispatched when resize operation is complete.
  4941. @event resize
  4942. @param {Object} event
  4943. */
  4944. 'resize',
  4945. /**
  4946. Dispatched when visual representation of the image is successfully embedded
  4947. into the corresponsing container.
  4948. @event embedded
  4949. @param {Object} event
  4950. */
  4951. 'embedded'
  4952. ];
  4953. function Image() {
  4954. RuntimeClient.call(this);
  4955. Basic.extend(this, {
  4956. /**
  4957. Unique id of the component
  4958. @property uid
  4959. @type {String}
  4960. */
  4961. uid: Basic.guid('uid_'),
  4962. /**
  4963. Unique id of the connected runtime, if any.
  4964. @property ruid
  4965. @type {String}
  4966. */
  4967. ruid: null,
  4968. /**
  4969. Name of the file, that was used to create an image, if available. If not equals to empty string.
  4970. @property name
  4971. @type {String}
  4972. @default ""
  4973. */
  4974. name: "",
  4975. /**
  4976. Size of the image in bytes. Actual value is set only after image is preloaded.
  4977. @property size
  4978. @type {Number}
  4979. @default 0
  4980. */
  4981. size: 0,
  4982. /**
  4983. Width of the image. Actual value is set only after image is preloaded.
  4984. @property width
  4985. @type {Number}
  4986. @default 0
  4987. */
  4988. width: 0,
  4989. /**
  4990. Height of the image. Actual value is set only after image is preloaded.
  4991. @property height
  4992. @type {Number}
  4993. @default 0
  4994. */
  4995. height: 0,
  4996. /**
  4997. Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded.
  4998. @property type
  4999. @type {String}
  5000. @default ""
  5001. */
  5002. type: "",
  5003. /**
  5004. Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded.
  5005. @property meta
  5006. @type {Object}
  5007. @default {}
  5008. */
  5009. meta: {},
  5010. /**
  5011. Alias for load method, that takes another moxie.image.Image object as a source (see load).
  5012. @method clone
  5013. @param {Image} src Source for the image
  5014. @param {Boolean} [exact=false] Whether to activate in-depth clone mode
  5015. */
  5016. clone: function() {
  5017. this.load.apply(this, arguments);
  5018. },
  5019. /**
  5020. Loads image from various sources. Currently the source for new image can be: moxie.image.Image,
  5021. moxie.file.Blob/moxie.file.File, native Blob/File, dataUrl or URL. Depending on the type of the
  5022. source, arguments - differ. When source is URL, Image will be downloaded from remote destination
  5023. and loaded in memory.
  5024. @example
  5025. var img = new moxie.image.Image();
  5026. img.onload = function() {
  5027. var blob = img.getAsBlob();
  5028. var formData = new moxie.xhr.FormData();
  5029. formData.append('file', blob);
  5030. var xhr = new moxie.xhr.XMLHttpRequest();
  5031. xhr.onload = function() {
  5032. // upload complete
  5033. };
  5034. xhr.open('post', 'upload.php');
  5035. xhr.send(formData);
  5036. };
  5037. img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg)
  5038. @method load
  5039. @param {Image|Blob|File|String} src Source for the image
  5040. @param {Boolean|Object} [mixed]
  5041. */
  5042. load: function() {
  5043. _load.apply(this, arguments);
  5044. },
  5045. /**
  5046. Resizes the image to fit the specified width/height. If crop is specified, image will also be
  5047. cropped to the exact dimensions.
  5048. @method resize
  5049. @since 3.0
  5050. @param {Object} options
  5051. @param {Number} options.width Resulting width
  5052. @param {Number} [options.height=width] Resulting height (optional, if not supplied will default to width)
  5053. @param {String} [options.type='image/jpeg'] MIME type of the resulting image
  5054. @param {Number} [options.quality=90] In the case of JPEG, controls the quality of resulting image
  5055. @param {Boolean} [options.crop='cc'] If not falsy, image will be cropped, by default from center
  5056. @param {Boolean} [options.fit=true] Whether to upscale the image to fit the exact dimensions
  5057. @param {Boolean} [options.preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
  5058. @param {String} [options.resample='default'] Resampling algorithm to use during resize
  5059. @param {Boolean} [options.multipass=true] Whether to scale the image in steps (results in better quality)
  5060. */
  5061. resize: function(options) {
  5062. var self = this;
  5063. var orientation;
  5064. var scale;
  5065. var srcRect = {
  5066. x: 0,
  5067. y: 0,
  5068. width: self.width,
  5069. height: self.height
  5070. };
  5071. var opts = Basic.extendIf({
  5072. width: self.width,
  5073. height: self.height,
  5074. type: self.type || 'image/jpeg',
  5075. quality: 90,
  5076. crop: false,
  5077. fit: true,
  5078. preserveHeaders: true,
  5079. resample: 'default',
  5080. multipass: true
  5081. }, options);
  5082. try {
  5083. if (!self.size) { // only preloaded image objects can be used as source
  5084. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5085. }
  5086. // no way to reliably intercept the crash due to high resolution, so we simply avoid it
  5087. if (self.width > Image.MAX_RESIZE_WIDTH || self.height > Image.MAX_RESIZE_HEIGHT) {
  5088. throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
  5089. }
  5090. // take into account orientation tag
  5091. orientation = (self.meta && self.meta.tiff && self.meta.tiff.Orientation) || 1;
  5092. if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
  5093. var tmp = opts.width;
  5094. opts.width = opts.height;
  5095. opts.height = tmp;
  5096. }
  5097. if (opts.crop) {
  5098. scale = Math.max(opts.width/self.width, opts.height/self.height);
  5099. if (options.fit) {
  5100. // first scale it up or down to fit the original image
  5101. srcRect.width = Math.min(Math.ceil(opts.width/scale), self.width);
  5102. srcRect.height = Math.min(Math.ceil(opts.height/scale), self.height);
  5103. // recalculate the scale for adapted dimensions
  5104. scale = opts.width/srcRect.width;
  5105. } else {
  5106. srcRect.width = Math.min(opts.width, self.width);
  5107. srcRect.height = Math.min(opts.height, self.height);
  5108. // now we do not need to scale it any further
  5109. scale = 1;
  5110. }
  5111. if (typeof(opts.crop) === 'boolean') {
  5112. opts.crop = 'cc';
  5113. }
  5114. switch (opts.crop.toLowerCase().replace(/_/, '-')) {
  5115. case 'rb':
  5116. case 'right-bottom':
  5117. srcRect.x = self.width - srcRect.width;
  5118. srcRect.y = self.height - srcRect.height;
  5119. break;
  5120. case 'cb':
  5121. case 'center-bottom':
  5122. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  5123. srcRect.y = self.height - srcRect.height;
  5124. break;
  5125. case 'lb':
  5126. case 'left-bottom':
  5127. srcRect.x = 0;
  5128. srcRect.y = self.height - srcRect.height;
  5129. break;
  5130. case 'lt':
  5131. case 'left-top':
  5132. srcRect.x = 0;
  5133. srcRect.y = 0;
  5134. break;
  5135. case 'ct':
  5136. case 'center-top':
  5137. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  5138. srcRect.y = 0;
  5139. break;
  5140. case 'rt':
  5141. case 'right-top':
  5142. srcRect.x = self.width - srcRect.width;
  5143. srcRect.y = 0;
  5144. break;
  5145. case 'rc':
  5146. case 'right-center':
  5147. case 'right-middle':
  5148. srcRect.x = self.width - srcRect.width;
  5149. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5150. break;
  5151. case 'lc':
  5152. case 'left-center':
  5153. case 'left-middle':
  5154. srcRect.x = 0;
  5155. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5156. break;
  5157. case 'cc':
  5158. case 'center-center':
  5159. case 'center-middle':
  5160. default:
  5161. srcRect.x = Math.floor((self.width - srcRect.width) / 2);
  5162. srcRect.y = Math.floor((self.height - srcRect.height) / 2);
  5163. }
  5164. // original image might be smaller than requested crop, so - avoid negative values
  5165. srcRect.x = Math.max(srcRect.x, 0);
  5166. srcRect.y = Math.max(srcRect.y, 0);
  5167. } else {
  5168. scale = Math.min(opts.width/self.width, opts.height/self.height);
  5169. // do not upscale if we were asked to not fit it
  5170. if (scale > 1 && !opts.fit) {
  5171. scale = 1;
  5172. }
  5173. }
  5174. this.exec('Image', 'resize', srcRect, scale, opts);
  5175. } catch(ex) {
  5176. // for now simply trigger error event
  5177. self.trigger('error', ex.code);
  5178. }
  5179. },
  5180. /**
  5181. Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions.
  5182. @method downsize
  5183. @deprecated use resize()
  5184. */
  5185. downsize: function(options) {
  5186. var defaults = {
  5187. width: this.width,
  5188. height: this.height,
  5189. type: this.type || 'image/jpeg',
  5190. quality: 90,
  5191. crop: false,
  5192. fit: false,
  5193. preserveHeaders: true,
  5194. resample: 'default'
  5195. }, opts;
  5196. if (typeof(options) === 'object') {
  5197. opts = Basic.extend(defaults, options);
  5198. } else {
  5199. // for backward compatibility
  5200. opts = Basic.extend(defaults, {
  5201. width: arguments[0],
  5202. height: arguments[1],
  5203. crop: arguments[2],
  5204. preserveHeaders: arguments[3]
  5205. });
  5206. }
  5207. this.resize(opts);
  5208. },
  5209. /**
  5210. Alias for downsize(width, height, true). (see downsize)
  5211. @method crop
  5212. @param {Number} width Resulting width
  5213. @param {Number} [height=width] Resulting height (optional, if not supplied will default to width)
  5214. @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
  5215. */
  5216. crop: function(width, height, preserveHeaders) {
  5217. this.downsize(width, height, true, preserveHeaders);
  5218. },
  5219. getAsCanvas: function() {
  5220. if (!Env.can('create_canvas')) {
  5221. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  5222. }
  5223. return this.exec('Image', 'getAsCanvas');
  5224. },
  5225. /**
  5226. Retrieves image in it's current state as moxie.file.Blob object. Cannot be run on empty or image in progress (throws
  5227. DOMException.INVALID_STATE_ERR).
  5228. @method getAsBlob
  5229. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5230. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5231. @return {Blob} Image as Blob
  5232. */
  5233. getAsBlob: function(type, quality) {
  5234. if (!this.size) {
  5235. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5236. }
  5237. return this.exec('Image', 'getAsBlob', type || 'image/jpeg', quality || 90);
  5238. },
  5239. /**
  5240. Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws
  5241. DOMException.INVALID_STATE_ERR).
  5242. @method getAsDataURL
  5243. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5244. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5245. @return {String} Image as dataURL string
  5246. */
  5247. getAsDataURL: function(type, quality) {
  5248. if (!this.size) {
  5249. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5250. }
  5251. return this.exec('Image', 'getAsDataURL', type || 'image/jpeg', quality || 90);
  5252. },
  5253. /**
  5254. Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws
  5255. DOMException.INVALID_STATE_ERR).
  5256. @method getAsBinaryString
  5257. @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
  5258. @param {Number} [quality=90] Applicable only together with mime type image/jpeg
  5259. @return {String} Image as binary string
  5260. */
  5261. getAsBinaryString: function(type, quality) {
  5262. var dataUrl = this.getAsDataURL(type, quality);
  5263. return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7));
  5264. },
  5265. /**
  5266. Embeds a visual representation of the image into the specified node. Depending on the runtime,
  5267. it might be a canvas, an img node or a thrid party shim object (Flash or SilverLight - very rare,
  5268. can be used in legacy browsers that do not have canvas or proper dataURI support).
  5269. @method embed
  5270. @param {DOMElement} el DOM element to insert the image object into
  5271. @param {Object} [options]
  5272. @param {Number} [options.width] The width of an embed (defaults to the image width)
  5273. @param {Number} [options.height] The height of an embed (defaults to the image height)
  5274. @param {String} [options.type="image/jpeg"] Mime type
  5275. @param {Number} [options.quality=90] Quality of an embed, if mime type is image/jpeg
  5276. @param {Boolean} [options.crop=false] Whether to crop an embed to the specified dimensions
  5277. @param {Boolean} [options.fit=true] By default thumbs will be up- or downscaled as necessary to fit the dimensions
  5278. */
  5279. embed: function(el, options) {
  5280. var self = this
  5281. , runtime // this has to be outside of all the closures to contain proper runtime
  5282. ;
  5283. var opts = Basic.extend({
  5284. width: this.width,
  5285. height: this.height,
  5286. type: this.type || 'image/jpeg',
  5287. quality: 90,
  5288. fit: true,
  5289. resample: 'nearest'
  5290. }, options);
  5291. function render(type, quality) {
  5292. var img = this;
  5293. // if possible, embed a canvas element directly
  5294. if (Env.can('create_canvas')) {
  5295. var canvas = img.getAsCanvas();
  5296. if (canvas) {
  5297. el.appendChild(canvas);
  5298. canvas = null;
  5299. img.destroy();
  5300. self.trigger('embedded');
  5301. return;
  5302. }
  5303. }
  5304. var dataUrl = img.getAsDataURL(type, quality);
  5305. if (!dataUrl) {
  5306. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  5307. }
  5308. if (Env.can('use_data_uri_of', dataUrl.length)) {
  5309. el.innerHTML = '<img src="' + dataUrl + '" width="' + img.width + '" height="' + img.height + '" alt="" />';
  5310. img.destroy();
  5311. self.trigger('embedded');
  5312. } else {
  5313. var tr = new Transporter();
  5314. tr.bind("TransportingComplete", function() {
  5315. runtime = self.connectRuntime(this.result.ruid);
  5316. self.bind("Embedded", function() {
  5317. // position and size properly
  5318. Basic.extend(runtime.getShimContainer().style, {
  5319. //position: 'relative',
  5320. top: '0px',
  5321. left: '0px',
  5322. width: img.width + 'px',
  5323. height: img.height + 'px'
  5324. });
  5325. // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's
  5326. // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and
  5327. // sometimes 8 and they do not have this problem, we can comment this for now
  5328. /*tr.bind("RuntimeInit", function(e, runtime) {
  5329. tr.destroy();
  5330. runtime.destroy();
  5331. onResize.call(self); // re-feed our image data
  5332. });*/
  5333. runtime = null; // release
  5334. }, 999);
  5335. runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height);
  5336. img.destroy();
  5337. });
  5338. tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, {
  5339. required_caps: {
  5340. display_media: true
  5341. },
  5342. runtime_order: 'flash,silverlight',
  5343. container: el
  5344. });
  5345. }
  5346. }
  5347. try {
  5348. if (!(el = Dom.get(el))) {
  5349. throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR);
  5350. }
  5351. if (!this.size) { // only preloaded image objects can be used as source
  5352. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5353. }
  5354. // high-resolution images cannot be consistently handled across the runtimes
  5355. if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
  5356. //throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
  5357. }
  5358. var imgCopy = new Image();
  5359. imgCopy.bind("Resize", function() {
  5360. render.call(this, opts.type, opts.quality);
  5361. });
  5362. imgCopy.bind("Load", function() {
  5363. this.downsize(opts);
  5364. });
  5365. // if embedded thumb data is available and dimensions are big enough, use it
  5366. if (this.meta.thumb && this.meta.thumb.width >= opts.width && this.meta.thumb.height >= opts.height) {
  5367. imgCopy.load(this.meta.thumb.data);
  5368. } else {
  5369. imgCopy.clone(this, false);
  5370. }
  5371. return imgCopy;
  5372. } catch(ex) {
  5373. // for now simply trigger error event
  5374. this.trigger('error', ex.code);
  5375. }
  5376. },
  5377. /**
  5378. Properly destroys the image and frees resources in use. If any. Recommended way to dispose
  5379. moxie.image.Image object.
  5380. @method destroy
  5381. */
  5382. destroy: function() {
  5383. if (this.ruid) {
  5384. this.getRuntime().exec.call(this, 'Image', 'destroy');
  5385. this.disconnectRuntime();
  5386. }
  5387. if (this.meta && this.meta.thumb) {
  5388. // thumb is blob, make sure we destroy it first
  5389. this.meta.thumb.data.destroy();
  5390. }
  5391. this.unbindAll();
  5392. }
  5393. });
  5394. // this is here, because in order to bind properly, we need uid, which is created above
  5395. this.handleEventProps(dispatches);
  5396. this.bind('Load Resize', function() {
  5397. return _updateInfo.call(this); // if operation fails (e.g. image is neither PNG nor JPEG) cancel all pending events
  5398. }, 999);
  5399. function _updateInfo(info) {
  5400. try {
  5401. if (!info) {
  5402. info = this.exec('Image', 'getInfo');
  5403. }
  5404. this.size = info.size;
  5405. this.width = info.width;
  5406. this.height = info.height;
  5407. this.type = info.type;
  5408. this.meta = info.meta;
  5409. // update file name, only if empty
  5410. if (this.name === '') {
  5411. this.name = info.name;
  5412. }
  5413. return true;
  5414. } catch(ex) {
  5415. this.trigger('error', ex.code);
  5416. return false;
  5417. }
  5418. }
  5419. function _load(src) {
  5420. var srcType = Basic.typeOf(src);
  5421. try {
  5422. // if source is Image
  5423. if (src instanceof Image) {
  5424. if (!src.size) { // only preloaded image objects can be used as source
  5425. throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
  5426. }
  5427. _loadFromImage.apply(this, arguments);
  5428. }
  5429. // if source is o.Blob/o.File
  5430. else if (src instanceof Blob) {
  5431. if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) {
  5432. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  5433. }
  5434. _loadFromBlob.apply(this, arguments);
  5435. }
  5436. // if native blob/file
  5437. else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) {
  5438. _load.call(this, new File(null, src), arguments[1]);
  5439. }
  5440. // if String
  5441. else if (srcType === 'string') {
  5442. // if dataUrl String
  5443. if (src.substr(0, 5) === 'data:') {
  5444. _load.call(this, new Blob(null, { data: src }), arguments[1]);
  5445. }
  5446. // else assume Url, either relative or absolute
  5447. else {
  5448. _loadFromUrl.apply(this, arguments);
  5449. }
  5450. }
  5451. // if source seems to be an img node
  5452. else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') {
  5453. _load.call(this, src.src, arguments[1]);
  5454. }
  5455. else {
  5456. throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR);
  5457. }
  5458. } catch(ex) {
  5459. // for now simply trigger error event
  5460. this.trigger('error', ex.code);
  5461. }
  5462. }
  5463. function _loadFromImage(img, exact) {
  5464. var runtime = this.connectRuntime(img.ruid);
  5465. this.ruid = runtime.uid;
  5466. runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact));
  5467. }
  5468. function _loadFromBlob(blob, options) {
  5469. var self = this;
  5470. self.name = blob.name || '';
  5471. function exec(runtime) {
  5472. self.ruid = runtime.uid;
  5473. runtime.exec.call(self, 'Image', 'loadFromBlob', blob);
  5474. }
  5475. if (blob.isDetached()) {
  5476. this.bind('RuntimeInit', function(e, runtime) {
  5477. exec(runtime);
  5478. });
  5479. // convert to object representation
  5480. if (options && typeof(options.required_caps) === 'string') {
  5481. options.required_caps = Runtime.parseCaps(options.required_caps);
  5482. }
  5483. this.connectRuntime(Basic.extend({
  5484. required_caps: {
  5485. access_image_binary: true,
  5486. resize_image: true
  5487. }
  5488. }, options));
  5489. } else {
  5490. exec(this.connectRuntime(blob.ruid));
  5491. }
  5492. }
  5493. function _loadFromUrl(url, options) {
  5494. var self = this, xhr;
  5495. xhr = new XMLHttpRequest();
  5496. xhr.open('get', url);
  5497. xhr.responseType = 'blob';
  5498. xhr.onprogress = function(e) {
  5499. self.trigger(e);
  5500. };
  5501. xhr.onload = function() {
  5502. _loadFromBlob.call(self, xhr.response, true);
  5503. };
  5504. xhr.onerror = function(e) {
  5505. self.trigger(e);
  5506. };
  5507. xhr.onloadend = function() {
  5508. xhr.destroy();
  5509. };
  5510. xhr.bind('RuntimeError', function(e, err) {
  5511. self.trigger('RuntimeError', err);
  5512. });
  5513. xhr.send(null, options);
  5514. }
  5515. }
  5516. // virtual world will crash on you if image has a resolution higher than this:
  5517. Image.MAX_RESIZE_WIDTH = 8192;
  5518. Image.MAX_RESIZE_HEIGHT = 8192;
  5519. Image.prototype = EventTarget.instance;
  5520. return Image;
  5521. });
  5522. // Included from: src/javascript/runtime/html5/Runtime.js
  5523. /**
  5524. * Runtime.js
  5525. *
  5526. * Copyright 2013, Moxiecode Systems AB
  5527. * Released under GPL License.
  5528. *
  5529. * License: http://www.plupload.com/license
  5530. * Contributing: http://www.plupload.com/contributing
  5531. */
  5532. /*global File:true */
  5533. /**
  5534. Defines constructor for HTML5 runtime.
  5535. @class moxie/runtime/html5/Runtime
  5536. @private
  5537. */
  5538. define("moxie/runtime/html5/Runtime", [
  5539. "moxie/core/utils/Basic",
  5540. "moxie/core/Exceptions",
  5541. "moxie/runtime/Runtime",
  5542. "moxie/core/utils/Env"
  5543. ], function(Basic, x, Runtime, Env) {
  5544. var type = "html5", extensions = {};
  5545. function Html5Runtime(options) {
  5546. var I = this
  5547. , Test = Runtime.capTest
  5548. , True = Runtime.capTrue
  5549. ;
  5550. var caps = Basic.extend({
  5551. access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
  5552. access_image_binary: function() {
  5553. return I.can('access_binary') && !!extensions.Image;
  5554. },
  5555. display_media: Test(
  5556. (Env.can('create_canvas') || Env.can('use_data_uri_over32kb')) &&
  5557. defined('moxie/image/Image')
  5558. ),
  5559. do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
  5560. drag_and_drop: Test(function() {
  5561. // this comes directly from Modernizr: http://www.modernizr.com/
  5562. var div = document.createElement('div');
  5563. // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
  5564. return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) &&
  5565. (Env.browser !== 'IE' || Env.verComp(Env.version, 9, '>'));
  5566. }()),
  5567. filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
  5568. return !(
  5569. (Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) ||
  5570. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) ||
  5571. (Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
  5572. (Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
  5573. );
  5574. }()),
  5575. return_response_headers: True,
  5576. return_response_type: function(responseType) {
  5577. if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
  5578. return true;
  5579. }
  5580. return Env.can('return_response_type', responseType);
  5581. },
  5582. return_status_code: True,
  5583. report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
  5584. resize_image: function() {
  5585. return I.can('access_binary') && Env.can('create_canvas');
  5586. },
  5587. select_file: function() {
  5588. return Env.can('use_fileinput') && window.File;
  5589. },
  5590. select_folder: function() {
  5591. return I.can('select_file') && (
  5592. Env.browser === 'Chrome' && Env.verComp(Env.version, 21, '>=') ||
  5593. Env.browser === 'Firefox' && Env.verComp(Env.version, 42, '>=') // https://developer.mozilla.org/en-US/Firefox/Releases/42
  5594. );
  5595. },
  5596. select_multiple: function() {
  5597. // it is buggy on Safari Windows and iOS
  5598. return I.can('select_file') &&
  5599. !(Env.browser === 'Safari' && Env.os === 'Windows') &&
  5600. !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.0", '>') && Env.verComp(Env.osVersion, "8.0.0", '<'));
  5601. },
  5602. send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
  5603. send_custom_headers: Test(window.XMLHttpRequest),
  5604. send_multipart: function() {
  5605. return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
  5606. },
  5607. slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
  5608. stream_upload: function(){
  5609. return I.can('slice_blob') && I.can('send_multipart');
  5610. },
  5611. summon_file_dialog: function() { // yeah... some dirty sniffing here...
  5612. return I.can('select_file') && !(
  5613. (Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '<')) ||
  5614. (Env.browser === 'Opera' && Env.verComp(Env.version, 12, '<')) ||
  5615. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<'))
  5616. );
  5617. },
  5618. upload_filesize: True,
  5619. use_http_method: True
  5620. },
  5621. arguments[2]
  5622. );
  5623. Runtime.call(this, options, (arguments[1] || type), caps);
  5624. Basic.extend(this, {
  5625. init : function() {
  5626. this.trigger("Init");
  5627. },
  5628. destroy: (function(destroy) { // extend default destroy method
  5629. return function() {
  5630. destroy.call(I);
  5631. destroy = I = null;
  5632. };
  5633. }(this.destroy))
  5634. });
  5635. Basic.extend(this.getShim(), extensions);
  5636. }
  5637. Runtime.addConstructor(type, Html5Runtime);
  5638. return extensions;
  5639. });
  5640. // Included from: src/javascript/runtime/html5/file/Blob.js
  5641. /**
  5642. * Blob.js
  5643. *
  5644. * Copyright 2013, Moxiecode Systems AB
  5645. * Released under GPL License.
  5646. *
  5647. * License: http://www.plupload.com/license
  5648. * Contributing: http://www.plupload.com/contributing
  5649. */
  5650. /**
  5651. @class moxie/runtime/html5/file/Blob
  5652. @private
  5653. */
  5654. define("moxie/runtime/html5/file/Blob", [
  5655. "moxie/runtime/html5/Runtime",
  5656. "moxie/file/Blob"
  5657. ], function(extensions, Blob) {
  5658. function HTML5Blob() {
  5659. function w3cBlobSlice(blob, start, end) {
  5660. var blobSlice;
  5661. if (window.File.prototype.slice) {
  5662. try {
  5663. blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception
  5664. return blob.slice(start, end);
  5665. } catch (e) {
  5666. // depricated slice method
  5667. return blob.slice(start, end - start);
  5668. }
  5669. // slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672
  5670. } else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) {
  5671. return blobSlice.call(blob, start, end);
  5672. } else {
  5673. return null; // or throw some exception
  5674. }
  5675. }
  5676. this.slice = function() {
  5677. return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments));
  5678. };
  5679. this.destroy = function() {
  5680. this.getRuntime().getShim().removeInstance(this.uid);
  5681. };
  5682. }
  5683. return (extensions.Blob = HTML5Blob);
  5684. });
  5685. // Included from: src/javascript/core/utils/Events.js
  5686. /**
  5687. * Events.js
  5688. *
  5689. * Copyright 2013, Moxiecode Systems AB
  5690. * Released under GPL License.
  5691. *
  5692. * License: http://www.plupload.com/license
  5693. * Contributing: http://www.plupload.com/contributing
  5694. */
  5695. /**
  5696. @class moxie/core/utils/Events
  5697. @public
  5698. @static
  5699. */
  5700. define('moxie/core/utils/Events', [
  5701. 'moxie/core/utils/Basic'
  5702. ], function(Basic) {
  5703. var eventhash = {}, uid = 'moxie_' + Basic.guid();
  5704. // IE W3C like event funcs
  5705. function preventDefault() {
  5706. this.returnValue = false;
  5707. }
  5708. function stopPropagation() {
  5709. this.cancelBubble = true;
  5710. }
  5711. /**
  5712. Adds an event handler to the specified object and store reference to the handler
  5713. in objects internal Plupload registry (@see removeEvent).
  5714. @method addEvent
  5715. @static
  5716. @param {Object} obj DOM element like object to add handler to.
  5717. @param {String} name Name to add event listener to.
  5718. @param {Function} callback Function to call when event occurs.
  5719. @param {String} [key] that might be used to add specifity to the event record.
  5720. */
  5721. var addEvent = function(obj, name, callback, key) {
  5722. var func, events;
  5723. name = name.toLowerCase();
  5724. // Add event listener
  5725. if (obj.addEventListener) {
  5726. func = callback;
  5727. obj.addEventListener(name, func, false);
  5728. } else if (obj.attachEvent) {
  5729. func = function() {
  5730. var evt = window.event;
  5731. if (!evt.target) {
  5732. evt.target = evt.srcElement;
  5733. }
  5734. evt.preventDefault = preventDefault;
  5735. evt.stopPropagation = stopPropagation;
  5736. callback(evt);
  5737. };
  5738. obj.attachEvent('on' + name, func);
  5739. }
  5740. // Log event handler to objects internal mOxie registry
  5741. if (!obj[uid]) {
  5742. obj[uid] = Basic.guid();
  5743. }
  5744. if (!eventhash.hasOwnProperty(obj[uid])) {
  5745. eventhash[obj[uid]] = {};
  5746. }
  5747. events = eventhash[obj[uid]];
  5748. if (!events.hasOwnProperty(name)) {
  5749. events[name] = [];
  5750. }
  5751. events[name].push({
  5752. func: func,
  5753. orig: callback, // store original callback for IE
  5754. key: key
  5755. });
  5756. };
  5757. /**
  5758. Remove event handler from the specified object. If third argument (callback)
  5759. is not specified remove all events with the specified name.
  5760. @method removeEvent
  5761. @static
  5762. @param {Object} obj DOM element to remove event listener(s) from.
  5763. @param {String} name Name of event listener to remove.
  5764. @param {Function|String} [callback] might be a callback or unique key to match.
  5765. */
  5766. var removeEvent = function(obj, name, callback) {
  5767. var type, undef;
  5768. name = name.toLowerCase();
  5769. if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
  5770. type = eventhash[obj[uid]][name];
  5771. } else {
  5772. return;
  5773. }
  5774. for (var i = type.length - 1; i >= 0; i--) {
  5775. // undefined or not, key should match
  5776. if (type[i].orig === callback || type[i].key === callback) {
  5777. if (obj.removeEventListener) {
  5778. obj.removeEventListener(name, type[i].func, false);
  5779. } else if (obj.detachEvent) {
  5780. obj.detachEvent('on'+name, type[i].func);
  5781. }
  5782. type[i].orig = null;
  5783. type[i].func = null;
  5784. type.splice(i, 1);
  5785. // If callback was passed we are done here, otherwise proceed
  5786. if (callback !== undef) {
  5787. break;
  5788. }
  5789. }
  5790. }
  5791. // If event array got empty, remove it
  5792. if (!type.length) {
  5793. delete eventhash[obj[uid]][name];
  5794. }
  5795. // If mOxie registry has become empty, remove it
  5796. if (Basic.isEmptyObj(eventhash[obj[uid]])) {
  5797. delete eventhash[obj[uid]];
  5798. // IE doesn't let you remove DOM object property with - delete
  5799. try {
  5800. delete obj[uid];
  5801. } catch(e) {
  5802. obj[uid] = undef;
  5803. }
  5804. }
  5805. };
  5806. /**
  5807. Remove all kind of events from the specified object
  5808. @method removeAllEvents
  5809. @static
  5810. @param {Object} obj DOM element to remove event listeners from.
  5811. @param {String} [key] unique key to match, when removing events.
  5812. */
  5813. var removeAllEvents = function(obj, key) {
  5814. if (!obj || !obj[uid]) {
  5815. return;
  5816. }
  5817. Basic.each(eventhash[obj[uid]], function(events, name) {
  5818. removeEvent(obj, name, key);
  5819. });
  5820. };
  5821. return {
  5822. addEvent: addEvent,
  5823. removeEvent: removeEvent,
  5824. removeAllEvents: removeAllEvents
  5825. };
  5826. });
  5827. // Included from: src/javascript/runtime/html5/file/FileInput.js
  5828. /**
  5829. * FileInput.js
  5830. *
  5831. * Copyright 2013, Moxiecode Systems AB
  5832. * Released under GPL License.
  5833. *
  5834. * License: http://www.plupload.com/license
  5835. * Contributing: http://www.plupload.com/contributing
  5836. */
  5837. /**
  5838. @class moxie/runtime/html5/file/FileInput
  5839. @private
  5840. */
  5841. define("moxie/runtime/html5/file/FileInput", [
  5842. "moxie/runtime/html5/Runtime",
  5843. "moxie/file/File",
  5844. "moxie/core/utils/Basic",
  5845. "moxie/core/utils/Dom",
  5846. "moxie/core/utils/Events",
  5847. "moxie/core/utils/Mime",
  5848. "moxie/core/utils/Env"
  5849. ], function(extensions, File, Basic, Dom, Events, Mime, Env) {
  5850. function FileInput() {
  5851. var _options, _browseBtnZIndex; // save original z-index
  5852. Basic.extend(this, {
  5853. init: function(options) {
  5854. var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top;
  5855. _options = options;
  5856. // figure out accept string
  5857. mimes = Mime.extList2mimes(_options.accept, I.can('filter_by_extension'));
  5858. shimContainer = I.getShimContainer();
  5859. shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' +
  5860. (_options.multiple && I.can('select_multiple') ? 'multiple' : '') +
  5861. (_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+
  5862. (mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />';
  5863. input = Dom.get(I.uid);
  5864. // prepare file input to be placed underneath the browse_button element
  5865. Basic.extend(input.style, {
  5866. position: 'absolute',
  5867. top: 0,
  5868. left: 0,
  5869. width: '100%',
  5870. height: '100%'
  5871. });
  5872. browseButton = Dom.get(_options.browse_button);
  5873. _browseBtnZIndex = Dom.getStyle(browseButton, 'z-index') || 'auto';
  5874. // Route click event to the input[type=file] element for browsers that support such behavior
  5875. if (I.can('summon_file_dialog')) {
  5876. if (Dom.getStyle(browseButton, 'position') === 'static') {
  5877. browseButton.style.position = 'relative';
  5878. }
  5879. Events.addEvent(browseButton, 'click', function(e) {
  5880. var input = Dom.get(I.uid);
  5881. if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
  5882. input.click();
  5883. }
  5884. e.preventDefault();
  5885. }, comp.uid);
  5886. comp.bind('Refresh', function() {
  5887. zIndex = parseInt(_browseBtnZIndex, 10) || 1;
  5888. Dom.get(_options.browse_button).style.zIndex = zIndex;
  5889. this.getRuntime().getShimContainer().style.zIndex = zIndex - 1;
  5890. });
  5891. }
  5892. /* Since we have to place input[type=file] on top of the browse_button for some browsers,
  5893. browse_button loses interactivity, so we restore it here */
  5894. top = I.can('summon_file_dialog') ? browseButton : shimContainer;
  5895. Events.addEvent(top, 'mouseover', function() {
  5896. comp.trigger('mouseenter');
  5897. }, comp.uid);
  5898. Events.addEvent(top, 'mouseout', function() {
  5899. comp.trigger('mouseleave');
  5900. }, comp.uid);
  5901. Events.addEvent(top, 'mousedown', function() {
  5902. comp.trigger('mousedown');
  5903. }, comp.uid);
  5904. Events.addEvent(Dom.get(_options.container), 'mouseup', function() {
  5905. comp.trigger('mouseup');
  5906. }, comp.uid);
  5907. // it shouldn't be possible to tab into the hidden element
  5908. (I.can('summon_file_dialog') ? input : browseButton).setAttribute('tabindex', -1);
  5909. input.onchange = function onChange() { // there should be only one handler for this
  5910. comp.files = [];
  5911. Basic.each(this.files, function(file) {
  5912. var relativePath = '';
  5913. if (_options.directory) {
  5914. // folders are represented by dots, filter them out (Chrome 11+)
  5915. if (file.name == ".") {
  5916. // if it looks like a folder...
  5917. return true;
  5918. }
  5919. }
  5920. if (file.webkitRelativePath) {
  5921. relativePath = '/' + file.webkitRelativePath.replace(/^\//, '');
  5922. }
  5923. file = new File(I.uid, file);
  5924. file.relativePath = relativePath;
  5925. comp.files.push(file);
  5926. });
  5927. // clearing the value enables the user to select the same file again if they want to
  5928. if (Env.browser !== 'IE' && Env.browser !== 'IEMobile') {
  5929. this.value = '';
  5930. } else {
  5931. // in IE input[type="file"] is read-only so the only way to reset it is to re-insert it
  5932. var clone = this.cloneNode(true);
  5933. this.parentNode.replaceChild(clone, this);
  5934. clone.onchange = onChange;
  5935. }
  5936. if (comp.files.length) {
  5937. comp.trigger('change');
  5938. }
  5939. };
  5940. // ready event is perfectly asynchronous
  5941. comp.trigger({
  5942. type: 'ready',
  5943. async: true
  5944. });
  5945. shimContainer = null;
  5946. },
  5947. setOption: function(name, value) {
  5948. var I = this.getRuntime();
  5949. var input = Dom.get(I.uid);
  5950. switch (name) {
  5951. case 'accept':
  5952. if (value) {
  5953. var mimes = value.mimes || Mime.extList2mimes(value, I.can('filter_by_extension'));
  5954. input.setAttribute('accept', mimes.join(','));
  5955. } else {
  5956. input.removeAttribute('accept');
  5957. }
  5958. break;
  5959. case 'directory':
  5960. if (value && I.can('select_folder')) {
  5961. input.setAttribute('directory', '');
  5962. input.setAttribute('webkitdirectory', '');
  5963. } else {
  5964. input.removeAttribute('directory');
  5965. input.removeAttribute('webkitdirectory');
  5966. }
  5967. break;
  5968. case 'multiple':
  5969. if (value && I.can('select_multiple')) {
  5970. input.setAttribute('multiple', '');
  5971. } else {
  5972. input.removeAttribute('multiple');
  5973. }
  5974. }
  5975. },
  5976. disable: function(state) {
  5977. var I = this.getRuntime(), input;
  5978. if ((input = Dom.get(I.uid))) {
  5979. input.disabled = !!state;
  5980. }
  5981. },
  5982. destroy: function() {
  5983. var I = this.getRuntime()
  5984. , shim = I.getShim()
  5985. , shimContainer = I.getShimContainer()
  5986. , container = _options && Dom.get(_options.container)
  5987. , browseButton = _options && Dom.get(_options.browse_button)
  5988. ;
  5989. if (container) {
  5990. Events.removeAllEvents(container, this.uid);
  5991. }
  5992. if (browseButton) {
  5993. Events.removeAllEvents(browseButton, this.uid);
  5994. browseButton.style.zIndex = _browseBtnZIndex; // reset to original value
  5995. }
  5996. if (shimContainer) {
  5997. Events.removeAllEvents(shimContainer, this.uid);
  5998. shimContainer.innerHTML = '';
  5999. }
  6000. shim.removeInstance(this.uid);
  6001. _options = shimContainer = container = browseButton = shim = null;
  6002. }
  6003. });
  6004. }
  6005. return (extensions.FileInput = FileInput);
  6006. });
  6007. // Included from: src/javascript/runtime/html5/file/FileDrop.js
  6008. /**
  6009. * FileDrop.js
  6010. *
  6011. * Copyright 2013, Moxiecode Systems AB
  6012. * Released under GPL License.
  6013. *
  6014. * License: http://www.plupload.com/license
  6015. * Contributing: http://www.plupload.com/contributing
  6016. */
  6017. /**
  6018. @class moxie/runtime/html5/file/FileDrop
  6019. @private
  6020. */
  6021. define("moxie/runtime/html5/file/FileDrop", [
  6022. "moxie/runtime/html5/Runtime",
  6023. 'moxie/file/File',
  6024. "moxie/core/utils/Basic",
  6025. "moxie/core/utils/Dom",
  6026. "moxie/core/utils/Events",
  6027. "moxie/core/utils/Mime"
  6028. ], function(extensions, File, Basic, Dom, Events, Mime) {
  6029. function FileDrop() {
  6030. var _files = [], _allowedExts = [], _options, _ruid;
  6031. Basic.extend(this, {
  6032. init: function(options) {
  6033. var comp = this, dropZone;
  6034. _options = options;
  6035. _ruid = comp.ruid; // every dropped-in file should have a reference to the runtime
  6036. _allowedExts = _extractExts(_options.accept);
  6037. dropZone = _options.container;
  6038. Events.addEvent(dropZone, 'dragover', function(e) {
  6039. if (!_hasFiles(e)) {
  6040. return;
  6041. }
  6042. e.preventDefault();
  6043. e.dataTransfer.dropEffect = 'copy';
  6044. }, comp.uid);
  6045. Events.addEvent(dropZone, 'drop', function(e) {
  6046. if (!_hasFiles(e)) {
  6047. return;
  6048. }
  6049. e.preventDefault();
  6050. _files = [];
  6051. // Chrome 21+ accepts folders via Drag'n'Drop
  6052. if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) {
  6053. _readItems(e.dataTransfer.items, function() {
  6054. comp.files = _files;
  6055. comp.trigger("drop");
  6056. });
  6057. } else {
  6058. Basic.each(e.dataTransfer.files, function(file) {
  6059. _addFile(file);
  6060. });
  6061. comp.files = _files;
  6062. comp.trigger("drop");
  6063. }
  6064. }, comp.uid);
  6065. Events.addEvent(dropZone, 'dragenter', function(e) {
  6066. comp.trigger("dragenter");
  6067. }, comp.uid);
  6068. Events.addEvent(dropZone, 'dragleave', function(e) {
  6069. comp.trigger("dragleave");
  6070. }, comp.uid);
  6071. },
  6072. destroy: function() {
  6073. Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
  6074. _ruid = _files = _allowedExts = _options = null;
  6075. this.getRuntime().getShim().removeInstance(this.uid);
  6076. }
  6077. });
  6078. function _hasFiles(e) {
  6079. if (!e.dataTransfer || !e.dataTransfer.types) { // e.dataTransfer.files is not available in Gecko during dragover
  6080. return false;
  6081. }
  6082. var types = Basic.toArray(e.dataTransfer.types || []);
  6083. return Basic.inArray("Files", types) !== -1 ||
  6084. Basic.inArray("public.file-url", types) !== -1 || // Safari < 5
  6085. Basic.inArray("application/x-moz-file", types) !== -1 // Gecko < 1.9.2 (< Firefox 3.6)
  6086. ;
  6087. }
  6088. function _addFile(file, relativePath) {
  6089. if (_isAcceptable(file)) {
  6090. var fileObj = new File(_ruid, file);
  6091. fileObj.relativePath = relativePath || '';
  6092. _files.push(fileObj);
  6093. }
  6094. }
  6095. function _extractExts(accept) {
  6096. var exts = [];
  6097. for (var i = 0; i < accept.length; i++) {
  6098. [].push.apply(exts, accept[i].extensions.split(/\s*,\s*/));
  6099. }
  6100. return Basic.inArray('*', exts) === -1 ? exts : [];
  6101. }
  6102. function _isAcceptable(file) {
  6103. if (!_allowedExts.length) {
  6104. return true;
  6105. }
  6106. var ext = Mime.getFileExtension(file.name);
  6107. return !ext || Basic.inArray(ext, _allowedExts) !== -1;
  6108. }
  6109. function _readItems(items, cb) {
  6110. var entries = [];
  6111. Basic.each(items, function(item) {
  6112. var entry = item.webkitGetAsEntry();
  6113. // Address #998 (https://code.google.com/p/chromium/issues/detail?id=332579)
  6114. if (entry) {
  6115. // file() fails on OSX when the filename contains a special character (e.g. umlaut): see #61
  6116. if (entry.isFile) {
  6117. _addFile(item.getAsFile(), entry.fullPath);
  6118. } else {
  6119. entries.push(entry);
  6120. }
  6121. }
  6122. });
  6123. if (entries.length) {
  6124. _readEntries(entries, cb);
  6125. } else {
  6126. cb();
  6127. }
  6128. }
  6129. function _readEntries(entries, cb) {
  6130. var queue = [];
  6131. Basic.each(entries, function(entry) {
  6132. queue.push(function(cbcb) {
  6133. _readEntry(entry, cbcb);
  6134. });
  6135. });
  6136. Basic.inSeries(queue, function() {
  6137. cb();
  6138. });
  6139. }
  6140. function _readEntry(entry, cb) {
  6141. if (entry.isFile) {
  6142. entry.file(function(file) {
  6143. _addFile(file, entry.fullPath);
  6144. cb();
  6145. }, function() {
  6146. // fire an error event maybe
  6147. cb();
  6148. });
  6149. } else if (entry.isDirectory) {
  6150. _readDirEntry(entry, cb);
  6151. } else {
  6152. cb(); // not file, not directory? what then?..
  6153. }
  6154. }
  6155. function _readDirEntry(dirEntry, cb) {
  6156. var entries = [], dirReader = dirEntry.createReader();
  6157. // keep quering recursively till no more entries
  6158. function getEntries(cbcb) {
  6159. dirReader.readEntries(function(moreEntries) {
  6160. if (moreEntries.length) {
  6161. [].push.apply(entries, moreEntries);
  6162. getEntries(cbcb);
  6163. } else {
  6164. cbcb();
  6165. }
  6166. }, cbcb);
  6167. }
  6168. // ...and you thought FileReader was crazy...
  6169. getEntries(function() {
  6170. _readEntries(entries, cb);
  6171. });
  6172. }
  6173. }
  6174. return (extensions.FileDrop = FileDrop);
  6175. });
  6176. // Included from: src/javascript/runtime/html5/file/FileReader.js
  6177. /**
  6178. * FileReader.js
  6179. *
  6180. * Copyright 2013, Moxiecode Systems AB
  6181. * Released under GPL License.
  6182. *
  6183. * License: http://www.plupload.com/license
  6184. * Contributing: http://www.plupload.com/contributing
  6185. */
  6186. /**
  6187. @class moxie/runtime/html5/file/FileReader
  6188. @private
  6189. */
  6190. define("moxie/runtime/html5/file/FileReader", [
  6191. "moxie/runtime/html5/Runtime",
  6192. "moxie/core/utils/Encode",
  6193. "moxie/core/utils/Basic"
  6194. ], function(extensions, Encode, Basic) {
  6195. function FileReader() {
  6196. var _fr, _convertToBinary = false;
  6197. Basic.extend(this, {
  6198. read: function(op, blob) {
  6199. var comp = this;
  6200. comp.result = '';
  6201. _fr = new window.FileReader();
  6202. _fr.addEventListener('progress', function(e) {
  6203. comp.trigger(e);
  6204. });
  6205. _fr.addEventListener('load', function(e) {
  6206. comp.result = _convertToBinary ? _toBinary(_fr.result) : _fr.result;
  6207. comp.trigger(e);
  6208. });
  6209. _fr.addEventListener('error', function(e) {
  6210. comp.trigger(e, _fr.error);
  6211. });
  6212. _fr.addEventListener('loadend', function(e) {
  6213. _fr = null;
  6214. comp.trigger(e);
  6215. });
  6216. if (Basic.typeOf(_fr[op]) === 'function') {
  6217. _convertToBinary = false;
  6218. _fr[op](blob.getSource());
  6219. } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
  6220. _convertToBinary = true;
  6221. _fr.readAsDataURL(blob.getSource());
  6222. }
  6223. },
  6224. abort: function() {
  6225. if (_fr) {
  6226. _fr.abort();
  6227. }
  6228. },
  6229. destroy: function() {
  6230. _fr = null;
  6231. this.getRuntime().getShim().removeInstance(this.uid);
  6232. }
  6233. });
  6234. function _toBinary(str) {
  6235. return Encode.atob(str.substring(str.indexOf('base64,') + 7));
  6236. }
  6237. }
  6238. return (extensions.FileReader = FileReader);
  6239. });
  6240. // Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js
  6241. /**
  6242. * XMLHttpRequest.js
  6243. *
  6244. * Copyright 2013, Moxiecode Systems AB
  6245. * Released under GPL License.
  6246. *
  6247. * License: http://www.plupload.com/license
  6248. * Contributing: http://www.plupload.com/contributing
  6249. */
  6250. /*global ActiveXObject:true */
  6251. /**
  6252. @class moxie/runtime/html5/xhr/XMLHttpRequest
  6253. @private
  6254. */
  6255. define("moxie/runtime/html5/xhr/XMLHttpRequest", [
  6256. "moxie/runtime/html5/Runtime",
  6257. "moxie/core/utils/Basic",
  6258. "moxie/core/utils/Mime",
  6259. "moxie/core/utils/Url",
  6260. "moxie/file/File",
  6261. "moxie/file/Blob",
  6262. "moxie/xhr/FormData",
  6263. "moxie/core/Exceptions",
  6264. "moxie/core/utils/Env"
  6265. ], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env) {
  6266. function XMLHttpRequest() {
  6267. var self = this
  6268. , _xhr
  6269. , _filename
  6270. ;
  6271. Basic.extend(this, {
  6272. send: function(meta, data) {
  6273. var target = this
  6274. , isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.verComp(Env.version, 4, '>=') && Env.verComp(Env.version, 7, '<'))
  6275. , isAndroidBrowser = Env.browser === 'Android Browser'
  6276. , mustSendAsBinary = false
  6277. ;
  6278. // extract file name
  6279. _filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase();
  6280. _xhr = _getNativeXHR();
  6281. _xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password);
  6282. // prepare data to be sent
  6283. if (data instanceof Blob) {
  6284. if (data.isDetached()) {
  6285. mustSendAsBinary = true;
  6286. }
  6287. data = data.getSource();
  6288. } else if (data instanceof FormData) {
  6289. if (data.hasBlob()) {
  6290. if (data.getBlob().isDetached()) {
  6291. data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state
  6292. mustSendAsBinary = true;
  6293. } else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) {
  6294. // Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
  6295. // Android browsers (default one and Dolphin) seem to have the same issue, see: #613
  6296. _preloadAndSend.call(target, meta, data);
  6297. return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D
  6298. }
  6299. }
  6300. // transfer fields to real FormData
  6301. if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart()
  6302. var fd = new window.FormData();
  6303. data.each(function(value, name) {
  6304. if (value instanceof Blob) {
  6305. fd.append(name, value.getSource());
  6306. } else {
  6307. fd.append(name, value);
  6308. }
  6309. });
  6310. data = fd;
  6311. }
  6312. }
  6313. // if XHR L2
  6314. if (_xhr.upload) {
  6315. if (meta.withCredentials) {
  6316. _xhr.withCredentials = true;
  6317. }
  6318. _xhr.addEventListener('load', function(e) {
  6319. target.trigger(e);
  6320. });
  6321. _xhr.addEventListener('error', function(e) {
  6322. target.trigger(e);
  6323. });
  6324. // additionally listen to progress events
  6325. _xhr.addEventListener('progress', function(e) {
  6326. target.trigger(e);
  6327. });
  6328. _xhr.upload.addEventListener('progress', function(e) {
  6329. target.trigger({
  6330. type: 'UploadProgress',
  6331. loaded: e.loaded,
  6332. total: e.total
  6333. });
  6334. });
  6335. // ... otherwise simulate XHR L2
  6336. } else {
  6337. _xhr.onreadystatechange = function onReadyStateChange() {
  6338. // fake Level 2 events
  6339. switch (_xhr.readyState) {
  6340. case 1: // XMLHttpRequest.OPENED
  6341. // readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu
  6342. break;
  6343. // looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu
  6344. case 2: // XMLHttpRequest.HEADERS_RECEIVED
  6345. break;
  6346. case 3: // XMLHttpRequest.LOADING
  6347. // try to fire progress event for not XHR L2
  6348. var total, loaded;
  6349. try {
  6350. if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers
  6351. total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here
  6352. }
  6353. if (_xhr.responseText) { // responseText was introduced in IE7
  6354. loaded = _xhr.responseText.length;
  6355. }
  6356. } catch(ex) {
  6357. total = loaded = 0;
  6358. }
  6359. target.trigger({
  6360. type: 'progress',
  6361. lengthComputable: !!total,
  6362. total: parseInt(total, 10),
  6363. loaded: loaded
  6364. });
  6365. break;
  6366. case 4: // XMLHttpRequest.DONE
  6367. // release readystatechange handler (mostly for IE)
  6368. _xhr.onreadystatechange = function() {};
  6369. // usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout
  6370. try {
  6371. if (_xhr.status >= 200 && _xhr.status < 400) {
  6372. target.trigger('load');
  6373. break;
  6374. }
  6375. } catch(ex) {}
  6376. target.trigger('error');
  6377. break;
  6378. }
  6379. };
  6380. }
  6381. // set request headers
  6382. if (!Basic.isEmptyObj(meta.headers)) {
  6383. Basic.each(meta.headers, function(value, header) {
  6384. _xhr.setRequestHeader(header, value);
  6385. });
  6386. }
  6387. // request response type
  6388. if ("" !== meta.responseType && 'responseType' in _xhr) {
  6389. if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one
  6390. _xhr.responseType = 'text';
  6391. } else {
  6392. _xhr.responseType = meta.responseType;
  6393. }
  6394. }
  6395. // send ...
  6396. if (!mustSendAsBinary) {
  6397. _xhr.send(data);
  6398. } else {
  6399. if (_xhr.sendAsBinary) { // Gecko
  6400. _xhr.sendAsBinary(data);
  6401. } else { // other browsers having support for typed arrays
  6402. (function() {
  6403. // mimic Gecko's sendAsBinary
  6404. var ui8a = new Uint8Array(data.length);
  6405. for (var i = 0; i < data.length; i++) {
  6406. ui8a[i] = (data.charCodeAt(i) & 0xff);
  6407. }
  6408. _xhr.send(ui8a.buffer);
  6409. }());
  6410. }
  6411. }
  6412. target.trigger('loadstart');
  6413. },
  6414. getStatus: function() {
  6415. // according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception
  6416. try {
  6417. if (_xhr) {
  6418. return _xhr.status;
  6419. }
  6420. } catch(ex) {}
  6421. return 0;
  6422. },
  6423. getResponse: function(responseType) {
  6424. var I = this.getRuntime();
  6425. try {
  6426. switch (responseType) {
  6427. case 'blob':
  6428. var file = new File(I.uid, _xhr.response);
  6429. // try to extract file name from content-disposition if possible (might be - not, if CORS for example)
  6430. var disposition = _xhr.getResponseHeader('Content-Disposition');
  6431. if (disposition) {
  6432. // extract filename from response header if available
  6433. var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/);
  6434. if (match) {
  6435. _filename = match[2];
  6436. }
  6437. }
  6438. file.name = _filename;
  6439. // pre-webkit Opera doesn't set type property on the blob response
  6440. if (!file.type) {
  6441. file.type = Mime.getFileMime(_filename);
  6442. }
  6443. return file;
  6444. case 'json':
  6445. if (!Env.can('return_response_type', 'json')) {
  6446. return _xhr.status === 200 && !!window.JSON ? JSON.parse(_xhr.responseText) : null;
  6447. }
  6448. return _xhr.response;
  6449. case 'document':
  6450. return _getDocument(_xhr);
  6451. default:
  6452. return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes
  6453. }
  6454. } catch(ex) {
  6455. return null;
  6456. }
  6457. },
  6458. getAllResponseHeaders: function() {
  6459. try {
  6460. return _xhr.getAllResponseHeaders();
  6461. } catch(ex) {}
  6462. return '';
  6463. },
  6464. abort: function() {
  6465. if (_xhr) {
  6466. _xhr.abort();
  6467. }
  6468. },
  6469. destroy: function() {
  6470. self = _filename = null;
  6471. this.getRuntime().getShim().removeInstance(this.uid);
  6472. }
  6473. });
  6474. // here we go... ugly fix for ugly bug
  6475. function _preloadAndSend(meta, data) {
  6476. var target = this, blob, fr;
  6477. // get original blob
  6478. blob = data.getBlob().getSource();
  6479. // preload blob in memory to be sent as binary string
  6480. fr = new window.FileReader();
  6481. fr.onload = function() {
  6482. // overwrite original blob
  6483. data.append(data.getBlobName(), new Blob(null, {
  6484. type: blob.type,
  6485. data: fr.result
  6486. }));
  6487. // invoke send operation again
  6488. self.send.call(target, meta, data);
  6489. };
  6490. fr.readAsBinaryString(blob);
  6491. }
  6492. function _getNativeXHR() {
  6493. if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.verComp(Env.version, 8, '<'))) { // IE7 has native XHR but it's buggy
  6494. return new window.XMLHttpRequest();
  6495. } else {
  6496. return (function() {
  6497. var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0
  6498. for (var i = 0; i < progIDs.length; i++) {
  6499. try {
  6500. return new ActiveXObject(progIDs[i]);
  6501. } catch (ex) {}
  6502. }
  6503. })();
  6504. }
  6505. }
  6506. // @credits Sergey Ilinsky (http://www.ilinsky.com/)
  6507. function _getDocument(xhr) {
  6508. var rXML = xhr.responseXML;
  6509. var rText = xhr.responseText;
  6510. // Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type)
  6511. if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) {
  6512. rXML = new window.ActiveXObject("Microsoft.XMLDOM");
  6513. rXML.async = false;
  6514. rXML.validateOnParse = false;
  6515. rXML.loadXML(rText);
  6516. }
  6517. // Check if there is no error in document
  6518. if (rXML) {
  6519. if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") {
  6520. return null;
  6521. }
  6522. }
  6523. return rXML;
  6524. }
  6525. function _prepareMultipart(fd) {
  6526. var boundary = '----moxieboundary' + new Date().getTime()
  6527. , dashdash = '--'
  6528. , crlf = '\r\n'
  6529. , multipart = ''
  6530. , I = this.getRuntime()
  6531. ;
  6532. if (!I.can('send_binary_string')) {
  6533. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  6534. }
  6535. _xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
  6536. // append multipart parameters
  6537. fd.each(function(value, name) {
  6538. // Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(),
  6539. // so we try it here ourselves with: unescape(encodeURIComponent(value))
  6540. if (value instanceof Blob) {
  6541. // Build RFC2388 blob
  6542. multipart += dashdash + boundary + crlf +
  6543. 'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf +
  6544. 'Content-Type: ' + (value.type || 'application/octet-stream') + crlf + crlf +
  6545. value.getSource() + crlf;
  6546. } else {
  6547. multipart += dashdash + boundary + crlf +
  6548. 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
  6549. unescape(encodeURIComponent(value)) + crlf;
  6550. }
  6551. });
  6552. multipart += dashdash + boundary + dashdash + crlf;
  6553. return multipart;
  6554. }
  6555. }
  6556. return (extensions.XMLHttpRequest = XMLHttpRequest);
  6557. });
  6558. // Included from: src/javascript/runtime/html5/utils/BinaryReader.js
  6559. /**
  6560. * BinaryReader.js
  6561. *
  6562. * Copyright 2013, Moxiecode Systems AB
  6563. * Released under GPL License.
  6564. *
  6565. * License: http://www.plupload.com/license
  6566. * Contributing: http://www.plupload.com/contributing
  6567. */
  6568. /**
  6569. @class moxie/runtime/html5/utils/BinaryReader
  6570. @private
  6571. */
  6572. define("moxie/runtime/html5/utils/BinaryReader", [
  6573. "moxie/core/utils/Basic"
  6574. ], function(Basic) {
  6575. function BinaryReader(data) {
  6576. if (data instanceof ArrayBuffer) {
  6577. ArrayBufferReader.apply(this, arguments);
  6578. } else {
  6579. UTF16StringReader.apply(this, arguments);
  6580. }
  6581. }
  6582. Basic.extend(BinaryReader.prototype, {
  6583. littleEndian: false,
  6584. read: function(idx, size) {
  6585. var sum, mv, i;
  6586. if (idx + size > this.length()) {
  6587. throw new Error("You are trying to read outside the source boundaries.");
  6588. }
  6589. mv = this.littleEndian
  6590. ? 0
  6591. : -8 * (size - 1)
  6592. ;
  6593. for (i = 0, sum = 0; i < size; i++) {
  6594. sum |= (this.readByteAt(idx + i) << Math.abs(mv + i*8));
  6595. }
  6596. return sum;
  6597. },
  6598. write: function(idx, num, size) {
  6599. var mv, i, str = '';
  6600. if (idx > this.length()) {
  6601. throw new Error("You are trying to write outside the source boundaries.");
  6602. }
  6603. mv = this.littleEndian
  6604. ? 0
  6605. : -8 * (size - 1)
  6606. ;
  6607. for (i = 0; i < size; i++) {
  6608. this.writeByteAt(idx + i, (num >> Math.abs(mv + i*8)) & 255);
  6609. }
  6610. },
  6611. BYTE: function(idx) {
  6612. return this.read(idx, 1);
  6613. },
  6614. SHORT: function(idx) {
  6615. return this.read(idx, 2);
  6616. },
  6617. LONG: function(idx) {
  6618. return this.read(idx, 4);
  6619. },
  6620. SLONG: function(idx) { // 2's complement notation
  6621. var num = this.read(idx, 4);
  6622. return (num > 2147483647 ? num - 4294967296 : num);
  6623. },
  6624. CHAR: function(idx) {
  6625. return String.fromCharCode(this.read(idx, 1));
  6626. },
  6627. STRING: function(idx, count) {
  6628. return this.asArray('CHAR', idx, count).join('');
  6629. },
  6630. asArray: function(type, idx, count) {
  6631. var values = [];
  6632. for (var i = 0; i < count; i++) {
  6633. values[i] = this[type](idx + i);
  6634. }
  6635. return values;
  6636. }
  6637. });
  6638. function ArrayBufferReader(data) {
  6639. var _dv = new DataView(data);
  6640. Basic.extend(this, {
  6641. readByteAt: function(idx) {
  6642. return _dv.getUint8(idx);
  6643. },
  6644. writeByteAt: function(idx, value) {
  6645. _dv.setUint8(idx, value);
  6646. },
  6647. SEGMENT: function(idx, size, value) {
  6648. switch (arguments.length) {
  6649. case 2:
  6650. return data.slice(idx, idx + size);
  6651. case 1:
  6652. return data.slice(idx);
  6653. case 3:
  6654. if (value === null) {
  6655. value = new ArrayBuffer();
  6656. }
  6657. if (value instanceof ArrayBuffer) {
  6658. var arr = new Uint8Array(this.length() - size + value.byteLength);
  6659. if (idx > 0) {
  6660. arr.set(new Uint8Array(data.slice(0, idx)), 0);
  6661. }
  6662. arr.set(new Uint8Array(value), idx);
  6663. arr.set(new Uint8Array(data.slice(idx + size)), idx + value.byteLength);
  6664. this.clear();
  6665. data = arr.buffer;
  6666. _dv = new DataView(data);
  6667. break;
  6668. }
  6669. default: return data;
  6670. }
  6671. },
  6672. length: function() {
  6673. return data ? data.byteLength : 0;
  6674. },
  6675. clear: function() {
  6676. _dv = data = null;
  6677. }
  6678. });
  6679. }
  6680. function UTF16StringReader(data) {
  6681. Basic.extend(this, {
  6682. readByteAt: function(idx) {
  6683. return data.charCodeAt(idx);
  6684. },
  6685. writeByteAt: function(idx, value) {
  6686. putstr(String.fromCharCode(value), idx, 1);
  6687. },
  6688. SEGMENT: function(idx, length, segment) {
  6689. switch (arguments.length) {
  6690. case 1:
  6691. return data.substr(idx);
  6692. case 2:
  6693. return data.substr(idx, length);
  6694. case 3:
  6695. putstr(segment !== null ? segment : '', idx, length);
  6696. break;
  6697. default: return data;
  6698. }
  6699. },
  6700. length: function() {
  6701. return data ? data.length : 0;
  6702. },
  6703. clear: function() {
  6704. data = null;
  6705. }
  6706. });
  6707. function putstr(segment, idx, length) {
  6708. length = arguments.length === 3 ? length : data.length - idx - 1;
  6709. data = data.substr(0, idx) + segment + data.substr(length + idx);
  6710. }
  6711. }
  6712. return BinaryReader;
  6713. });
  6714. // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js
  6715. /**
  6716. * JPEGHeaders.js
  6717. *
  6718. * Copyright 2013, Moxiecode Systems AB
  6719. * Released under GPL License.
  6720. *
  6721. * License: http://www.plupload.com/license
  6722. * Contributing: http://www.plupload.com/contributing
  6723. */
  6724. /**
  6725. @class moxie/runtime/html5/image/JPEGHeaders
  6726. @private
  6727. */
  6728. define("moxie/runtime/html5/image/JPEGHeaders", [
  6729. "moxie/runtime/html5/utils/BinaryReader",
  6730. "moxie/core/Exceptions"
  6731. ], function(BinaryReader, x) {
  6732. return function JPEGHeaders(data) {
  6733. var headers = [], _br, idx, marker, length = 0;
  6734. _br = new BinaryReader(data);
  6735. // Check if data is jpeg
  6736. if (_br.SHORT(0) !== 0xFFD8) {
  6737. _br.clear();
  6738. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  6739. }
  6740. idx = 2;
  6741. while (idx <= _br.length()) {
  6742. marker = _br.SHORT(idx);
  6743. // omit RST (restart) markers
  6744. if (marker >= 0xFFD0 && marker <= 0xFFD7) {
  6745. idx += 2;
  6746. continue;
  6747. }
  6748. // no headers allowed after SOS marker
  6749. if (marker === 0xFFDA || marker === 0xFFD9) {
  6750. break;
  6751. }
  6752. length = _br.SHORT(idx + 2) + 2;
  6753. // APPn marker detected
  6754. if (marker >= 0xFFE1 && marker <= 0xFFEF) {
  6755. headers.push({
  6756. hex: marker,
  6757. name: 'APP' + (marker & 0x000F),
  6758. start: idx,
  6759. length: length,
  6760. segment: _br.SEGMENT(idx, length)
  6761. });
  6762. }
  6763. idx += length;
  6764. }
  6765. _br.clear();
  6766. return {
  6767. headers: headers,
  6768. restore: function(data) {
  6769. var max, i, br;
  6770. br = new BinaryReader(data);
  6771. idx = br.SHORT(2) == 0xFFE0 ? 4 + br.SHORT(4) : 2;
  6772. for (i = 0, max = headers.length; i < max; i++) {
  6773. br.SEGMENT(idx, 0, headers[i].segment);
  6774. idx += headers[i].length;
  6775. }
  6776. data = br.SEGMENT();
  6777. br.clear();
  6778. return data;
  6779. },
  6780. strip: function(data) {
  6781. var br, headers, jpegHeaders, i;
  6782. jpegHeaders = new JPEGHeaders(data);
  6783. headers = jpegHeaders.headers;
  6784. jpegHeaders.purge();
  6785. br = new BinaryReader(data);
  6786. i = headers.length;
  6787. while (i--) {
  6788. br.SEGMENT(headers[i].start, headers[i].length, '');
  6789. }
  6790. data = br.SEGMENT();
  6791. br.clear();
  6792. return data;
  6793. },
  6794. get: function(name) {
  6795. var array = [];
  6796. for (var i = 0, max = headers.length; i < max; i++) {
  6797. if (headers[i].name === name.toUpperCase()) {
  6798. array.push(headers[i].segment);
  6799. }
  6800. }
  6801. return array;
  6802. },
  6803. set: function(name, segment) {
  6804. var array = [], i, ii, max;
  6805. if (typeof(segment) === 'string') {
  6806. array.push(segment);
  6807. } else {
  6808. array = segment;
  6809. }
  6810. for (i = ii = 0, max = headers.length; i < max; i++) {
  6811. if (headers[i].name === name.toUpperCase()) {
  6812. headers[i].segment = array[ii];
  6813. headers[i].length = array[ii].length;
  6814. ii++;
  6815. }
  6816. if (ii >= array.length) {
  6817. break;
  6818. }
  6819. }
  6820. },
  6821. purge: function() {
  6822. this.headers = headers = [];
  6823. }
  6824. };
  6825. };
  6826. });
  6827. // Included from: src/javascript/runtime/html5/image/ExifParser.js
  6828. /**
  6829. * ExifParser.js
  6830. *
  6831. * Copyright 2013, Moxiecode Systems AB
  6832. * Released under GPL License.
  6833. *
  6834. * License: http://www.plupload.com/license
  6835. * Contributing: http://www.plupload.com/contributing
  6836. */
  6837. /**
  6838. @class moxie/runtime/html5/image/ExifParser
  6839. @private
  6840. */
  6841. define("moxie/runtime/html5/image/ExifParser", [
  6842. "moxie/core/utils/Basic",
  6843. "moxie/runtime/html5/utils/BinaryReader",
  6844. "moxie/core/Exceptions"
  6845. ], function(Basic, BinaryReader, x) {
  6846. function ExifParser(data) {
  6847. var __super__, tags, tagDescs, offsets, idx, Tiff;
  6848. BinaryReader.call(this, data);
  6849. tags = {
  6850. tiff: {
  6851. /*
  6852. The image orientation viewed in terms of rows and columns.
  6853. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
  6854. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
  6855. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
  6856. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
  6857. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
  6858. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
  6859. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
  6860. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
  6861. */
  6862. 0x0112: 'Orientation',
  6863. 0x010E: 'ImageDescription',
  6864. 0x010F: 'Make',
  6865. 0x0110: 'Model',
  6866. 0x0131: 'Software',
  6867. 0x8769: 'ExifIFDPointer',
  6868. 0x8825: 'GPSInfoIFDPointer'
  6869. },
  6870. exif: {
  6871. 0x9000: 'ExifVersion',
  6872. 0xA001: 'ColorSpace',
  6873. 0xA002: 'PixelXDimension',
  6874. 0xA003: 'PixelYDimension',
  6875. 0x9003: 'DateTimeOriginal',
  6876. 0x829A: 'ExposureTime',
  6877. 0x829D: 'FNumber',
  6878. 0x8827: 'ISOSpeedRatings',
  6879. 0x9201: 'ShutterSpeedValue',
  6880. 0x9202: 'ApertureValue' ,
  6881. 0x9207: 'MeteringMode',
  6882. 0x9208: 'LightSource',
  6883. 0x9209: 'Flash',
  6884. 0x920A: 'FocalLength',
  6885. 0xA402: 'ExposureMode',
  6886. 0xA403: 'WhiteBalance',
  6887. 0xA406: 'SceneCaptureType',
  6888. 0xA404: 'DigitalZoomRatio',
  6889. 0xA408: 'Contrast',
  6890. 0xA409: 'Saturation',
  6891. 0xA40A: 'Sharpness'
  6892. },
  6893. gps: {
  6894. 0x0000: 'GPSVersionID',
  6895. 0x0001: 'GPSLatitudeRef',
  6896. 0x0002: 'GPSLatitude',
  6897. 0x0003: 'GPSLongitudeRef',
  6898. 0x0004: 'GPSLongitude'
  6899. },
  6900. thumb: {
  6901. 0x0201: 'JPEGInterchangeFormat',
  6902. 0x0202: 'JPEGInterchangeFormatLength'
  6903. }
  6904. };
  6905. tagDescs = {
  6906. 'ColorSpace': {
  6907. 1: 'sRGB',
  6908. 0: 'Uncalibrated'
  6909. },
  6910. 'MeteringMode': {
  6911. 0: 'Unknown',
  6912. 1: 'Average',
  6913. 2: 'CenterWeightedAverage',
  6914. 3: 'Spot',
  6915. 4: 'MultiSpot',
  6916. 5: 'Pattern',
  6917. 6: 'Partial',
  6918. 255: 'Other'
  6919. },
  6920. 'LightSource': {
  6921. 1: 'Daylight',
  6922. 2: 'Fliorescent',
  6923. 3: 'Tungsten',
  6924. 4: 'Flash',
  6925. 9: 'Fine weather',
  6926. 10: 'Cloudy weather',
  6927. 11: 'Shade',
  6928. 12: 'Daylight fluorescent (D 5700 - 7100K)',
  6929. 13: 'Day white fluorescent (N 4600 -5400K)',
  6930. 14: 'Cool white fluorescent (W 3900 - 4500K)',
  6931. 15: 'White fluorescent (WW 3200 - 3700K)',
  6932. 17: 'Standard light A',
  6933. 18: 'Standard light B',
  6934. 19: 'Standard light C',
  6935. 20: 'D55',
  6936. 21: 'D65',
  6937. 22: 'D75',
  6938. 23: 'D50',
  6939. 24: 'ISO studio tungsten',
  6940. 255: 'Other'
  6941. },
  6942. 'Flash': {
  6943. 0x0000: 'Flash did not fire',
  6944. 0x0001: 'Flash fired',
  6945. 0x0005: 'Strobe return light not detected',
  6946. 0x0007: 'Strobe return light detected',
  6947. 0x0009: 'Flash fired, compulsory flash mode',
  6948. 0x000D: 'Flash fired, compulsory flash mode, return light not detected',
  6949. 0x000F: 'Flash fired, compulsory flash mode, return light detected',
  6950. 0x0010: 'Flash did not fire, compulsory flash mode',
  6951. 0x0018: 'Flash did not fire, auto mode',
  6952. 0x0019: 'Flash fired, auto mode',
  6953. 0x001D: 'Flash fired, auto mode, return light not detected',
  6954. 0x001F: 'Flash fired, auto mode, return light detected',
  6955. 0x0020: 'No flash function',
  6956. 0x0041: 'Flash fired, red-eye reduction mode',
  6957. 0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
  6958. 0x0047: 'Flash fired, red-eye reduction mode, return light detected',
  6959. 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
  6960. 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
  6961. 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
  6962. 0x0059: 'Flash fired, auto mode, red-eye reduction mode',
  6963. 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
  6964. 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
  6965. },
  6966. 'ExposureMode': {
  6967. 0: 'Auto exposure',
  6968. 1: 'Manual exposure',
  6969. 2: 'Auto bracket'
  6970. },
  6971. 'WhiteBalance': {
  6972. 0: 'Auto white balance',
  6973. 1: 'Manual white balance'
  6974. },
  6975. 'SceneCaptureType': {
  6976. 0: 'Standard',
  6977. 1: 'Landscape',
  6978. 2: 'Portrait',
  6979. 3: 'Night scene'
  6980. },
  6981. 'Contrast': {
  6982. 0: 'Normal',
  6983. 1: 'Soft',
  6984. 2: 'Hard'
  6985. },
  6986. 'Saturation': {
  6987. 0: 'Normal',
  6988. 1: 'Low saturation',
  6989. 2: 'High saturation'
  6990. },
  6991. 'Sharpness': {
  6992. 0: 'Normal',
  6993. 1: 'Soft',
  6994. 2: 'Hard'
  6995. },
  6996. // GPS related
  6997. 'GPSLatitudeRef': {
  6998. N: 'North latitude',
  6999. S: 'South latitude'
  7000. },
  7001. 'GPSLongitudeRef': {
  7002. E: 'East longitude',
  7003. W: 'West longitude'
  7004. }
  7005. };
  7006. offsets = {
  7007. tiffHeader: 10
  7008. };
  7009. idx = offsets.tiffHeader;
  7010. __super__ = {
  7011. clear: this.clear
  7012. };
  7013. // Public functions
  7014. Basic.extend(this, {
  7015. read: function() {
  7016. try {
  7017. return ExifParser.prototype.read.apply(this, arguments);
  7018. } catch (ex) {
  7019. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7020. }
  7021. },
  7022. write: function() {
  7023. try {
  7024. return ExifParser.prototype.write.apply(this, arguments);
  7025. } catch (ex) {
  7026. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7027. }
  7028. },
  7029. UNDEFINED: function() {
  7030. return this.BYTE.apply(this, arguments);
  7031. },
  7032. RATIONAL: function(idx) {
  7033. return this.LONG(idx) / this.LONG(idx + 4)
  7034. },
  7035. SRATIONAL: function(idx) {
  7036. return this.SLONG(idx) / this.SLONG(idx + 4)
  7037. },
  7038. ASCII: function(idx) {
  7039. return this.CHAR(idx);
  7040. },
  7041. TIFF: function() {
  7042. return Tiff || null;
  7043. },
  7044. EXIF: function() {
  7045. var Exif = null;
  7046. if (offsets.exifIFD) {
  7047. try {
  7048. Exif = extractTags.call(this, offsets.exifIFD, tags.exif);
  7049. } catch(ex) {
  7050. return null;
  7051. }
  7052. // Fix formatting of some tags
  7053. if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') {
  7054. for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) {
  7055. exifVersion += String.fromCharCode(Exif.ExifVersion[i]);
  7056. }
  7057. Exif.ExifVersion = exifVersion;
  7058. }
  7059. }
  7060. return Exif;
  7061. },
  7062. GPS: function() {
  7063. var GPS = null;
  7064. if (offsets.gpsIFD) {
  7065. try {
  7066. GPS = extractTags.call(this, offsets.gpsIFD, tags.gps);
  7067. } catch (ex) {
  7068. return null;
  7069. }
  7070. // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..)
  7071. if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') {
  7072. GPS.GPSVersionID = GPS.GPSVersionID.join('.');
  7073. }
  7074. }
  7075. return GPS;
  7076. },
  7077. thumb: function() {
  7078. if (offsets.IFD1) {
  7079. try {
  7080. var IFD1Tags = extractTags.call(this, offsets.IFD1, tags.thumb);
  7081. if ('JPEGInterchangeFormat' in IFD1Tags) {
  7082. return this.SEGMENT(offsets.tiffHeader + IFD1Tags.JPEGInterchangeFormat, IFD1Tags.JPEGInterchangeFormatLength);
  7083. }
  7084. } catch (ex) {}
  7085. }
  7086. return null;
  7087. },
  7088. setExif: function(tag, value) {
  7089. // Right now only setting of width/height is possible
  7090. if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') { return false; }
  7091. return setTag.call(this, 'exif', tag, value);
  7092. },
  7093. clear: function() {
  7094. __super__.clear();
  7095. data = tags = tagDescs = Tiff = offsets = __super__ = null;
  7096. }
  7097. });
  7098. // Check if that's APP1 and that it has EXIF
  7099. if (this.SHORT(0) !== 0xFFE1 || this.STRING(4, 5).toUpperCase() !== "EXIF\0") {
  7100. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7101. }
  7102. // Set read order of multi-byte data
  7103. this.littleEndian = (this.SHORT(idx) == 0x4949);
  7104. // Check if always present bytes are indeed present
  7105. if (this.SHORT(idx+=2) !== 0x002A) {
  7106. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7107. }
  7108. offsets.IFD0 = offsets.tiffHeader + this.LONG(idx += 2);
  7109. Tiff = extractTags.call(this, offsets.IFD0, tags.tiff);
  7110. if ('ExifIFDPointer' in Tiff) {
  7111. offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer;
  7112. delete Tiff.ExifIFDPointer;
  7113. }
  7114. if ('GPSInfoIFDPointer' in Tiff) {
  7115. offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer;
  7116. delete Tiff.GPSInfoIFDPointer;
  7117. }
  7118. if (Basic.isEmptyObj(Tiff)) {
  7119. Tiff = null;
  7120. }
  7121. // check if we have a thumb as well
  7122. var IFD1Offset = this.LONG(offsets.IFD0 + this.SHORT(offsets.IFD0) * 12 + 2);
  7123. if (IFD1Offset) {
  7124. offsets.IFD1 = offsets.tiffHeader + IFD1Offset;
  7125. }
  7126. function extractTags(IFD_offset, tags2extract) {
  7127. var data = this;
  7128. var length, i, tag, type, count, size, offset, value, values = [], hash = {};
  7129. var types = {
  7130. 1 : 'BYTE',
  7131. 7 : 'UNDEFINED',
  7132. 2 : 'ASCII',
  7133. 3 : 'SHORT',
  7134. 4 : 'LONG',
  7135. 5 : 'RATIONAL',
  7136. 9 : 'SLONG',
  7137. 10: 'SRATIONAL'
  7138. };
  7139. var sizes = {
  7140. 'BYTE' : 1,
  7141. 'UNDEFINED' : 1,
  7142. 'ASCII' : 1,
  7143. 'SHORT' : 2,
  7144. 'LONG' : 4,
  7145. 'RATIONAL' : 8,
  7146. 'SLONG' : 4,
  7147. 'SRATIONAL' : 8
  7148. };
  7149. length = data.SHORT(IFD_offset);
  7150. // The size of APP1 including all these elements shall not exceed the 64 Kbytes specified in the JPEG standard.
  7151. for (i = 0; i < length; i++) {
  7152. values = [];
  7153. // Set binary reader pointer to beginning of the next tag
  7154. offset = IFD_offset + 2 + i*12;
  7155. tag = tags2extract[data.SHORT(offset)];
  7156. if (tag === undefined) {
  7157. continue; // Not the tag we requested
  7158. }
  7159. type = types[data.SHORT(offset+=2)];
  7160. count = data.LONG(offset+=2);
  7161. size = sizes[type];
  7162. if (!size) {
  7163. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7164. }
  7165. offset += 4;
  7166. // tag can only fit 4 bytes of data, if data is larger we should look outside
  7167. if (size * count > 4) {
  7168. // instead of data tag contains an offset of the data
  7169. offset = data.LONG(offset) + offsets.tiffHeader;
  7170. }
  7171. // in case we left the boundaries of data throw an early exception
  7172. if (offset + size * count >= this.length()) {
  7173. throw new x.ImageError(x.ImageError.INVALID_META_ERR);
  7174. }
  7175. // special care for the string
  7176. if (type === 'ASCII') {
  7177. hash[tag] = Basic.trim(data.STRING(offset, count).replace(/\0$/, '')); // strip trailing NULL
  7178. continue;
  7179. } else {
  7180. values = data.asArray(type, offset, count);
  7181. value = (count == 1 ? values[0] : values);
  7182. if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') {
  7183. hash[tag] = tagDescs[tag][value];
  7184. } else {
  7185. hash[tag] = value;
  7186. }
  7187. }
  7188. }
  7189. return hash;
  7190. }
  7191. // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported
  7192. function setTag(ifd, tag, value) {
  7193. var offset, length, tagOffset, valueOffset = 0;
  7194. // If tag name passed translate into hex key
  7195. if (typeof(tag) === 'string') {
  7196. var tmpTags = tags[ifd.toLowerCase()];
  7197. for (var hex in tmpTags) {
  7198. if (tmpTags[hex] === tag) {
  7199. tag = hex;
  7200. break;
  7201. }
  7202. }
  7203. }
  7204. offset = offsets[ifd.toLowerCase() + 'IFD'];
  7205. length = this.SHORT(offset);
  7206. for (var i = 0; i < length; i++) {
  7207. tagOffset = offset + 12 * i + 2;
  7208. if (this.SHORT(tagOffset) == tag) {
  7209. valueOffset = tagOffset + 8;
  7210. break;
  7211. }
  7212. }
  7213. if (!valueOffset) {
  7214. return false;
  7215. }
  7216. try {
  7217. this.write(valueOffset, value, 4);
  7218. } catch(ex) {
  7219. return false;
  7220. }
  7221. return true;
  7222. }
  7223. }
  7224. ExifParser.prototype = BinaryReader.prototype;
  7225. return ExifParser;
  7226. });
  7227. // Included from: src/javascript/runtime/html5/image/JPEG.js
  7228. /**
  7229. * JPEG.js
  7230. *
  7231. * Copyright 2013, Moxiecode Systems AB
  7232. * Released under GPL License.
  7233. *
  7234. * License: http://www.plupload.com/license
  7235. * Contributing: http://www.plupload.com/contributing
  7236. */
  7237. /**
  7238. @class moxie/runtime/html5/image/JPEG
  7239. @private
  7240. */
  7241. define("moxie/runtime/html5/image/JPEG", [
  7242. "moxie/core/utils/Basic",
  7243. "moxie/core/Exceptions",
  7244. "moxie/runtime/html5/image/JPEGHeaders",
  7245. "moxie/runtime/html5/utils/BinaryReader",
  7246. "moxie/runtime/html5/image/ExifParser"
  7247. ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {
  7248. function JPEG(data) {
  7249. var _br, _hm, _ep, _info;
  7250. _br = new BinaryReader(data);
  7251. // check if it is jpeg
  7252. if (_br.SHORT(0) !== 0xFFD8) {
  7253. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7254. }
  7255. // backup headers
  7256. _hm = new JPEGHeaders(data);
  7257. // extract exif info
  7258. try {
  7259. _ep = new ExifParser(_hm.get('app1')[0]);
  7260. } catch(ex) {}
  7261. // get dimensions
  7262. _info = _getDimensions.call(this);
  7263. Basic.extend(this, {
  7264. type: 'image/jpeg',
  7265. size: _br.length(),
  7266. width: _info && _info.width || 0,
  7267. height: _info && _info.height || 0,
  7268. setExif: function(tag, value) {
  7269. if (!_ep) {
  7270. return false; // or throw an exception
  7271. }
  7272. if (Basic.typeOf(tag) === 'object') {
  7273. Basic.each(tag, function(value, tag) {
  7274. _ep.setExif(tag, value);
  7275. });
  7276. } else {
  7277. _ep.setExif(tag, value);
  7278. }
  7279. // update internal headers
  7280. _hm.set('app1', _ep.SEGMENT());
  7281. },
  7282. writeHeaders: function() {
  7283. if (!arguments.length) {
  7284. // if no arguments passed, update headers internally
  7285. return _hm.restore(data);
  7286. }
  7287. return _hm.restore(arguments[0]);
  7288. },
  7289. stripHeaders: function(data) {
  7290. return _hm.strip(data);
  7291. },
  7292. purge: function() {
  7293. _purge.call(this);
  7294. }
  7295. });
  7296. if (_ep) {
  7297. this.meta = {
  7298. tiff: _ep.TIFF(),
  7299. exif: _ep.EXIF(),
  7300. gps: _ep.GPS(),
  7301. thumb: _getThumb()
  7302. };
  7303. }
  7304. function _getDimensions(br) {
  7305. var idx = 0
  7306. , marker
  7307. , length
  7308. ;
  7309. if (!br) {
  7310. br = _br;
  7311. }
  7312. // examine all through the end, since some images might have very large APP segments
  7313. while (idx <= br.length()) {
  7314. marker = br.SHORT(idx += 2);
  7315. if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
  7316. idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
  7317. return {
  7318. height: br.SHORT(idx),
  7319. width: br.SHORT(idx += 2)
  7320. };
  7321. }
  7322. length = br.SHORT(idx += 2);
  7323. idx += length - 2;
  7324. }
  7325. return null;
  7326. }
  7327. function _getThumb() {
  7328. var data = _ep.thumb()
  7329. , br
  7330. , info
  7331. ;
  7332. if (data) {
  7333. br = new BinaryReader(data);
  7334. info = _getDimensions(br);
  7335. br.clear();
  7336. if (info) {
  7337. info.data = data;
  7338. return info;
  7339. }
  7340. }
  7341. return null;
  7342. }
  7343. function _purge() {
  7344. if (!_ep || !_hm || !_br) {
  7345. return; // ignore any repeating purge requests
  7346. }
  7347. _ep.clear();
  7348. _hm.purge();
  7349. _br.clear();
  7350. _info = _hm = _ep = _br = null;
  7351. }
  7352. }
  7353. return JPEG;
  7354. });
  7355. // Included from: src/javascript/runtime/html5/image/PNG.js
  7356. /**
  7357. * PNG.js
  7358. *
  7359. * Copyright 2013, Moxiecode Systems AB
  7360. * Released under GPL License.
  7361. *
  7362. * License: http://www.plupload.com/license
  7363. * Contributing: http://www.plupload.com/contributing
  7364. */
  7365. /**
  7366. @class moxie/runtime/html5/image/PNG
  7367. @private
  7368. */
  7369. define("moxie/runtime/html5/image/PNG", [
  7370. "moxie/core/Exceptions",
  7371. "moxie/core/utils/Basic",
  7372. "moxie/runtime/html5/utils/BinaryReader"
  7373. ], function(x, Basic, BinaryReader) {
  7374. function PNG(data) {
  7375. var _br, _hm, _ep, _info;
  7376. _br = new BinaryReader(data);
  7377. // check if it's png
  7378. (function() {
  7379. var idx = 0, i = 0
  7380. , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A]
  7381. ;
  7382. for (i = 0; i < signature.length; i++, idx += 2) {
  7383. if (signature[i] != _br.SHORT(idx)) {
  7384. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7385. }
  7386. }
  7387. }());
  7388. function _getDimensions() {
  7389. var chunk, idx;
  7390. chunk = _getChunkAt.call(this, 8);
  7391. if (chunk.type == 'IHDR') {
  7392. idx = chunk.start;
  7393. return {
  7394. width: _br.LONG(idx),
  7395. height: _br.LONG(idx += 4)
  7396. };
  7397. }
  7398. return null;
  7399. }
  7400. function _purge() {
  7401. if (!_br) {
  7402. return; // ignore any repeating purge requests
  7403. }
  7404. _br.clear();
  7405. data = _info = _hm = _ep = _br = null;
  7406. }
  7407. _info = _getDimensions.call(this);
  7408. Basic.extend(this, {
  7409. type: 'image/png',
  7410. size: _br.length(),
  7411. width: _info.width,
  7412. height: _info.height,
  7413. purge: function() {
  7414. _purge.call(this);
  7415. }
  7416. });
  7417. // for PNG we can safely trigger purge automatically, as we do not keep any data for later
  7418. _purge.call(this);
  7419. function _getChunkAt(idx) {
  7420. var length, type, start, CRC;
  7421. length = _br.LONG(idx);
  7422. type = _br.STRING(idx += 4, 4);
  7423. start = idx += 4;
  7424. CRC = _br.LONG(idx + length);
  7425. return {
  7426. length: length,
  7427. type: type,
  7428. start: start,
  7429. CRC: CRC
  7430. };
  7431. }
  7432. }
  7433. return PNG;
  7434. });
  7435. // Included from: src/javascript/runtime/html5/image/ImageInfo.js
  7436. /**
  7437. * ImageInfo.js
  7438. *
  7439. * Copyright 2013, Moxiecode Systems AB
  7440. * Released under GPL License.
  7441. *
  7442. * License: http://www.plupload.com/license
  7443. * Contributing: http://www.plupload.com/contributing
  7444. */
  7445. /**
  7446. Optional image investigation tool for HTML5 runtime. Provides the following features:
  7447. - ability to distinguish image type (JPEG or PNG) by signature
  7448. - ability to extract image width/height directly from it's internals, without preloading in memory (fast)
  7449. - ability to extract APP headers from JPEGs (Exif, GPS, etc)
  7450. - ability to replace width/height tags in extracted JPEG headers
  7451. - ability to restore APP headers, that were for example stripped during image manipulation
  7452. @class moxie/runtime/html5/image/ImageInfo
  7453. @private
  7454. @param {String} data Image source as binary string
  7455. */
  7456. define("moxie/runtime/html5/image/ImageInfo", [
  7457. "moxie/core/utils/Basic",
  7458. "moxie/core/Exceptions",
  7459. "moxie/runtime/html5/image/JPEG",
  7460. "moxie/runtime/html5/image/PNG"
  7461. ], function(Basic, x, JPEG, PNG) {
  7462. return function(data) {
  7463. var _cs = [JPEG, PNG], _img;
  7464. // figure out the format, throw: ImageError.WRONG_FORMAT if not supported
  7465. _img = (function() {
  7466. for (var i = 0; i < _cs.length; i++) {
  7467. try {
  7468. return new _cs[i](data);
  7469. } catch (ex) {
  7470. // console.info(ex);
  7471. }
  7472. }
  7473. throw new x.ImageError(x.ImageError.WRONG_FORMAT);
  7474. }());
  7475. Basic.extend(this, {
  7476. /**
  7477. Image Mime Type extracted from it's depths
  7478. @property type
  7479. @type {String}
  7480. @default ''
  7481. */
  7482. type: '',
  7483. /**
  7484. Image size in bytes
  7485. @property size
  7486. @type {Number}
  7487. @default 0
  7488. */
  7489. size: 0,
  7490. /**
  7491. Image width extracted from image source
  7492. @property width
  7493. @type {Number}
  7494. @default 0
  7495. */
  7496. width: 0,
  7497. /**
  7498. Image height extracted from image source
  7499. @property height
  7500. @type {Number}
  7501. @default 0
  7502. */
  7503. height: 0,
  7504. /**
  7505. Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs.
  7506. @method setExif
  7507. @param {String} tag Tag to set
  7508. @param {Mixed} value Value to assign to the tag
  7509. */
  7510. setExif: function() {},
  7511. /**
  7512. Restores headers to the source.
  7513. @method writeHeaders
  7514. @param {String} data Image source as binary string
  7515. @return {String} Updated binary string
  7516. */
  7517. writeHeaders: function(data) {
  7518. return data;
  7519. },
  7520. /**
  7521. Strip all headers from the source.
  7522. @method stripHeaders
  7523. @param {String} data Image source as binary string
  7524. @return {String} Updated binary string
  7525. */
  7526. stripHeaders: function(data) {
  7527. return data;
  7528. },
  7529. /**
  7530. Dispose resources.
  7531. @method purge
  7532. */
  7533. purge: function() {
  7534. data = null;
  7535. }
  7536. });
  7537. Basic.extend(this, _img);
  7538. this.purge = function() {
  7539. _img.purge();
  7540. _img = null;
  7541. };
  7542. };
  7543. });
  7544. // Included from: src/javascript/runtime/html5/image/ResizerCanvas.js
  7545. /**
  7546. * ResizerCanvas.js
  7547. *
  7548. * Copyright 2013, Moxiecode Systems AB
  7549. * Released under GPL License.
  7550. *
  7551. * License: http://www.plupload.com/license
  7552. * Contributing: http://www.plupload.com/contributing
  7553. */
  7554. /**
  7555. * Resizes image/canvas using canvas
  7556. */
  7557. define("moxie/runtime/html5/image/ResizerCanvas", [], function() {
  7558. function scale(image, ratio, resample) {
  7559. var sD = image.width > image.height ? 'width' : 'height'; // take the largest side
  7560. var dD = Math.round(image[sD] * ratio);
  7561. var scaleCapped = false;
  7562. if (resample !== 'nearest' && (ratio < 0.5 || ratio > 2)) {
  7563. ratio = ratio < 0.5 ? 0.5 : 2;
  7564. scaleCapped = true;
  7565. }
  7566. var tCanvas = _scale(image, ratio);
  7567. if (scaleCapped) {
  7568. return scale(tCanvas, dD / tCanvas[sD], resample);
  7569. } else {
  7570. return tCanvas;
  7571. }
  7572. }
  7573. function _scale(image, ratio) {
  7574. var sW = image.width;
  7575. var sH = image.height;
  7576. var dW = Math.round(sW * ratio);
  7577. var dH = Math.round(sH * ratio);
  7578. var canvas = document.createElement('canvas');
  7579. canvas.width = dW;
  7580. canvas.height = dH;
  7581. canvas.getContext("2d").drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH);
  7582. image = null; // just in case
  7583. return canvas;
  7584. }
  7585. return {
  7586. scale: scale
  7587. };
  7588. });
  7589. // Included from: src/javascript/runtime/html5/image/Image.js
  7590. /**
  7591. * Image.js
  7592. *
  7593. * Copyright 2013, Moxiecode Systems AB
  7594. * Released under GPL License.
  7595. *
  7596. * License: http://www.plupload.com/license
  7597. * Contributing: http://www.plupload.com/contributing
  7598. */
  7599. /**
  7600. @class moxie/runtime/html5/image/Image
  7601. @private
  7602. */
  7603. define("moxie/runtime/html5/image/Image", [
  7604. "moxie/runtime/html5/Runtime",
  7605. "moxie/core/utils/Basic",
  7606. "moxie/core/Exceptions",
  7607. "moxie/core/utils/Encode",
  7608. "moxie/file/Blob",
  7609. "moxie/file/File",
  7610. "moxie/runtime/html5/image/ImageInfo",
  7611. "moxie/runtime/html5/image/ResizerCanvas",
  7612. "moxie/core/utils/Mime",
  7613. "moxie/core/utils/Env"
  7614. ], function(extensions, Basic, x, Encode, Blob, File, ImageInfo, ResizerCanvas, Mime, Env) {
  7615. function HTML5Image() {
  7616. var me = this
  7617. , _img, _imgInfo, _canvas, _binStr, _blob
  7618. , _modified = false // is set true whenever image is modified
  7619. , _preserveHeaders = true
  7620. ;
  7621. Basic.extend(this, {
  7622. loadFromBlob: function(blob) {
  7623. var I = this.getRuntime()
  7624. , asBinary = arguments.length > 1 ? arguments[1] : true
  7625. ;
  7626. if (!I.can('access_binary')) {
  7627. throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
  7628. }
  7629. _blob = blob;
  7630. if (blob.isDetached()) {
  7631. _binStr = blob.getSource();
  7632. _preload.call(this, _binStr);
  7633. } else if (Env.can('use_blob_uri')) {
  7634. _preload.call(this, URL.createObjectURL(blob.getSource()));
  7635. } else {
  7636. _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) {
  7637. if (asBinary) {
  7638. _binStr = _toBinary(dataUrl);
  7639. }
  7640. _preload.call(this, dataUrl);
  7641. });
  7642. }
  7643. },
  7644. loadFromImage: function(img, exact) {
  7645. var comp = this;
  7646. comp.meta = img.meta;
  7647. _blob = new File(null, {
  7648. name: img.name,
  7649. size: img.size,
  7650. type: img.type
  7651. });
  7652. if (Env.can('create_canvas') && !exact) {
  7653. _canvas = img.getAsCanvas();
  7654. setTimeout(function() {
  7655. comp.trigger('load');
  7656. });
  7657. } else {
  7658. _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL());
  7659. }
  7660. },
  7661. getInfo: function() {
  7662. var I = this.getRuntime(), info;
  7663. if (!_imgInfo && _binStr && I.can('access_image_binary')) {
  7664. _imgInfo = new ImageInfo(_binStr);
  7665. }
  7666. // this stuff below is definitely having fun with itself
  7667. info = {
  7668. width: _getImg().width || 0,
  7669. height: _getImg().height || 0,
  7670. type: _blob.type || Mime.getFileMime(_blob.name),
  7671. size: _binStr && _binStr.length || _blob.size || 0,
  7672. name: _blob.name || '',
  7673. meta: null
  7674. };
  7675. if (_preserveHeaders) {
  7676. info.meta = _imgInfo && _imgInfo.meta || this.meta || {};
  7677. // if data was taken from ImageInfo it will be a binary string, so we convert it to blob
  7678. if (info.meta && info.meta.thumb && !(info.meta.thumb.data instanceof Blob)) {
  7679. info.meta.thumb.data = new Blob(null, {
  7680. type: 'image/jpeg',
  7681. data: info.meta.thumb.data
  7682. });
  7683. }
  7684. }
  7685. return info;
  7686. },
  7687. resize: function(rect, ratio, options) {
  7688. var canvas = document.createElement('canvas');
  7689. canvas.width = rect.width;
  7690. canvas.height = rect.height;
  7691. canvas.getContext("2d").drawImage(_getImg(), rect.x, rect.y, rect.width, rect.height, 0, 0, canvas.width, canvas.height);
  7692. _canvas = ResizerCanvas.scale(canvas, ratio);
  7693. _preserveHeaders = options.preserveHeaders;
  7694. // rotate if required, according to orientation tag
  7695. if (!_preserveHeaders) {
  7696. var orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;
  7697. _canvas = _rotateToOrientaion(_canvas, orientation);
  7698. }
  7699. this.width = _canvas.width;
  7700. this.height = _canvas.height;
  7701. _modified = true;
  7702. this.trigger('Resize');
  7703. },
  7704. getAsCanvas: function() {
  7705. if (!_canvas) {
  7706. _canvas = _getCanvas();
  7707. }
  7708. _canvas.id = this.uid + '_canvas';
  7709. return _canvas;
  7710. },
  7711. getAsBlob: function(type, quality) {
  7712. if (type !== this.type) {
  7713. _modified = true; // reconsider the state
  7714. return new File(null, {
  7715. name: _blob.name || '',
  7716. type: type,
  7717. data: me.getAsDataURL(type, quality)
  7718. });
  7719. }
  7720. return new File(null, {
  7721. name: _blob.name || '',
  7722. type: type,
  7723. data: me.getAsBinaryString(type, quality)
  7724. });
  7725. },
  7726. getAsDataURL: function(type) {
  7727. var quality = arguments[1] || 90;
  7728. // if image has not been modified, return the source right away
  7729. if (!_modified && _img.src.substr(0, 5) === 'data:') {
  7730. return _img.src;
  7731. }
  7732. // make sure we have a canvas to work with
  7733. _getCanvas();
  7734. if ('image/jpeg' !== type) {
  7735. return _canvas.toDataURL('image/png');
  7736. } else {
  7737. try {
  7738. // older Geckos used to result in an exception on quality argument
  7739. return _canvas.toDataURL('image/jpeg', quality/100);
  7740. } catch (ex) {
  7741. return _canvas.toDataURL('image/jpeg');
  7742. }
  7743. }
  7744. },
  7745. getAsBinaryString: function(type, quality) {
  7746. // if image has not been modified, return the source right away
  7747. if (!_modified) {
  7748. // if image was not loaded from binary string
  7749. if (!_binStr) {
  7750. _binStr = _toBinary(me.getAsDataURL(type, quality));
  7751. }
  7752. return _binStr;
  7753. }
  7754. if ('image/jpeg' !== type) {
  7755. _binStr = _toBinary(me.getAsDataURL(type, quality));
  7756. } else {
  7757. var dataUrl;
  7758. // if jpeg
  7759. if (!quality) {
  7760. quality = 90;
  7761. }
  7762. // make sure we have a canvas to work with
  7763. _getCanvas();
  7764. try {
  7765. // older Geckos used to result in an exception on quality argument
  7766. dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
  7767. } catch (ex) {
  7768. dataUrl = _canvas.toDataURL('image/jpeg');
  7769. }
  7770. _binStr = _toBinary(dataUrl);
  7771. if (_imgInfo) {
  7772. _binStr = _imgInfo.stripHeaders(_binStr);
  7773. if (_preserveHeaders) {
  7774. // update dimensions info in exif
  7775. if (_imgInfo.meta && _imgInfo.meta.exif) {
  7776. _imgInfo.setExif({
  7777. PixelXDimension: this.width,
  7778. PixelYDimension: this.height
  7779. });
  7780. }
  7781. // re-inject the headers
  7782. _binStr = _imgInfo.writeHeaders(_binStr);
  7783. }
  7784. // will be re-created from fresh on next getInfo call
  7785. _imgInfo.purge();
  7786. _imgInfo = null;
  7787. }
  7788. }
  7789. _modified = false;
  7790. return _binStr;
  7791. },
  7792. destroy: function() {
  7793. me = null;
  7794. _purge.call(this);
  7795. this.getRuntime().getShim().removeInstance(this.uid);
  7796. }
  7797. });
  7798. function _getImg() {
  7799. if (!_canvas && !_img) {
  7800. throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
  7801. }
  7802. return _canvas || _img;
  7803. }
  7804. function _getCanvas() {
  7805. var canvas = _getImg();
  7806. if (canvas.nodeName.toLowerCase() == 'canvas') {
  7807. return canvas;
  7808. }
  7809. _canvas = document.createElement('canvas');
  7810. _canvas.width = canvas.width;
  7811. _canvas.height = canvas.height;
  7812. _canvas.getContext("2d").drawImage(canvas, 0, 0);
  7813. return _canvas;
  7814. }
  7815. function _toBinary(str) {
  7816. return Encode.atob(str.substring(str.indexOf('base64,') + 7));
  7817. }
  7818. function _toDataUrl(str, type) {
  7819. return 'data:' + (type || '') + ';base64,' + Encode.btoa(str);
  7820. }
  7821. function _preload(str) {
  7822. var comp = this;
  7823. var prefix = str.substr(0, 5);
  7824. _img = new Image();
  7825. _img.onerror = function() {
  7826. _purge.call(this);
  7827. comp.trigger('error', x.ImageError.WRONG_FORMAT);
  7828. };
  7829. _img.onload = function() {
  7830. comp.trigger('load');
  7831. };
  7832. _img.src = (prefix === 'data:' || prefix === 'blob:' ? str : _toDataUrl(str, _blob.type));
  7833. }
  7834. function _readAsDataUrl(file, callback) {
  7835. var comp = this, fr;
  7836. // use FileReader if it's available
  7837. if (window.FileReader) {
  7838. fr = new FileReader();
  7839. fr.onload = function() {
  7840. callback.call(comp, this.result);
  7841. };
  7842. fr.onerror = function() {
  7843. comp.trigger('error', x.ImageError.WRONG_FORMAT);
  7844. };
  7845. fr.readAsDataURL(file);
  7846. } else {
  7847. return callback.call(this, file.getAsDataURL());
  7848. }
  7849. }
  7850. /**
  7851. * Transform canvas coordination according to specified frame size and orientation
  7852. * Orientation value is from EXIF tag
  7853. * @author Shinichi Tomita <shinichi.tomita@gmail.com>
  7854. */
  7855. function _rotateToOrientaion(img, orientation) {
  7856. var RADIANS = Math.PI/180;
  7857. var canvas = document.createElement('canvas');
  7858. var ctx = canvas.getContext('2d');
  7859. var width = img.width;
  7860. var height = img.height;
  7861. if (Basic.inArray(orientation, [5,6,7,8]) > -1) {
  7862. canvas.width = height;
  7863. canvas.height = width;
  7864. } else {
  7865. canvas.width = width;
  7866. canvas.height = height;
  7867. }
  7868. /**
  7869. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
  7870. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
  7871. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
  7872. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
  7873. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
  7874. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
  7875. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
  7876. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
  7877. */
  7878. switch (orientation) {
  7879. case 2:
  7880. // horizontal flip
  7881. ctx.translate(width, 0);
  7882. ctx.scale(-1, 1);
  7883. break;
  7884. case 3:
  7885. // 180 rotate left
  7886. ctx.translate(width, height);
  7887. ctx.rotate(180 * RADIANS);
  7888. break;
  7889. case 4:
  7890. // vertical flip
  7891. ctx.translate(0, height);
  7892. ctx.scale(1, -1);
  7893. break;
  7894. case 5:
  7895. // vertical flip + 90 rotate right
  7896. ctx.rotate(90 * RADIANS);
  7897. ctx.scale(1, -1);
  7898. break;
  7899. case 6:
  7900. // 90 rotate right
  7901. ctx.rotate(90 * RADIANS);
  7902. ctx.translate(0, -height);
  7903. break;
  7904. case 7:
  7905. // horizontal flip + 90 rotate right
  7906. ctx.rotate(90 * RADIANS);
  7907. ctx.translate(width, -height);
  7908. ctx.scale(-1, 1);
  7909. break;
  7910. case 8:
  7911. // 90 rotate left
  7912. ctx.rotate(-90 * RADIANS);
  7913. ctx.translate(-width, 0);
  7914. break;
  7915. }
  7916. ctx.drawImage(img, 0, 0, width, height);
  7917. return canvas;
  7918. }
  7919. function _purge() {
  7920. if (_imgInfo) {
  7921. _imgInfo.purge();
  7922. _imgInfo = null;
  7923. }
  7924. if (_img && Env.can('use_blob_uri')) {
  7925. URL.revokeObjectURL(_img.src);
  7926. }
  7927. _binStr = _img = _canvas = _blob = null;
  7928. _modified = false;
  7929. }
  7930. }
  7931. return (extensions.Image = HTML5Image);
  7932. });
  7933. // Included from: src/javascript/runtime/flash/Runtime.js
  7934. /**
  7935. * Runtime.js
  7936. *
  7937. * Copyright 2013, Moxiecode Systems AB
  7938. * Released under GPL License.
  7939. *
  7940. * License: http://www.plupload.com/license
  7941. * Contributing: http://www.plupload.com/contributing
  7942. */
  7943. /*global ActiveXObject:true */
  7944. /**
  7945. Defines constructor for Flash runtime.
  7946. @class moxie/runtime/flash/Runtime
  7947. @private
  7948. */
  7949. define("moxie/runtime/flash/Runtime", [
  7950. "moxie/core/utils/Basic",
  7951. "moxie/core/utils/Env",
  7952. "moxie/core/utils/Dom",
  7953. "moxie/core/Exceptions",
  7954. "moxie/runtime/Runtime"
  7955. ], function(Basic, Env, Dom, x, Runtime) {
  7956. var type = 'flash', extensions = {};
  7957. /**
  7958. Get the version of the Flash Player
  7959. @method getShimVersion
  7960. @private
  7961. @return {Number} Flash Player version
  7962. */
  7963. function getShimVersion() {
  7964. var version;
  7965. try {
  7966. version = navigator.plugins['Shockwave Flash'];
  7967. version = version.description;
  7968. } catch (e1) {
  7969. try {
  7970. version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
  7971. } catch (e2) {
  7972. version = '0.0';
  7973. }
  7974. }
  7975. version = version.match(/\d+/g);
  7976. return parseFloat(version[0] + '.' + version[1]);
  7977. }
  7978. /**
  7979. Cross-browser SWF removal
  7980. - Especially needed to safely and completely remove a SWF in Internet Explorer
  7981. Originated from SWFObject v2.2 <http://code.google.com/p/swfobject/>
  7982. */
  7983. function removeSWF(id) {
  7984. var obj = Dom.get(id);
  7985. if (obj && obj.nodeName == "OBJECT") {
  7986. if (Env.browser === 'IE') {
  7987. obj.style.display = "none";
  7988. (function onInit(){
  7989. // http://msdn.microsoft.com/en-us/library/ie/ms534360(v=vs.85).aspx
  7990. if (obj.readyState == 4) {
  7991. removeObjectInIE(id);
  7992. }
  7993. else {
  7994. setTimeout(onInit, 10);
  7995. }
  7996. })();
  7997. }
  7998. else {
  7999. obj.parentNode.removeChild(obj);
  8000. }
  8001. }
  8002. }
  8003. function removeObjectInIE(id) {
  8004. var obj = Dom.get(id);
  8005. if (obj) {
  8006. for (var i in obj) {
  8007. if (typeof obj[i] == "function") {
  8008. obj[i] = null;
  8009. }
  8010. }
  8011. obj.parentNode.removeChild(obj);
  8012. }
  8013. }
  8014. /**
  8015. Constructor for the Flash Runtime
  8016. */
  8017. function FlashRuntime(options) {
  8018. var I = this, initTimer;
  8019. options = Basic.extend({ swf_url: Env.swf_url }, options);
  8020. Runtime.call(this, options, type, {
  8021. access_binary: function(value) {
  8022. return value && I.mode === 'browser';
  8023. },
  8024. access_image_binary: function(value) {
  8025. return value && I.mode === 'browser';
  8026. },
  8027. display_media: Runtime.capTest(defined('moxie/image/Image')),
  8028. do_cors: Runtime.capTrue,
  8029. drag_and_drop: false,
  8030. report_upload_progress: function() {
  8031. return I.mode === 'client';
  8032. },
  8033. resize_image: Runtime.capTrue,
  8034. return_response_headers: false,
  8035. return_response_type: function(responseType) {
  8036. if (responseType === 'json' && !!window.JSON) {
  8037. return true;
  8038. }
  8039. return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser';
  8040. },
  8041. return_status_code: function(code) {
  8042. return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]);
  8043. },
  8044. select_file: Runtime.capTrue,
  8045. select_multiple: Runtime.capTrue,
  8046. send_binary_string: function(value) {
  8047. return value && I.mode === 'browser';
  8048. },
  8049. send_browser_cookies: function(value) {
  8050. return value && I.mode === 'browser';
  8051. },
  8052. send_custom_headers: function(value) {
  8053. return value && I.mode === 'browser';
  8054. },
  8055. send_multipart: Runtime.capTrue,
  8056. slice_blob: function(value) {
  8057. return value && I.mode === 'browser';
  8058. },
  8059. stream_upload: function(value) {
  8060. return value && I.mode === 'browser';
  8061. },
  8062. summon_file_dialog: false,
  8063. upload_filesize: function(size) {
  8064. return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client';
  8065. },
  8066. use_http_method: function(methods) {
  8067. return !Basic.arrayDiff(methods, ['GET', 'POST']);
  8068. }
  8069. }, {
  8070. // capabilities that require specific mode
  8071. access_binary: function(value) {
  8072. return value ? 'browser' : 'client';
  8073. },
  8074. access_image_binary: function(value) {
  8075. return value ? 'browser' : 'client';
  8076. },
  8077. report_upload_progress: function(value) {
  8078. return value ? 'browser' : 'client';
  8079. },
  8080. return_response_type: function(responseType) {
  8081. return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser'];
  8082. },
  8083. return_status_code: function(code) {
  8084. return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser'];
  8085. },
  8086. send_binary_string: function(value) {
  8087. return value ? 'browser' : 'client';
  8088. },
  8089. send_browser_cookies: function(value) {
  8090. return value ? 'browser' : 'client';
  8091. },
  8092. send_custom_headers: function(value) {
  8093. return value ? 'browser' : 'client';
  8094. },
  8095. slice_blob: function(value) {
  8096. return value ? 'browser' : 'client';
  8097. },
  8098. stream_upload: function(value) {
  8099. return value ? 'client' : 'browser';
  8100. },
  8101. upload_filesize: function(size) {
  8102. return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser';
  8103. }
  8104. }, 'client');
  8105. // minimal requirement for Flash Player version
  8106. if (getShimVersion() < 11.3) {
  8107. if (MXI_DEBUG && Env.debug.runtime) {
  8108. Env.log("\tFlash didn't meet minimal version requirement (11.3).");
  8109. }
  8110. this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before
  8111. }
  8112. Basic.extend(this, {
  8113. getShim: function() {
  8114. return Dom.get(this.uid);
  8115. },
  8116. shimExec: function(component, action) {
  8117. var args = [].slice.call(arguments, 2);
  8118. return I.getShim().exec(this.uid, component, action, args);
  8119. },
  8120. init: function() {
  8121. var html, el, container;
  8122. container = this.getShimContainer();
  8123. // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
  8124. Basic.extend(container.style, {
  8125. position: 'absolute',
  8126. top: '-8px',
  8127. left: '-8px',
  8128. width: '9px',
  8129. height: '9px',
  8130. overflow: 'hidden'
  8131. });
  8132. // insert flash object
  8133. html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" ';
  8134. if (Env.browser === 'IE') {
  8135. html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
  8136. }
  8137. html += 'width="100%" height="100%" style="outline:0">' +
  8138. '<param name="movie" value="' + options.swf_url + '" />' +
  8139. '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Runtime.getGlobalEventTarget() + '" />' +
  8140. '<param name="wmode" value="transparent" />' +
  8141. '<param name="allowscriptaccess" value="always" />' +
  8142. '</object>';
  8143. if (Env.browser === 'IE') {
  8144. el = document.createElement('div');
  8145. container.appendChild(el);
  8146. el.outerHTML = html;
  8147. el = container = null; // just in case
  8148. } else {
  8149. container.innerHTML = html;
  8150. }
  8151. // Init is dispatched by the shim
  8152. initTimer = setTimeout(function() {
  8153. if (I && !I.initialized) { // runtime might be already destroyed by this moment
  8154. I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  8155. if (MXI_DEBUG && Env.debug.runtime) {
  8156. Env.log("\tFlash failed to initialize within a specified period of time (typically 5s).");
  8157. }
  8158. }
  8159. }, 5000);
  8160. },
  8161. destroy: (function(destroy) { // extend default destroy method
  8162. return function() {
  8163. removeSWF(I.uid); // SWF removal requires special care in IE
  8164. destroy.call(I);
  8165. clearTimeout(initTimer); // initialization check might be still onwait
  8166. options = initTimer = destroy = I = null;
  8167. };
  8168. }(this.destroy))
  8169. }, extensions);
  8170. }
  8171. Runtime.addConstructor(type, FlashRuntime);
  8172. return extensions;
  8173. });
  8174. // Included from: src/javascript/runtime/flash/file/Blob.js
  8175. /**
  8176. * Blob.js
  8177. *
  8178. * Copyright 2013, Moxiecode Systems AB
  8179. * Released under GPL License.
  8180. *
  8181. * License: http://www.plupload.com/license
  8182. * Contributing: http://www.plupload.com/contributing
  8183. */
  8184. /**
  8185. @class moxie/runtime/flash/file/Blob
  8186. @private
  8187. */
  8188. define("moxie/runtime/flash/file/Blob", [
  8189. "moxie/runtime/flash/Runtime",
  8190. "moxie/file/Blob"
  8191. ], function(extensions, Blob) {
  8192. var FlashBlob = {
  8193. slice: function(blob, start, end, type) {
  8194. var self = this.getRuntime();
  8195. if (start < 0) {
  8196. start = Math.max(blob.size + start, 0);
  8197. } else if (start > 0) {
  8198. start = Math.min(start, blob.size);
  8199. }
  8200. if (end < 0) {
  8201. end = Math.max(blob.size + end, 0);
  8202. } else if (end > 0) {
  8203. end = Math.min(end, blob.size);
  8204. }
  8205. blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || '');
  8206. if (blob) {
  8207. blob = new Blob(self.uid, blob);
  8208. }
  8209. return blob;
  8210. }
  8211. };
  8212. return (extensions.Blob = FlashBlob);
  8213. });
  8214. // Included from: src/javascript/runtime/flash/file/FileInput.js
  8215. /**
  8216. * FileInput.js
  8217. *
  8218. * Copyright 2013, Moxiecode Systems AB
  8219. * Released under GPL License.
  8220. *
  8221. * License: http://www.plupload.com/license
  8222. * Contributing: http://www.plupload.com/contributing
  8223. */
  8224. /**
  8225. @class moxie/runtime/flash/file/FileInput
  8226. @private
  8227. */
  8228. define("moxie/runtime/flash/file/FileInput", [
  8229. "moxie/runtime/flash/Runtime",
  8230. "moxie/file/File",
  8231. "moxie/core/utils/Dom",
  8232. "moxie/core/utils/Basic"
  8233. ], function(extensions, File, Dom, Basic) {
  8234. var FileInput = {
  8235. init: function(options) {
  8236. var comp = this, I = this.getRuntime();
  8237. var browseButton = Dom.get(options.browse_button);
  8238. if (browseButton) {
  8239. browseButton.setAttribute('tabindex', -1);
  8240. browseButton = null;
  8241. }
  8242. this.bind("Change", function() {
  8243. var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
  8244. comp.files = [];
  8245. Basic.each(files, function(file) {
  8246. comp.files.push(new File(I.uid, file));
  8247. });
  8248. }, 999);
  8249. this.getRuntime().shimExec.call(this, 'FileInput', 'init', {
  8250. accept: options.accept,
  8251. multiple: options.multiple
  8252. });
  8253. this.trigger('ready');
  8254. }
  8255. };
  8256. return (extensions.FileInput = FileInput);
  8257. });
  8258. // Included from: src/javascript/runtime/flash/file/FileReader.js
  8259. /**
  8260. * FileReader.js
  8261. *
  8262. * Copyright 2013, Moxiecode Systems AB
  8263. * Released under GPL License.
  8264. *
  8265. * License: http://www.plupload.com/license
  8266. * Contributing: http://www.plupload.com/contributing
  8267. */
  8268. /**
  8269. @class moxie/runtime/flash/file/FileReader
  8270. @private
  8271. */
  8272. define("moxie/runtime/flash/file/FileReader", [
  8273. "moxie/runtime/flash/Runtime",
  8274. "moxie/core/utils/Encode"
  8275. ], function(extensions, Encode) {
  8276. function _formatData(data, op) {
  8277. switch (op) {
  8278. case 'readAsText':
  8279. return Encode.atob(data, 'utf8');
  8280. case 'readAsBinaryString':
  8281. return Encode.atob(data);
  8282. case 'readAsDataURL':
  8283. return data;
  8284. }
  8285. return null;
  8286. }
  8287. var FileReader = {
  8288. read: function(op, blob) {
  8289. var comp = this;
  8290. comp.result = '';
  8291. // special prefix for DataURL read mode
  8292. if (op === 'readAsDataURL') {
  8293. comp.result = 'data:' + (blob.type || '') + ';base64,';
  8294. }
  8295. comp.bind('Progress', function(e, data) {
  8296. if (data) {
  8297. comp.result += _formatData(data, op);
  8298. }
  8299. }, 999);
  8300. return comp.getRuntime().shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid);
  8301. }
  8302. };
  8303. return (extensions.FileReader = FileReader);
  8304. });
  8305. // Included from: src/javascript/runtime/flash/file/FileReaderSync.js
  8306. /**
  8307. * FileReaderSync.js
  8308. *
  8309. * Copyright 2013, Moxiecode Systems AB
  8310. * Released under GPL License.
  8311. *
  8312. * License: http://www.plupload.com/license
  8313. * Contributing: http://www.plupload.com/contributing
  8314. */
  8315. /**
  8316. @class moxie/runtime/flash/file/FileReaderSync
  8317. @private
  8318. */
  8319. define("moxie/runtime/flash/file/FileReaderSync", [
  8320. "moxie/runtime/flash/Runtime",
  8321. "moxie/core/utils/Encode"
  8322. ], function(extensions, Encode) {
  8323. function _formatData(data, op) {
  8324. switch (op) {
  8325. case 'readAsText':
  8326. return Encode.atob(data, 'utf8');
  8327. case 'readAsBinaryString':
  8328. return Encode.atob(data);
  8329. case 'readAsDataURL':
  8330. return data;
  8331. }
  8332. return null;
  8333. }
  8334. var FileReaderSync = {
  8335. read: function(op, blob) {
  8336. var result, self = this.getRuntime();
  8337. result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid);
  8338. if (!result) {
  8339. return null; // or throw ex
  8340. }
  8341. // special prefix for DataURL read mode
  8342. if (op === 'readAsDataURL') {
  8343. result = 'data:' + (blob.type || '') + ';base64,' + result;
  8344. }
  8345. return _formatData(result, op, blob.type);
  8346. }
  8347. };
  8348. return (extensions.FileReaderSync = FileReaderSync);
  8349. });
  8350. // Included from: src/javascript/runtime/flash/runtime/Transporter.js
  8351. /**
  8352. * Transporter.js
  8353. *
  8354. * Copyright 2013, Moxiecode Systems AB
  8355. * Released under GPL License.
  8356. *
  8357. * License: http://www.plupload.com/license
  8358. * Contributing: http://www.plupload.com/contributing
  8359. */
  8360. /**
  8361. @class moxie/runtime/flash/runtime/Transporter
  8362. @private
  8363. */
  8364. define("moxie/runtime/flash/runtime/Transporter", [
  8365. "moxie/runtime/flash/Runtime",
  8366. "moxie/file/Blob"
  8367. ], function(extensions, Blob) {
  8368. var Transporter = {
  8369. getAsBlob: function(type) {
  8370. var self = this.getRuntime()
  8371. , blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type)
  8372. ;
  8373. if (blob) {
  8374. return new Blob(self.uid, blob);
  8375. }
  8376. return null;
  8377. }
  8378. };
  8379. return (extensions.Transporter = Transporter);
  8380. });
  8381. // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js
  8382. /**
  8383. * XMLHttpRequest.js
  8384. *
  8385. * Copyright 2013, Moxiecode Systems AB
  8386. * Released under GPL License.
  8387. *
  8388. * License: http://www.plupload.com/license
  8389. * Contributing: http://www.plupload.com/contributing
  8390. */
  8391. /**
  8392. @class moxie/runtime/flash/xhr/XMLHttpRequest
  8393. @private
  8394. */
  8395. define("moxie/runtime/flash/xhr/XMLHttpRequest", [
  8396. "moxie/runtime/flash/Runtime",
  8397. "moxie/core/utils/Basic",
  8398. "moxie/file/Blob",
  8399. "moxie/file/File",
  8400. "moxie/file/FileReaderSync",
  8401. "moxie/runtime/flash/file/FileReaderSync",
  8402. "moxie/xhr/FormData",
  8403. "moxie/runtime/Transporter",
  8404. "moxie/runtime/flash/runtime/Transporter"
  8405. ], function(extensions, Basic, Blob, File, FileReaderSync, FileReaderSyncFlash, FormData, Transporter, TransporterFlash) {
  8406. var XMLHttpRequest = {
  8407. send: function(meta, data) {
  8408. var target = this, self = target.getRuntime();
  8409. function send() {
  8410. meta.transport = self.mode;
  8411. self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data);
  8412. }
  8413. function appendBlob(name, blob) {
  8414. self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid);
  8415. data = null;
  8416. send();
  8417. }
  8418. function attachBlob(blob, cb) {
  8419. var tr = new Transporter();
  8420. tr.bind("TransportingComplete", function() {
  8421. cb(this.result);
  8422. });
  8423. tr.transport(blob.getSource(), blob.type, {
  8424. ruid: self.uid
  8425. });
  8426. }
  8427. // copy over the headers if any
  8428. if (!Basic.isEmptyObj(meta.headers)) {
  8429. Basic.each(meta.headers, function(value, header) {
  8430. self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object
  8431. });
  8432. }
  8433. // transfer over multipart params and blob itself
  8434. if (data instanceof FormData) {
  8435. var blobField;
  8436. data.each(function(value, name) {
  8437. if (value instanceof Blob) {
  8438. blobField = name;
  8439. } else {
  8440. self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value);
  8441. }
  8442. });
  8443. if (!data.hasBlob()) {
  8444. data = null;
  8445. send();
  8446. } else {
  8447. var blob = data.getBlob();
  8448. if (blob.isDetached()) {
  8449. attachBlob(blob, function(attachedBlob) {
  8450. blob.destroy();
  8451. appendBlob(blobField, attachedBlob);
  8452. });
  8453. } else {
  8454. appendBlob(blobField, blob);
  8455. }
  8456. }
  8457. } else if (data instanceof Blob) {
  8458. if (data.isDetached()) {
  8459. attachBlob(data, function(attachedBlob) {
  8460. data.destroy();
  8461. data = attachedBlob.uid;
  8462. send();
  8463. });
  8464. } else {
  8465. data = data.uid;
  8466. send();
  8467. }
  8468. } else {
  8469. send();
  8470. }
  8471. },
  8472. getResponse: function(responseType) {
  8473. var frs, blob, self = this.getRuntime();
  8474. blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob');
  8475. if (blob) {
  8476. blob = new File(self.uid, blob);
  8477. if ('blob' === responseType) {
  8478. return blob;
  8479. }
  8480. try {
  8481. frs = new FileReaderSync();
  8482. if (!!~Basic.inArray(responseType, ["", "text"])) {
  8483. return frs.readAsText(blob);
  8484. } else if ('json' === responseType && !!window.JSON) {
  8485. return JSON.parse(frs.readAsText(blob));
  8486. }
  8487. } finally {
  8488. blob.destroy();
  8489. }
  8490. }
  8491. return null;
  8492. },
  8493. abort: function(upload_complete_flag) {
  8494. var self = this.getRuntime();
  8495. self.shimExec.call(this, 'XMLHttpRequest', 'abort');
  8496. this.dispatchEvent('readystatechange');
  8497. // this.dispatchEvent('progress');
  8498. this.dispatchEvent('abort');
  8499. //if (!upload_complete_flag) {
  8500. // this.dispatchEvent('uploadprogress');
  8501. //}
  8502. }
  8503. };
  8504. return (extensions.XMLHttpRequest = XMLHttpRequest);
  8505. });
  8506. // Included from: src/javascript/runtime/flash/image/Image.js
  8507. /**
  8508. * Image.js
  8509. *
  8510. * Copyright 2013, Moxiecode Systems AB
  8511. * Released under GPL License.
  8512. *
  8513. * License: http://www.plupload.com/license
  8514. * Contributing: http://www.plupload.com/contributing
  8515. */
  8516. /**
  8517. @class moxie/runtime/flash/image/Image
  8518. @private
  8519. */
  8520. define("moxie/runtime/flash/image/Image", [
  8521. "moxie/runtime/flash/Runtime",
  8522. "moxie/core/utils/Basic",
  8523. "moxie/runtime/Transporter",
  8524. "moxie/file/Blob",
  8525. "moxie/file/FileReaderSync"
  8526. ], function(extensions, Basic, Transporter, Blob, FileReaderSync) {
  8527. var Image = {
  8528. loadFromBlob: function(blob) {
  8529. var comp = this, self = comp.getRuntime();
  8530. function exec(srcBlob) {
  8531. self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid);
  8532. comp = self = null;
  8533. }
  8534. if (blob.isDetached()) { // binary string
  8535. var tr = new Transporter();
  8536. tr.bind("TransportingComplete", function() {
  8537. exec(tr.result.getSource());
  8538. });
  8539. tr.transport(blob.getSource(), blob.type, { ruid: self.uid });
  8540. } else {
  8541. exec(blob.getSource());
  8542. }
  8543. },
  8544. loadFromImage: function(img) {
  8545. var self = this.getRuntime();
  8546. return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid);
  8547. },
  8548. getInfo: function() {
  8549. var self = this.getRuntime()
  8550. , info = self.shimExec.call(this, 'Image', 'getInfo')
  8551. ;
  8552. if (info.meta && info.meta.thumb && info.meta.thumb.data && !(self.meta.thumb.data instanceof Blob)) {
  8553. info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
  8554. }
  8555. return info;
  8556. },
  8557. getAsBlob: function(type, quality) {
  8558. var self = this.getRuntime()
  8559. , blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality)
  8560. ;
  8561. if (blob) {
  8562. return new Blob(self.uid, blob);
  8563. }
  8564. return null;
  8565. },
  8566. getAsDataURL: function() {
  8567. var self = this.getRuntime()
  8568. , blob = self.Image.getAsBlob.apply(this, arguments)
  8569. , frs
  8570. ;
  8571. if (!blob) {
  8572. return null;
  8573. }
  8574. frs = new FileReaderSync();
  8575. return frs.readAsDataURL(blob);
  8576. }
  8577. };
  8578. return (extensions.Image = Image);
  8579. });
  8580. // Included from: src/javascript/runtime/silverlight/Runtime.js
  8581. /**
  8582. * RunTime.js
  8583. *
  8584. * Copyright 2013, Moxiecode Systems AB
  8585. * Released under GPL License.
  8586. *
  8587. * License: http://www.plupload.com/license
  8588. * Contributing: http://www.plupload.com/contributing
  8589. */
  8590. /*global ActiveXObject:true */
  8591. /**
  8592. Defines constructor for Silverlight runtime.
  8593. @class moxie/runtime/silverlight/Runtime
  8594. @private
  8595. */
  8596. define("moxie/runtime/silverlight/Runtime", [
  8597. "moxie/core/utils/Basic",
  8598. "moxie/core/utils/Env",
  8599. "moxie/core/utils/Dom",
  8600. "moxie/core/Exceptions",
  8601. "moxie/runtime/Runtime"
  8602. ], function(Basic, Env, Dom, x, Runtime) {
  8603. var type = "silverlight", extensions = {};
  8604. function isInstalled(version) {
  8605. var isVersionSupported = false, control = null, actualVer,
  8606. actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0;
  8607. try {
  8608. try {
  8609. control = new ActiveXObject('AgControl.AgControl');
  8610. if (control.IsVersionSupported(version)) {
  8611. isVersionSupported = true;
  8612. }
  8613. control = null;
  8614. } catch (e) {
  8615. var plugin = navigator.plugins["Silverlight Plug-In"];
  8616. if (plugin) {
  8617. actualVer = plugin.description;
  8618. if (actualVer === "1.0.30226.2") {
  8619. actualVer = "2.0.30226.2";
  8620. }
  8621. actualVerArray = actualVer.split(".");
  8622. while (actualVerArray.length > 3) {
  8623. actualVerArray.pop();
  8624. }
  8625. while ( actualVerArray.length < 4) {
  8626. actualVerArray.push(0);
  8627. }
  8628. reqVerArray = version.split(".");
  8629. while (reqVerArray.length > 4) {
  8630. reqVerArray.pop();
  8631. }
  8632. do {
  8633. requiredVersionPart = parseInt(reqVerArray[index], 10);
  8634. actualVersionPart = parseInt(actualVerArray[index], 10);
  8635. index++;
  8636. } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
  8637. if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
  8638. isVersionSupported = true;
  8639. }
  8640. }
  8641. }
  8642. } catch (e2) {
  8643. isVersionSupported = false;
  8644. }
  8645. return isVersionSupported;
  8646. }
  8647. /**
  8648. Constructor for the Silverlight Runtime
  8649. */
  8650. function SilverlightRuntime(options) {
  8651. var I = this, initTimer;
  8652. options = Basic.extend({ xap_url: Env.xap_url }, options);
  8653. Runtime.call(this, options, type, {
  8654. access_binary: Runtime.capTrue,
  8655. access_image_binary: Runtime.capTrue,
  8656. display_media: Runtime.capTest(defined('moxie/image/Image')),
  8657. do_cors: Runtime.capTrue,
  8658. drag_and_drop: false,
  8659. report_upload_progress: Runtime.capTrue,
  8660. resize_image: Runtime.capTrue,
  8661. return_response_headers: function(value) {
  8662. return value && I.mode === 'client';
  8663. },
  8664. return_response_type: function(responseType) {
  8665. if (responseType !== 'json') {
  8666. return true;
  8667. } else {
  8668. return !!window.JSON;
  8669. }
  8670. },
  8671. return_status_code: function(code) {
  8672. return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]);
  8673. },
  8674. select_file: Runtime.capTrue,
  8675. select_multiple: Runtime.capTrue,
  8676. send_binary_string: Runtime.capTrue,
  8677. send_browser_cookies: function(value) {
  8678. return value && I.mode === 'browser';
  8679. },
  8680. send_custom_headers: function(value) {
  8681. return value && I.mode === 'client';
  8682. },
  8683. send_multipart: Runtime.capTrue,
  8684. slice_blob: Runtime.capTrue,
  8685. stream_upload: true,
  8686. summon_file_dialog: false,
  8687. upload_filesize: Runtime.capTrue,
  8688. use_http_method: function(methods) {
  8689. return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']);
  8690. }
  8691. }, {
  8692. // capabilities that require specific mode
  8693. return_response_headers: function(value) {
  8694. return value ? 'client' : 'browser';
  8695. },
  8696. return_status_code: function(code) {
  8697. return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser'];
  8698. },
  8699. send_browser_cookies: function(value) {
  8700. return value ? 'browser' : 'client';
  8701. },
  8702. send_custom_headers: function(value) {
  8703. return value ? 'client' : 'browser';
  8704. },
  8705. use_http_method: function(methods) {
  8706. return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser'];
  8707. }
  8708. });
  8709. // minimal requirement
  8710. if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') {
  8711. if (MXI_DEBUG && Env.debug.runtime) {
  8712. Env.log("\tSilverlight is not installed or minimal version (2.0.31005.0) requirement not met (not likely).");
  8713. }
  8714. this.mode = false;
  8715. }
  8716. Basic.extend(this, {
  8717. getShim: function() {
  8718. return Dom.get(this.uid).content.Moxie;
  8719. },
  8720. shimExec: function(component, action) {
  8721. var args = [].slice.call(arguments, 2);
  8722. return I.getShim().exec(this.uid, component, action, args);
  8723. },
  8724. init : function() {
  8725. var container;
  8726. container = this.getShimContainer();
  8727. container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' +
  8728. '<param name="source" value="' + options.xap_url + '"/>' +
  8729. '<param name="background" value="Transparent"/>' +
  8730. '<param name="windowless" value="true"/>' +
  8731. '<param name="enablehtmlaccess" value="true"/>' +
  8732. '<param name="initParams" value="uid=' + this.uid + ',target=' + Runtime.getGlobalEventTarget() + '"/>' +
  8733. '</object>';
  8734. // Init is dispatched by the shim
  8735. initTimer = setTimeout(function() {
  8736. if (I && !I.initialized) { // runtime might be already destroyed by this moment
  8737. I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
  8738. if (MXI_DEBUG && Env.debug.runtime) {
  8739. Env.log("\Silverlight failed to initialize within a specified period of time (5-10s).");
  8740. }
  8741. }
  8742. }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac)
  8743. },
  8744. destroy: (function(destroy) { // extend default destroy method
  8745. return function() {
  8746. destroy.call(I);
  8747. clearTimeout(initTimer); // initialization check might be still onwait
  8748. options = initTimer = destroy = I = null;
  8749. };
  8750. }(this.destroy))
  8751. }, extensions);
  8752. }
  8753. Runtime.addConstructor(type, SilverlightRuntime);
  8754. return extensions;
  8755. });
  8756. // Included from: src/javascript/runtime/silverlight/file/Blob.js
  8757. /**
  8758. * Blob.js
  8759. *
  8760. * Copyright 2013, Moxiecode Systems AB
  8761. * Released under GPL License.
  8762. *
  8763. * License: http://www.plupload.com/license
  8764. * Contributing: http://www.plupload.com/contributing
  8765. */
  8766. /**
  8767. @class moxie/runtime/silverlight/file/Blob
  8768. @private
  8769. */
  8770. define("moxie/runtime/silverlight/file/Blob", [
  8771. "moxie/runtime/silverlight/Runtime",
  8772. "moxie/core/utils/Basic",
  8773. "moxie/runtime/flash/file/Blob"
  8774. ], function(extensions, Basic, Blob) {
  8775. return (extensions.Blob = Basic.extend({}, Blob));
  8776. });
  8777. // Included from: src/javascript/runtime/silverlight/file/FileInput.js
  8778. /**
  8779. * FileInput.js
  8780. *
  8781. * Copyright 2013, Moxiecode Systems AB
  8782. * Released under GPL License.
  8783. *
  8784. * License: http://www.plupload.com/license
  8785. * Contributing: http://www.plupload.com/contributing
  8786. */
  8787. /**
  8788. @class moxie/runtime/silverlight/file/FileInput
  8789. @private
  8790. */
  8791. define("moxie/runtime/silverlight/file/FileInput", [
  8792. "moxie/runtime/silverlight/Runtime",
  8793. "moxie/file/File",
  8794. "moxie/core/utils/Dom",
  8795. "moxie/core/utils/Basic"
  8796. ], function(extensions, File, Dom, Basic) {
  8797. function toFilters(accept) {
  8798. var filter = '';
  8799. for (var i = 0; i < accept.length; i++) {
  8800. filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.');
  8801. }
  8802. return filter;
  8803. }
  8804. var FileInput = {
  8805. init: function(options) {
  8806. var comp = this, I = this.getRuntime();
  8807. var browseButton = Dom.get(options.browse_button);
  8808. if (browseButton) {
  8809. browseButton.setAttribute('tabindex', -1);
  8810. browseButton = null;
  8811. }
  8812. this.bind("Change", function() {
  8813. var files = I.shimExec.call(comp, 'FileInput', 'getFiles');
  8814. comp.files = [];
  8815. Basic.each(files, function(file) {
  8816. comp.files.push(new File(I.uid, file));
  8817. });
  8818. }, 999);
  8819. I.shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.multiple);
  8820. this.trigger('ready');
  8821. },
  8822. setOption: function(name, value) {
  8823. if (name == 'accept') {
  8824. value = toFilters(value);
  8825. }
  8826. this.getRuntime().shimExec.call(this, 'FileInput', 'setOption', name, value);
  8827. }
  8828. };
  8829. return (extensions.FileInput = FileInput);
  8830. });
  8831. // Included from: src/javascript/runtime/silverlight/file/FileDrop.js
  8832. /**
  8833. * FileDrop.js
  8834. *
  8835. * Copyright 2013, Moxiecode Systems AB
  8836. * Released under GPL License.
  8837. *
  8838. * License: http://www.plupload.com/license
  8839. * Contributing: http://www.plupload.com/contributing
  8840. */
  8841. /**
  8842. @class moxie/runtime/silverlight/file/FileDrop
  8843. @private
  8844. */
  8845. define("moxie/runtime/silverlight/file/FileDrop", [
  8846. "moxie/runtime/silverlight/Runtime",
  8847. "moxie/core/utils/Dom",
  8848. "moxie/core/utils/Events"
  8849. ], function(extensions, Dom, Events) {
  8850. // not exactly useful, since works only in safari (...crickets...)
  8851. var FileDrop = {
  8852. init: function() {
  8853. var comp = this, self = comp.getRuntime(), dropZone;
  8854. dropZone = self.getShimContainer();
  8855. Events.addEvent(dropZone, 'dragover', function(e) {
  8856. e.preventDefault();
  8857. e.stopPropagation();
  8858. e.dataTransfer.dropEffect = 'copy';
  8859. }, comp.uid);
  8860. Events.addEvent(dropZone, 'dragenter', function(e) {
  8861. e.preventDefault();
  8862. var flag = Dom.get(self.uid).dragEnter(e);
  8863. // If handled, then stop propagation of event in DOM
  8864. if (flag) {
  8865. e.stopPropagation();
  8866. }
  8867. }, comp.uid);
  8868. Events.addEvent(dropZone, 'drop', function(e) {
  8869. e.preventDefault();
  8870. var flag = Dom.get(self.uid).dragDrop(e);
  8871. // If handled, then stop propagation of event in DOM
  8872. if (flag) {
  8873. e.stopPropagation();
  8874. }
  8875. }, comp.uid);
  8876. return self.shimExec.call(this, 'FileDrop', 'init');
  8877. }
  8878. };
  8879. return (extensions.FileDrop = FileDrop);
  8880. });
  8881. // Included from: src/javascript/runtime/silverlight/file/FileReader.js
  8882. /**
  8883. * FileReader.js
  8884. *
  8885. * Copyright 2013, Moxiecode Systems AB
  8886. * Released under GPL License.
  8887. *
  8888. * License: http://www.plupload.com/license
  8889. * Contributing: http://www.plupload.com/contributing
  8890. */
  8891. /**
  8892. @class moxie/runtime/silverlight/file/FileReader
  8893. @private
  8894. */
  8895. define("moxie/runtime/silverlight/file/FileReader", [
  8896. "moxie/runtime/silverlight/Runtime",
  8897. "moxie/core/utils/Basic",
  8898. "moxie/runtime/flash/file/FileReader"
  8899. ], function(extensions, Basic, FileReader) {
  8900. return (extensions.FileReader = Basic.extend({}, FileReader));
  8901. });
  8902. // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js
  8903. /**
  8904. * FileReaderSync.js
  8905. *
  8906. * Copyright 2013, Moxiecode Systems AB
  8907. * Released under GPL License.
  8908. *
  8909. * License: http://www.plupload.com/license
  8910. * Contributing: http://www.plupload.com/contributing
  8911. */
  8912. /**
  8913. @class moxie/runtime/silverlight/file/FileReaderSync
  8914. @private
  8915. */
  8916. define("moxie/runtime/silverlight/file/FileReaderSync", [
  8917. "moxie/runtime/silverlight/Runtime",
  8918. "moxie/core/utils/Basic",
  8919. "moxie/runtime/flash/file/FileReaderSync"
  8920. ], function(extensions, Basic, FileReaderSync) {
  8921. return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync));
  8922. });
  8923. // Included from: src/javascript/runtime/silverlight/runtime/Transporter.js
  8924. /**
  8925. * Transporter.js
  8926. *
  8927. * Copyright 2013, Moxiecode Systems AB
  8928. * Released under GPL License.
  8929. *
  8930. * License: http://www.plupload.com/license
  8931. * Contributing: http://www.plupload.com/contributing
  8932. */
  8933. /**
  8934. @class moxie/runtime/silverlight/runtime/Transporter
  8935. @private
  8936. */
  8937. define("moxie/runtime/silverlight/runtime/Transporter", [
  8938. "moxie/runtime/silverlight/Runtime",
  8939. "moxie/core/utils/Basic",
  8940. "moxie/runtime/flash/runtime/Transporter"
  8941. ], function(extensions, Basic, Transporter) {
  8942. return (extensions.Transporter = Basic.extend({}, Transporter));
  8943. });
  8944. // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js
  8945. /**
  8946. * XMLHttpRequest.js
  8947. *
  8948. * Copyright 2013, Moxiecode Systems AB
  8949. * Released under GPL License.
  8950. *
  8951. * License: http://www.plupload.com/license
  8952. * Contributing: http://www.plupload.com/contributing
  8953. */
  8954. /**
  8955. @class moxie/runtime/silverlight/xhr/XMLHttpRequest
  8956. @private
  8957. */
  8958. define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [
  8959. "moxie/runtime/silverlight/Runtime",
  8960. "moxie/core/utils/Basic",
  8961. "moxie/runtime/flash/xhr/XMLHttpRequest",
  8962. "moxie/runtime/silverlight/file/FileReaderSync",
  8963. "moxie/runtime/silverlight/runtime/Transporter"
  8964. ], function(extensions, Basic, XMLHttpRequest, FileReaderSyncSilverlight, TransporterSilverlight) {
  8965. return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest));
  8966. });
  8967. // Included from: src/javascript/runtime/silverlight/image/Image.js
  8968. /**
  8969. * Image.js
  8970. *
  8971. * Copyright 2013, Moxiecode Systems AB
  8972. * Released under GPL License.
  8973. *
  8974. * License: http://www.plupload.com/license
  8975. * Contributing: http://www.plupload.com/contributing
  8976. */
  8977. /**
  8978. @class moxie/runtime/silverlight/image/Image
  8979. @private
  8980. */
  8981. define("moxie/runtime/silverlight/image/Image", [
  8982. "moxie/runtime/silverlight/Runtime",
  8983. "moxie/core/utils/Basic",
  8984. "moxie/file/Blob",
  8985. "moxie/runtime/flash/image/Image"
  8986. ], function(extensions, Basic, Blob, Image) {
  8987. return (extensions.Image = Basic.extend({}, Image, {
  8988. getInfo: function() {
  8989. var self = this.getRuntime()
  8990. , grps = ['tiff', 'exif', 'gps', 'thumb']
  8991. , info = { meta: {} }
  8992. , rawInfo = self.shimExec.call(this, 'Image', 'getInfo')
  8993. ;
  8994. if (rawInfo.meta) {
  8995. Basic.each(grps, function(grp) {
  8996. var meta = rawInfo.meta[grp]
  8997. , tag
  8998. , i
  8999. , length
  9000. , value
  9001. ;
  9002. if (meta && meta.keys) {
  9003. info.meta[grp] = {};
  9004. for (i = 0, length = meta.keys.length; i < length; i++) {
  9005. tag = meta.keys[i];
  9006. value = meta[tag];
  9007. if (value) {
  9008. // convert numbers
  9009. if (/^(\d|[1-9]\d+)$/.test(value)) { // integer (make sure doesn't start with zero)
  9010. value = parseInt(value, 10);
  9011. } else if (/^\d*\.\d+$/.test(value)) { // double
  9012. value = parseFloat(value);
  9013. }
  9014. info.meta[grp][tag] = value;
  9015. }
  9016. }
  9017. }
  9018. });
  9019. // save thumb data as blob
  9020. if (info.meta && info.meta.thumb && info.meta.thumb.data && !(self.meta.thumb.data instanceof Blob)) {
  9021. info.meta.thumb.data = new Blob(self.uid, info.meta.thumb.data);
  9022. }
  9023. }
  9024. info.width = parseInt(rawInfo.width, 10);
  9025. info.height = parseInt(rawInfo.height, 10);
  9026. info.size = parseInt(rawInfo.size, 10);
  9027. info.type = rawInfo.type;
  9028. info.name = rawInfo.name;
  9029. return info;
  9030. },
  9031. resize: function(rect, ratio, opts) {
  9032. this.getRuntime().shimExec.call(this, 'Image', 'resize', rect.x, rect.y, rect.width, rect.height, ratio, opts.preserveHeaders, opts.resample);
  9033. }
  9034. }));
  9035. });
  9036. // Included from: src/javascript/runtime/html4/Runtime.js
  9037. /**
  9038. * Runtime.js
  9039. *
  9040. * Copyright 2013, Moxiecode Systems AB
  9041. * Released under GPL License.
  9042. *
  9043. * License: http://www.plupload.com/license
  9044. * Contributing: http://www.plupload.com/contributing
  9045. */
  9046. /*global File:true */
  9047. /**
  9048. Defines constructor for HTML4 runtime.
  9049. @class moxie/runtime/html4/Runtime
  9050. @private
  9051. */
  9052. define("moxie/runtime/html4/Runtime", [
  9053. "moxie/core/utils/Basic",
  9054. "moxie/core/Exceptions",
  9055. "moxie/runtime/Runtime",
  9056. "moxie/core/utils/Env"
  9057. ], function(Basic, x, Runtime, Env) {
  9058. var type = 'html4', extensions = {};
  9059. function Html4Runtime(options) {
  9060. var I = this
  9061. , Test = Runtime.capTest
  9062. , True = Runtime.capTrue
  9063. ;
  9064. Runtime.call(this, options, type, {
  9065. access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
  9066. access_image_binary: false,
  9067. display_media: Test(
  9068. (Env.can('create_canvas') || Env.can('use_data_uri_over32kb')) &&
  9069. defined('moxie/image/Image')
  9070. ),
  9071. do_cors: false,
  9072. drag_and_drop: false,
  9073. filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
  9074. return !(
  9075. (Env.browser === 'Chrome' && Env.verComp(Env.version, 28, '<')) ||
  9076. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) ||
  9077. (Env.browser === 'Safari' && Env.verComp(Env.version, 7, '<')) ||
  9078. (Env.browser === 'Firefox' && Env.verComp(Env.version, 37, '<'))
  9079. );
  9080. }()),
  9081. resize_image: function() {
  9082. return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
  9083. },
  9084. report_upload_progress: false,
  9085. return_response_headers: false,
  9086. return_response_type: function(responseType) {
  9087. if (responseType === 'json' && !!window.JSON) {
  9088. return true;
  9089. }
  9090. return !!~Basic.inArray(responseType, ['text', 'document', '']);
  9091. },
  9092. return_status_code: function(code) {
  9093. return !Basic.arrayDiff(code, [200, 404]);
  9094. },
  9095. select_file: function() {
  9096. return Env.can('use_fileinput');
  9097. },
  9098. select_multiple: false,
  9099. send_binary_string: false,
  9100. send_custom_headers: false,
  9101. send_multipart: true,
  9102. slice_blob: false,
  9103. stream_upload: function() {
  9104. return I.can('select_file');
  9105. },
  9106. summon_file_dialog: function() { // yeah... some dirty sniffing here...
  9107. return I.can('select_file') && !(
  9108. (Env.browser === 'Firefox' && Env.verComp(Env.version, 4, '<')) ||
  9109. (Env.browser === 'Opera' && Env.verComp(Env.version, 12, '<')) ||
  9110. (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<'))
  9111. );
  9112. },
  9113. upload_filesize: True,
  9114. use_http_method: function(methods) {
  9115. return !Basic.arrayDiff(methods, ['GET', 'POST']);
  9116. }
  9117. });
  9118. Basic.extend(this, {
  9119. init : function() {
  9120. this.trigger("Init");
  9121. },
  9122. destroy: (function(destroy) { // extend default destroy method
  9123. return function() {
  9124. destroy.call(I);
  9125. destroy = I = null;
  9126. };
  9127. }(this.destroy))
  9128. });
  9129. Basic.extend(this.getShim(), extensions);
  9130. }
  9131. Runtime.addConstructor(type, Html4Runtime);
  9132. return extensions;
  9133. });
  9134. // Included from: src/javascript/runtime/html4/file/FileInput.js
  9135. /**
  9136. * FileInput.js
  9137. *
  9138. * Copyright 2013, Moxiecode Systems AB
  9139. * Released under GPL License.
  9140. *
  9141. * License: http://www.plupload.com/license
  9142. * Contributing: http://www.plupload.com/contributing
  9143. */
  9144. /**
  9145. @class moxie/runtime/html4/file/FileInput
  9146. @private
  9147. */
  9148. define("moxie/runtime/html4/file/FileInput", [
  9149. "moxie/runtime/html4/Runtime",
  9150. "moxie/file/File",
  9151. "moxie/core/utils/Basic",
  9152. "moxie/core/utils/Dom",
  9153. "moxie/core/utils/Events",
  9154. "moxie/core/utils/Mime",
  9155. "moxie/core/utils/Env"
  9156. ], function(extensions, File, Basic, Dom, Events, Mime, Env) {
  9157. function FileInput() {
  9158. var _uid, _mimes = [], _options, _browseBtnZIndex; // save original z-index;
  9159. function addInput() {
  9160. var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;
  9161. uid = Basic.guid('uid_');
  9162. shimContainer = I.getShimContainer(); // we get new ref every time to avoid memory leaks in IE
  9163. if (_uid) { // move previous form out of the view
  9164. currForm = Dom.get(_uid + '_form');
  9165. if (currForm) {
  9166. Basic.extend(currForm.style, { top: '100%' });
  9167. // it shouldn't be possible to tab into the hidden element
  9168. currForm.firstChild.setAttribute('tabindex', -1);
  9169. }
  9170. }
  9171. // build form in DOM, since innerHTML version not able to submit file for some reason
  9172. form = document.createElement('form');
  9173. form.setAttribute('id', uid + '_form');
  9174. form.setAttribute('method', 'post');
  9175. form.setAttribute('enctype', 'multipart/form-data');
  9176. form.setAttribute('encoding', 'multipart/form-data');
  9177. Basic.extend(form.style, {
  9178. overflow: 'hidden',
  9179. position: 'absolute',
  9180. top: 0,
  9181. left: 0,
  9182. width: '100%',
  9183. height: '100%'
  9184. });
  9185. input = document.createElement('input');
  9186. input.setAttribute('id', uid);
  9187. input.setAttribute('type', 'file');
  9188. input.setAttribute('accept', _mimes.join(','));
  9189. if (I.can('summon_file_dialog')) {
  9190. input.setAttribute('tabindex', -1);
  9191. }
  9192. Basic.extend(input.style, {
  9193. fontSize: '999px',
  9194. opacity: 0
  9195. });
  9196. form.appendChild(input);
  9197. shimContainer.appendChild(form);
  9198. // prepare file input to be placed underneath the browse_button element
  9199. Basic.extend(input.style, {
  9200. position: 'absolute',
  9201. top: 0,
  9202. left: 0,
  9203. width: '100%',
  9204. height: '100%'
  9205. });
  9206. if (Env.browser === 'IE' && Env.verComp(Env.version, 10, '<')) {
  9207. Basic.extend(input.style, {
  9208. filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
  9209. });
  9210. }
  9211. input.onchange = function() { // there should be only one handler for this
  9212. var file;
  9213. if (!this.value) {
  9214. return;
  9215. }
  9216. if (this.files) { // check if browser is fresh enough
  9217. file = this.files[0];
  9218. } else {
  9219. file = {
  9220. name: this.value
  9221. };
  9222. }
  9223. file = new File(I.uid, file);
  9224. // clear event handler
  9225. this.onchange = function() {};
  9226. addInput.call(comp);
  9227. comp.files = [file];
  9228. // substitute all ids with file uids (consider file.uid read-only - we cannot do it the other way around)
  9229. input.setAttribute('id', file.uid);
  9230. form.setAttribute('id', file.uid + '_form');
  9231. comp.trigger('change');
  9232. input = form = null;
  9233. };
  9234. // route click event to the input
  9235. if (I.can('summon_file_dialog')) {
  9236. browseButton = Dom.get(_options.browse_button);
  9237. Events.removeEvent(browseButton, 'click', comp.uid);
  9238. Events.addEvent(browseButton, 'click', function(e) {
  9239. if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
  9240. input.click();
  9241. }
  9242. e.preventDefault();
  9243. }, comp.uid);
  9244. }
  9245. _uid = uid;
  9246. shimContainer = currForm = browseButton = null;
  9247. }
  9248. Basic.extend(this, {
  9249. init: function(options) {
  9250. var comp = this, I = comp.getRuntime(), shimContainer;
  9251. // figure out accept string
  9252. _options = options;
  9253. _mimes = Mime.extList2mimes(options.accept, I.can('filter_by_extension'));
  9254. shimContainer = I.getShimContainer();
  9255. (function() {
  9256. var browseButton, zIndex, top;
  9257. browseButton = Dom.get(options.browse_button);
  9258. _browseBtnZIndex = Dom.getStyle(browseButton, 'z-index') || 'auto';
  9259. // Route click event to the input[type=file] element for browsers that support such behavior
  9260. if (I.can('summon_file_dialog')) {
  9261. if (Dom.getStyle(browseButton, 'position') === 'static') {
  9262. browseButton.style.position = 'relative';
  9263. }
  9264. comp.bind('Refresh', function() {
  9265. zIndex = parseInt(_browseBtnZIndex, 10) || 1;
  9266. Dom.get(_options.browse_button).style.zIndex = zIndex;
  9267. this.getRuntime().getShimContainer().style.zIndex = zIndex - 1;
  9268. });
  9269. } else {
  9270. // it shouldn't be possible to tab into the hidden element
  9271. browseButton.setAttribute('tabindex', -1);
  9272. }
  9273. /* Since we have to place input[type=file] on top of the browse_button for some browsers,
  9274. browse_button loses interactivity, so we restore it here */
  9275. top = I.can('summon_file_dialog') ? browseButton : shimContainer;
  9276. Events.addEvent(top, 'mouseover', function() {
  9277. comp.trigger('mouseenter');
  9278. }, comp.uid);
  9279. Events.addEvent(top, 'mouseout', function() {
  9280. comp.trigger('mouseleave');
  9281. }, comp.uid);
  9282. Events.addEvent(top, 'mousedown', function() {
  9283. comp.trigger('mousedown');
  9284. }, comp.uid);
  9285. Events.addEvent(Dom.get(options.container), 'mouseup', function() {
  9286. comp.trigger('mouseup');
  9287. }, comp.uid);
  9288. browseButton = null;
  9289. }());
  9290. addInput.call(this);
  9291. shimContainer = null;
  9292. // trigger ready event asynchronously
  9293. comp.trigger({
  9294. type: 'ready',
  9295. async: true
  9296. });
  9297. },
  9298. setOption: function(name, value) {
  9299. var I = this.getRuntime();
  9300. var input;
  9301. if (name == 'accept') {
  9302. _mimes = value.mimes || Mime.extList2mimes(value, I.can('filter_by_extension'));
  9303. }
  9304. // update current input
  9305. input = Dom.get(_uid)
  9306. if (input) {
  9307. input.setAttribute('accept', _mimes.join(','));
  9308. }
  9309. },
  9310. disable: function(state) {
  9311. var input;
  9312. if ((input = Dom.get(_uid))) {
  9313. input.disabled = !!state;
  9314. }
  9315. },
  9316. destroy: function() {
  9317. var I = this.getRuntime()
  9318. , shim = I.getShim()
  9319. , shimContainer = I.getShimContainer()
  9320. , container = _options && Dom.get(_options.container)
  9321. , browseButton = _options && Dom.get(_options.browse_button)
  9322. ;
  9323. if (container) {
  9324. Events.removeAllEvents(container, this.uid);
  9325. }
  9326. if (browseButton) {
  9327. Events.removeAllEvents(browseButton, this.uid);
  9328. browseButton.style.zIndex = _browseBtnZIndex; // reset to original value
  9329. }
  9330. if (shimContainer) {
  9331. Events.removeAllEvents(shimContainer, this.uid);
  9332. shimContainer.innerHTML = '';
  9333. }
  9334. shim.removeInstance(this.uid);
  9335. _uid = _mimes = _options = shimContainer = container = browseButton = shim = null;
  9336. }
  9337. });
  9338. }
  9339. return (extensions.FileInput = FileInput);
  9340. });
  9341. // Included from: src/javascript/runtime/html4/file/FileReader.js
  9342. /**
  9343. * FileReader.js
  9344. *
  9345. * Copyright 2013, Moxiecode Systems AB
  9346. * Released under GPL License.
  9347. *
  9348. * License: http://www.plupload.com/license
  9349. * Contributing: http://www.plupload.com/contributing
  9350. */
  9351. /**
  9352. @class moxie/runtime/html4/file/FileReader
  9353. @private
  9354. */
  9355. define("moxie/runtime/html4/file/FileReader", [
  9356. "moxie/runtime/html4/Runtime",
  9357. "moxie/runtime/html5/file/FileReader"
  9358. ], function(extensions, FileReader) {
  9359. return (extensions.FileReader = FileReader);
  9360. });
  9361. // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js
  9362. /**
  9363. * XMLHttpRequest.js
  9364. *
  9365. * Copyright 2013, Moxiecode Systems AB
  9366. * Released under GPL License.
  9367. *
  9368. * License: http://www.plupload.com/license
  9369. * Contributing: http://www.plupload.com/contributing
  9370. */
  9371. /**
  9372. @class moxie/runtime/html4/xhr/XMLHttpRequest
  9373. @private
  9374. */
  9375. define("moxie/runtime/html4/xhr/XMLHttpRequest", [
  9376. "moxie/runtime/html4/Runtime",
  9377. "moxie/core/utils/Basic",
  9378. "moxie/core/utils/Dom",
  9379. "moxie/core/utils/Url",
  9380. "moxie/core/Exceptions",
  9381. "moxie/core/utils/Events",
  9382. "moxie/file/Blob",
  9383. "moxie/xhr/FormData"
  9384. ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
  9385. function XMLHttpRequest() {
  9386. var _status, _response, _iframe;
  9387. function cleanup(cb) {
  9388. var target = this, uid, form, inputs, i, hasFile = false;
  9389. if (!_iframe) {
  9390. return;
  9391. }
  9392. uid = _iframe.id.replace(/_iframe$/, '');
  9393. form = Dom.get(uid + '_form');
  9394. if (form) {
  9395. inputs = form.getElementsByTagName('input');
  9396. i = inputs.length;
  9397. while (i--) {
  9398. switch (inputs[i].getAttribute('type')) {
  9399. case 'hidden':
  9400. inputs[i].parentNode.removeChild(inputs[i]);
  9401. break;
  9402. case 'file':
  9403. hasFile = true; // flag the case for later
  9404. break;
  9405. }
  9406. }
  9407. inputs = [];
  9408. if (!hasFile) { // we need to keep the form for sake of possible retries
  9409. form.parentNode.removeChild(form);
  9410. }
  9411. form = null;
  9412. }
  9413. // without timeout, request is marked as canceled (in console)
  9414. setTimeout(function() {
  9415. Events.removeEvent(_iframe, 'load', target.uid);
  9416. if (_iframe.parentNode) { // #382
  9417. _iframe.parentNode.removeChild(_iframe);
  9418. }
  9419. // check if shim container has any other children, if - not, remove it as well
  9420. var shimContainer = target.getRuntime().getShimContainer();
  9421. if (!shimContainer.children.length) {
  9422. shimContainer.parentNode.removeChild(shimContainer);
  9423. }
  9424. shimContainer = _iframe = null;
  9425. cb();
  9426. }, 1);
  9427. }
  9428. Basic.extend(this, {
  9429. send: function(meta, data) {
  9430. var target = this, I = target.getRuntime(), uid, form, input, blob;
  9431. _status = _response = null;
  9432. function createIframe() {
  9433. var container = I.getShimContainer() || document.body
  9434. , temp = document.createElement('div')
  9435. ;
  9436. // IE 6 won't be able to set the name using setAttribute or iframe.name
  9437. temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>';
  9438. _iframe = temp.firstChild;
  9439. container.appendChild(_iframe);
  9440. /* _iframe.onreadystatechange = function() {
  9441. console.info(_iframe.readyState);
  9442. };*/
  9443. Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
  9444. var el;
  9445. try {
  9446. el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
  9447. // try to detect some standard error pages
  9448. if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
  9449. _status = el.title.replace(/^(\d+).*$/, '$1');
  9450. } else {
  9451. _status = 200;
  9452. // get result
  9453. _response = Basic.trim(el.body.innerHTML);
  9454. // we need to fire these at least once
  9455. target.trigger({
  9456. type: 'progress',
  9457. loaded: _response.length,
  9458. total: _response.length
  9459. });
  9460. if (blob) { // if we were uploading a file
  9461. target.trigger({
  9462. type: 'uploadprogress',
  9463. loaded: blob.size || 1025,
  9464. total: blob.size || 1025
  9465. });
  9466. }
  9467. }
  9468. } catch (ex) {
  9469. if (Url.hasSameOrigin(meta.url)) {
  9470. // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
  9471. // which obviously results to cross domain error (wtf?)
  9472. _status = 404;
  9473. } else {
  9474. cleanup.call(target, function() {
  9475. target.trigger('error');
  9476. });
  9477. return;
  9478. }
  9479. }
  9480. cleanup.call(target, function() {
  9481. target.trigger('load');
  9482. });
  9483. }, target.uid);
  9484. } // end createIframe
  9485. // prepare data to be sent and convert if required
  9486. if (data instanceof FormData && data.hasBlob()) {
  9487. blob = data.getBlob();
  9488. uid = blob.uid;
  9489. input = Dom.get(uid);
  9490. form = Dom.get(uid + '_form');
  9491. if (!form) {
  9492. throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
  9493. }
  9494. } else {
  9495. uid = Basic.guid('uid_');
  9496. form = document.createElement('form');
  9497. form.setAttribute('id', uid + '_form');
  9498. form.setAttribute('method', meta.method);
  9499. form.setAttribute('enctype', 'multipart/form-data');
  9500. form.setAttribute('encoding', 'multipart/form-data');
  9501. I.getShimContainer().appendChild(form);
  9502. }
  9503. // set upload target
  9504. form.setAttribute('target', uid + '_iframe');
  9505. if (data instanceof FormData) {
  9506. data.each(function(value, name) {
  9507. if (value instanceof Blob) {
  9508. if (input) {
  9509. input.setAttribute('name', name);
  9510. }
  9511. } else {
  9512. var hidden = document.createElement('input');
  9513. Basic.extend(hidden, {
  9514. type : 'hidden',
  9515. name : name,
  9516. value : value
  9517. });
  9518. // make sure that input[type="file"], if it's there, comes last
  9519. if (input) {
  9520. form.insertBefore(hidden, input);
  9521. } else {
  9522. form.appendChild(hidden);
  9523. }
  9524. }
  9525. });
  9526. }
  9527. // set destination url
  9528. form.setAttribute("action", meta.url);
  9529. createIframe();
  9530. form.submit();
  9531. target.trigger('loadstart');
  9532. },
  9533. getStatus: function() {
  9534. return _status;
  9535. },
  9536. getResponse: function(responseType) {
  9537. if ('json' === responseType) {
  9538. // strip off <pre>..</pre> tags that might be enclosing the response
  9539. if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
  9540. try {
  9541. return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
  9542. } catch (ex) {
  9543. return null;
  9544. }
  9545. }
  9546. } else if ('document' === responseType) {
  9547. }
  9548. return _response;
  9549. },
  9550. abort: function() {
  9551. var target = this;
  9552. if (_iframe && _iframe.contentWindow) {
  9553. if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
  9554. _iframe.contentWindow.stop();
  9555. } else if (_iframe.contentWindow.document.execCommand) { // IE
  9556. _iframe.contentWindow.document.execCommand('Stop');
  9557. } else {
  9558. _iframe.src = "about:blank";
  9559. }
  9560. }
  9561. cleanup.call(this, function() {
  9562. // target.dispatchEvent('readystatechange');
  9563. target.dispatchEvent('abort');
  9564. });
  9565. },
  9566. destroy: function() {
  9567. this.getRuntime().getShim().removeInstance(this.uid);
  9568. }
  9569. });
  9570. }
  9571. return (extensions.XMLHttpRequest = XMLHttpRequest);
  9572. });
  9573. // Included from: src/javascript/runtime/html4/image/Image.js
  9574. /**
  9575. * Image.js
  9576. *
  9577. * Copyright 2013, Moxiecode Systems AB
  9578. * Released under GPL License.
  9579. *
  9580. * License: http://www.plupload.com/license
  9581. * Contributing: http://www.plupload.com/contributing
  9582. */
  9583. /**
  9584. @class moxie/runtime/html4/image/Image
  9585. @private
  9586. */
  9587. define("moxie/runtime/html4/image/Image", [
  9588. "moxie/runtime/html4/Runtime",
  9589. "moxie/runtime/html5/image/Image"
  9590. ], function(extensions, Image) {
  9591. return (extensions.Image = Image);
  9592. });
  9593. expose(["moxie/core/utils/Basic","moxie/core/utils/Encode","moxie/core/utils/Env","moxie/core/Exceptions","moxie/core/utils/Dom","moxie/core/EventTarget","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/core/I18n","moxie/core/utils/Mime","moxie/file/FileInput","moxie/file/File","moxie/file/FileDrop","moxie/file/FileReader","moxie/core/utils/Url","moxie/runtime/RuntimeTarget","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/image/Image","moxie/core/utils/Events","moxie/runtime/html5/image/ResizerCanvas"]);
  9594. })(this);
  9595. }));