URI.as 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466
  1. /*
  2. Copyright (c) 2008, Adobe Systems Incorporated
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are
  6. met:
  7. * Redistributions of source code must retain the above copyright notice,
  8. this list of conditions and the following disclaimer.
  9. * Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. * Neither the name of Adobe Systems Incorporated nor the names of its
  13. contributors may be used to endorse or promote products derived from
  14. this software without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  16. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  17. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  18. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  19. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  20. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  23. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  24. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package com.adobe.net
  28. {
  29. import flash.utils.ByteArray;
  30. /**
  31. * This class implements functions and utilities for working with URI's
  32. * (Universal Resource Identifiers). For technical description of the
  33. * URI syntax, please see RFC 3986 at http://www.ietf.org/rfc/rfc3986.txt
  34. * or do a web search for "rfc 3986".
  35. *
  36. * <p>The most important aspect of URI's to understand is that URI's
  37. * and URL's are not strings. URI's are complex data structures that
  38. * encapsulate many pieces of information. The string version of a
  39. * URI is the serialized representation of that data structure. This
  40. * string serialization is used to provide a human readable
  41. * representation and a means to transport the data over the network
  42. * where it can then be parsed back into its' component parts.</p>
  43. *
  44. * <p>URI's fall into one of three categories:
  45. * <ul>
  46. * <li>&lt;scheme&gt;:&lt;scheme-specific-part&gt;#&lt;fragment&gt; (non-hierarchical)</li>
  47. * <li>&lt;scheme&gt;:<authority&gt;&lt;path&gt;?&lt;query&gt;#&lt;fragment&gt; (hierarchical)</li>
  48. * <li>&lt;path&gt;?&lt;query&gt;#&lt;fragment&gt; (relative hierarchical)</li>
  49. * </ul></p>
  50. *
  51. * <p>The query and fragment parts are optional.</p>
  52. *
  53. * <p>This class supports both non-hierarchical and hierarchical URI's</p>
  54. *
  55. * <p>This class is intended to be used "as-is" for the vast majority
  56. * of common URI's. However, if your application requires a custom
  57. * URI syntax (e.g. custom query syntax or special handling of
  58. * non-hierarchical URI's), this class can be fully subclassed. If you
  59. * intended to subclass URI, please see the source code for complete
  60. * documentation on protected members and protected functions.</p>
  61. *
  62. * @langversion ActionScript 3.0
  63. * @playerversion Flash 9.0
  64. */
  65. public class URI
  66. {
  67. // Here we define which characters must be escaped for each
  68. // URI part. The characters that must be escaped for each
  69. // part differ depending on what would cause ambiguous parsing.
  70. // RFC 3986 sec. 2.4 states that characters should only be
  71. // encoded when they would conflict with subcomponent delimiters.
  72. // We don't want to over-do the escaping. We only want to escape
  73. // the minimum needed to prevent parsing problems.
  74. // space and % must be escaped in all cases. '%' is the delimiter
  75. // for escaped characters.
  76. public static const URImustEscape:String = " %";
  77. // Baseline of what characters must be escaped
  78. public static const URIbaselineEscape:String = URImustEscape + ":?#/@";
  79. // Characters that must be escaped in the part part.
  80. public static const URIpathEscape:String = URImustEscape + "?#";
  81. // Characters that must be escaped in the query part, if setting
  82. // the query as a whole string. If the query is set by
  83. // name/value, URIqueryPartEscape is used instead.
  84. public static const URIqueryEscape:String = URImustEscape + "#";
  85. // This is what each name/value pair must escape "&=" as well
  86. // so they don't conflict with the "param=value&param2=value2"
  87. // syntax.
  88. public static const URIqueryPartEscape:String = URImustEscape + "#&=";
  89. // Non-hierarchical URI's can have query and fragment parts, but
  90. // we also want to prevent '/' otherwise it might end up looking
  91. // like a hierarchical URI to the parser.
  92. public static const URInonHierEscape:String = URImustEscape + "?#/";
  93. // Baseline uninitialized setting for the URI scheme.
  94. public static const UNKNOWN_SCHEME:String = "unknown";
  95. // The following bitmaps are used for performance enhanced
  96. // character escaping.
  97. // Baseline characters that need to be escaped. Many parts use
  98. // this.
  99. protected static const URIbaselineExcludedBitmap:URIEncodingBitmap =
  100. new URIEncodingBitmap(URIbaselineEscape);
  101. // Scheme escaping bitmap
  102. protected static const URIschemeExcludedBitmap:URIEncodingBitmap =
  103. URIbaselineExcludedBitmap;
  104. // User/pass escaping bitmap
  105. protected static const URIuserpassExcludedBitmap:URIEncodingBitmap =
  106. URIbaselineExcludedBitmap;
  107. // Authority escaping bitmap
  108. protected static const URIauthorityExcludedBitmap:URIEncodingBitmap =
  109. URIbaselineExcludedBitmap;
  110. // Port escaping bitmap
  111. protected static const URIportExludedBitmap:URIEncodingBitmap =
  112. URIbaselineExcludedBitmap;
  113. // Path escaping bitmap
  114. protected static const URIpathExcludedBitmap:URIEncodingBitmap =
  115. new URIEncodingBitmap(URIpathEscape);
  116. // Query (whole) escaping bitmap
  117. protected static const URIqueryExcludedBitmap:URIEncodingBitmap =
  118. new URIEncodingBitmap(URIqueryEscape);
  119. // Query (individual parts) escaping bitmap
  120. protected static const URIqueryPartExcludedBitmap:URIEncodingBitmap =
  121. new URIEncodingBitmap(URIqueryPartEscape);
  122. // Fragments are the last part in the URI. They only need to
  123. // escape space, '#', and '%'. Turns out that is what query
  124. // uses too.
  125. protected static const URIfragmentExcludedBitmap:URIEncodingBitmap =
  126. URIqueryExcludedBitmap;
  127. // Characters that need to be escaped in the non-hierarchical part
  128. protected static const URInonHierexcludedBitmap:URIEncodingBitmap =
  129. new URIEncodingBitmap(URInonHierEscape);
  130. // Values used by getRelation()
  131. public static const NOT_RELATED:int = 0;
  132. public static const CHILD:int = 1;
  133. public static const EQUAL:int = 2;
  134. public static const PARENT:int = 3;
  135. //-------------------------------------------------------------------
  136. // protected class members
  137. //-------------------------------------------------------------------
  138. protected var _valid:Boolean = false;
  139. protected var _relative:Boolean = false;
  140. protected var _scheme:String = "";
  141. protected var _authority:String = "";
  142. protected var _username:String = "";
  143. protected var _password:String = "";
  144. protected var _port:String = "";
  145. protected var _path:String = "";
  146. protected var _query:String = "";
  147. protected var _fragment:String = "";
  148. protected var _nonHierarchical:String = "";
  149. protected static var _resolver:IURIResolver = null;
  150. /**
  151. * URI Constructor. If no string is given, this will initialize
  152. * this URI object to a blank URI.
  153. */
  154. public function URI(uri:String = null) : void
  155. {
  156. if (uri == null)
  157. initialize();
  158. else
  159. constructURI(uri);
  160. }
  161. /**
  162. * @private
  163. * Method that loads the URI from the given string.
  164. */
  165. protected function constructURI(uri:String) : Boolean
  166. {
  167. if (!parseURI(uri))
  168. _valid = false;
  169. return isValid();
  170. }
  171. /**
  172. * @private Private initialization.
  173. */
  174. protected function initialize() : void
  175. {
  176. _valid = false;
  177. _relative = false;
  178. _scheme = UNKNOWN_SCHEME;
  179. _authority = "";
  180. _username = "";
  181. _password = "";
  182. _port = "";
  183. _path = "";
  184. _query = "";
  185. _fragment = "";
  186. _nonHierarchical = "";
  187. }
  188. /**
  189. * @private Accessor to explicitly set/get the hierarchical
  190. * state of the URI.
  191. */
  192. protected function set hierState(state:Boolean) : void
  193. {
  194. if (state)
  195. {
  196. // Clear the non-hierarchical data
  197. _nonHierarchical = "";
  198. // Also set the state vars while we are at it
  199. if (_scheme == "" || _scheme == UNKNOWN_SCHEME)
  200. _relative = true;
  201. else
  202. _relative = false;
  203. if (_authority.length == 0 && _path.length == 0)
  204. _valid = false;
  205. else
  206. _valid = true;
  207. }
  208. else
  209. {
  210. // Clear the hierarchical data
  211. _authority = "";
  212. _username = "";
  213. _password = "";
  214. _port = "";
  215. _path = "";
  216. _relative = false;
  217. if (_scheme == "" || _scheme == UNKNOWN_SCHEME)
  218. _valid = false;
  219. else
  220. _valid = true;
  221. }
  222. }
  223. protected function get hierState() : Boolean
  224. {
  225. return (_nonHierarchical.length == 0);
  226. }
  227. /**
  228. * @private Functions that performs some basic consistency validation.
  229. */
  230. protected function validateURI() : Boolean
  231. {
  232. // Check the scheme
  233. if (isAbsolute())
  234. {
  235. if (_scheme.length <= 1 || _scheme == UNKNOWN_SCHEME)
  236. {
  237. // we probably parsed a C:\ type path or no scheme
  238. return false;
  239. }
  240. else if (verifyAlpha(_scheme) == false)
  241. return false; // Scheme contains bad characters
  242. }
  243. if (hierState)
  244. {
  245. if (_path.search('\\') != -1)
  246. return false; // local path
  247. else if (isRelative() == false && _scheme == UNKNOWN_SCHEME)
  248. return false; // It's an absolute URI, but it has a bad scheme
  249. }
  250. else
  251. {
  252. if (_nonHierarchical.search('\\') != -1)
  253. return false; // some kind of local path
  254. }
  255. // Looks like it's ok.
  256. return true;
  257. }
  258. /**
  259. * @private
  260. *
  261. * Given a URI in string format, parse that sucker into its basic
  262. * components and assign them to this object. A URI is of the form:
  263. * <scheme>:<authority><path>?<query>#<fragment>
  264. *
  265. * For simplicity, we parse the URI in the following order:
  266. *
  267. * 1. Fragment (anchors)
  268. * 2. Query (CGI stuff)
  269. * 3. Scheme ("http")
  270. * 4. Authority (host name)
  271. * 5. Username/Password (if any)
  272. * 6. Port (server port if any)
  273. * 7. Path (/homepages/mypage.html)
  274. *
  275. * The reason for this order is to minimize any parsing ambiguities.
  276. * Fragments and queries can contain almost anything (they are parts
  277. * that can contain custom data with their own syntax). Parsing
  278. * them out first removes a large chance of parsing errors. This
  279. * method expects well formed URI's, but performing the parse in
  280. * this order makes us a little more tolerant of user error.
  281. *
  282. * REGEXP
  283. * Why doesn't this use regular expressions to parse the URI? We
  284. * have found that in a real world scenario, URI's are not always
  285. * well formed. Sometimes characters that should have been escaped
  286. * are not, and those situations would break a regexp pattern. This
  287. * function attempts to be smart about what it is parsing based on
  288. * location of characters relative to each other. This function has
  289. * been proven through real-world use to parse the vast majority
  290. * of URI's correctly.
  291. *
  292. * NOTE
  293. * It is assumed that the string in URI form is escaped. This function
  294. * does not escape anything. If you constructed the URI string by
  295. * hand, and used this to parse in the URI and still need it escaped,
  296. * call forceEscape() on your URI object.
  297. *
  298. * Parsing Assumptions
  299. * This routine assumes that the URI being passed is well formed.
  300. * Passing things like local paths, malformed URI's, and the such
  301. * will result in parsing errors. This function can handle
  302. * - absolute hierarchical (e.g. "http://something.com/index.html),
  303. * - relative hierarchical (e.g. "../images/flower.gif"), or
  304. * - non-hierarchical URIs (e.g. "mailto:jsmith@fungoo.com").
  305. *
  306. * Anything else will probably result in a parsing error, or a bogus
  307. * URI object.
  308. *
  309. * Note that non-hierarchical URIs *MUST* have a scheme, otherwise
  310. * they will be mistaken for relative URI's.
  311. *
  312. * If you are not sure what is being passed to you (like manually
  313. * entered text from UI), you can construct a blank URI object and
  314. * call unknownToURI() passing in the unknown string.
  315. *
  316. * @return true if successful, false if there was some kind of
  317. * parsing error
  318. */
  319. protected function parseURI(uri:String) : Boolean
  320. {
  321. var baseURI:String = uri;
  322. var index:int, index2:int;
  323. // Make sure this object is clean before we start. If it was used
  324. // before and we are now parsing a new URI, we don't want any stale
  325. // info lying around.
  326. initialize();
  327. // Remove any fragments (anchors) from the URI
  328. index = baseURI.indexOf("#");
  329. if (index != -1)
  330. {
  331. // Store the fragment piece if any
  332. if (baseURI.length > (index + 1)) // +1 is to skip the '#'
  333. _fragment = baseURI.substr(index + 1, baseURI.length - (index + 1));
  334. // Trim off the fragment
  335. baseURI = baseURI.substr(0, index);
  336. }
  337. // We need to strip off any CGI parameters (eg '?param=bob')
  338. index = baseURI.indexOf("?");
  339. if (index != -1)
  340. {
  341. if (baseURI.length > (index + 1))
  342. _query = baseURI.substr(index + 1, baseURI.length - (index + 1)); // +1 is to skip the '?'
  343. // Trim off the query
  344. baseURI = baseURI.substr(0, index);
  345. }
  346. // Now try to find the scheme part
  347. index = baseURI.search(':');
  348. index2 = baseURI.search('/');
  349. var containsColon:Boolean = (index != -1);
  350. var containsSlash:Boolean = (index2 != -1);
  351. // This value is indeterminate if "containsColon" is false.
  352. // (if there is no colon, does the slash come before or
  353. // after said non-existing colon?)
  354. var colonBeforeSlash:Boolean = (!containsSlash || index < index2);
  355. // If it has a colon and it's before the first slash, we will treat
  356. // it as a scheme. If a slash is before a colon, there must be a
  357. // stray colon in a path or something. In which case, the colon is
  358. // not the separator for the scheme. Technically, we could consider
  359. // this an error, but since this is not an ambiguous state (we know
  360. // 100% that this has no scheme), we will keep going.
  361. if (containsColon && colonBeforeSlash)
  362. {
  363. // We found a scheme
  364. _scheme = baseURI.substr(0, index);
  365. // Normalize the scheme
  366. _scheme = _scheme.toLowerCase();
  367. baseURI = baseURI.substr(index + 1);
  368. if (baseURI.substr(0, 2) == "//")
  369. {
  370. // This is a hierarchical URI
  371. _nonHierarchical = "";
  372. // Trim off the "//"
  373. baseURI = baseURI.substr(2, baseURI.length - 2);
  374. }
  375. else
  376. {
  377. // This is a non-hierarchical URI like "mailto:bob@mail.com"
  378. _nonHierarchical = baseURI;
  379. if ((_valid = validateURI()) == false)
  380. initialize(); // Bad URI. Clear it.
  381. // No more parsing to do for this case
  382. return isValid();
  383. }
  384. }
  385. else
  386. {
  387. // No scheme. We will consider this a relative URI
  388. _scheme = "";
  389. _relative = true;
  390. _nonHierarchical = "";
  391. }
  392. // Ok, what we have left is everything after the <scheme>://
  393. // Now that we have stripped off any query and fragment parts, we
  394. // need to split the authority from the path
  395. if (isRelative())
  396. {
  397. // Don't bother looking for the authority. It's a relative URI
  398. _authority = "";
  399. _port = "";
  400. _path = baseURI;
  401. }
  402. else
  403. {
  404. // Check for malformed UNC style file://///server/type/path/
  405. // By the time we get here, we have already trimmed the "file://"
  406. // so baseURI will be ///server/type/path. If baseURI only
  407. // has one slash, we leave it alone because that is valid (that
  408. // is the case of "file:///path/to/file.txt" where there is no
  409. // server - implicit "localhost").
  410. if (baseURI.substr(0, 2) == "//")
  411. {
  412. // Trim all leading slashes
  413. while(baseURI.charAt(0) == "/")
  414. baseURI = baseURI.substr(1, baseURI.length - 1);
  415. }
  416. index = baseURI.search('/');
  417. if (index == -1)
  418. {
  419. // No path. We must have passed something like "http://something.com"
  420. _authority = baseURI;
  421. _path = "";
  422. }
  423. else
  424. {
  425. _authority = baseURI.substr(0, index);
  426. _path = baseURI.substr(index, baseURI.length - index);
  427. }
  428. // Check to see if the URI has any username or password information.
  429. // For example: ftp://username:password@server.com
  430. index = _authority.search('@');
  431. if (index != -1)
  432. {
  433. // We have a username and possibly a password
  434. _username = _authority.substr(0, index);
  435. // Remove the username/password from the authority
  436. _authority = _authority.substr(index + 1); // Skip the '@'
  437. // Now check to see if the username also has a password
  438. index = _username.search(':');
  439. if (index != -1)
  440. {
  441. _password = _username.substring(index + 1, _username.length);
  442. _username = _username.substr(0, index);
  443. }
  444. else
  445. _password = "";
  446. }
  447. else
  448. {
  449. _username = "";
  450. _password = "";
  451. }
  452. // Lastly, check to see if the authorty has a port number.
  453. // This is parsed after the username/password to avoid conflicting
  454. // with the ':' in the 'username:password' if one exists.
  455. index = _authority.search(':');
  456. if (index != -1)
  457. {
  458. _port = _authority.substring(index + 1, _authority.length); // skip the ':'
  459. _authority = _authority.substr(0, index);
  460. }
  461. else
  462. {
  463. _port = "";
  464. }
  465. // Lastly, normalize the authority. Domain names
  466. // are case insensitive.
  467. _authority = _authority.toLowerCase();
  468. }
  469. if ((_valid = validateURI()) == false)
  470. initialize(); // Bad URI. Clear it
  471. return isValid();
  472. }
  473. /********************************************************************
  474. * Copy function.
  475. */
  476. public function copyURI(uri:URI) : void
  477. {
  478. this._scheme = uri._scheme;
  479. this._authority = uri._authority;
  480. this._username = uri._username;
  481. this._password = uri._password;
  482. this._port = uri._port;
  483. this._path = uri._path;
  484. this._query = uri._query;
  485. this._fragment = uri._fragment;
  486. this._nonHierarchical = uri._nonHierarchical;
  487. this._valid = uri._valid;
  488. this._relative = uri._relative;
  489. }
  490. /**
  491. * @private
  492. * Checks if the given string only contains a-z or A-Z.
  493. */
  494. protected function verifyAlpha(str:String) : Boolean
  495. {
  496. var pattern:RegExp = /[^a-z]/;
  497. var index:int;
  498. str = str.toLowerCase();
  499. index = str.search(pattern);
  500. if (index == -1)
  501. return true;
  502. else
  503. return false;
  504. }
  505. /**
  506. * Is this a valid URI?
  507. *
  508. * @return true if this object represents a valid URI, false
  509. * otherwise.
  510. */
  511. public function isValid() : Boolean
  512. {
  513. return this._valid;
  514. }
  515. /**
  516. * Is this URI an absolute URI? An absolute URI is a complete, fully
  517. * qualified reference to a resource. e.g. http://site.com/index.htm
  518. * Non-hierarchical URI's are always absolute.
  519. */
  520. public function isAbsolute() : Boolean
  521. {
  522. return !this._relative;
  523. }
  524. /**
  525. * Is this URI a relative URI? Relative URI's do not have a scheme
  526. * and only contain a relative path with optional anchor and query
  527. * parts. e.g. "../reports/index.htm". Non-hierarchical URI's
  528. * will never be relative.
  529. */
  530. public function isRelative() : Boolean
  531. {
  532. return this._relative;
  533. }
  534. /**
  535. * Does this URI point to a resource that is a directory/folder?
  536. * The URI specification dictates that any path that ends in a slash
  537. * is a directory. This is needed to be able to perform correct path
  538. * logic when combining relative URI's with absolute URI's to
  539. * obtain the correct absolute URI to a resource.
  540. *
  541. * @see URI.chdir
  542. *
  543. * @return true if this URI represents a directory resource, false
  544. * if this URI represents a file resource.
  545. */
  546. public function isDirectory() : Boolean
  547. {
  548. if (_path.length == 0)
  549. return false;
  550. return (_path.charAt(path.length - 1) == '/');
  551. }
  552. /**
  553. * Is this URI a hierarchical URI? URI's can be
  554. */
  555. public function isHierarchical() : Boolean
  556. {
  557. return hierState;
  558. }
  559. /**
  560. * The scheme of the URI.
  561. */
  562. public function get scheme() : String
  563. {
  564. return URI.unescapeChars(_scheme);
  565. }
  566. public function set scheme(schemeStr:String) : void
  567. {
  568. // Normalize the scheme
  569. var normalized:String = schemeStr.toLowerCase();
  570. _scheme = URI.fastEscapeChars(normalized, URI.URIschemeExcludedBitmap);
  571. }
  572. /**
  573. * The authority (host) of the URI. Only valid for
  574. * hierarchical URI's. If the URI is relative, this will
  575. * be an empty string. When setting this value, the string
  576. * given is assumed to be unescaped. When retrieving this
  577. * value, the resulting string is unescaped.
  578. */
  579. public function get authority() : String
  580. {
  581. return URI.unescapeChars(_authority);
  582. }
  583. public function set authority(authorityStr:String) : void
  584. {
  585. // Normalize the authority
  586. authorityStr = authorityStr.toLowerCase();
  587. _authority = URI.fastEscapeChars(authorityStr,
  588. URI.URIauthorityExcludedBitmap);
  589. // Only hierarchical URI's can have an authority, make
  590. // sure this URI is of the proper format.
  591. this.hierState = true;
  592. }
  593. /**
  594. * The username of the URI. Only valid for hierarchical
  595. * URI's. If the URI is relative, this will be an empty
  596. * string.
  597. *
  598. * <p>The URI specification allows for authentication
  599. * credentials to be embedded in the URI as such:</p>
  600. *
  601. * <p>http://user:passwd&#64;host/path/to/file.htm</p>
  602. *
  603. * <p>When setting this value, the string
  604. * given is assumed to be unescaped. When retrieving this
  605. * value, the resulting string is unescaped.</p>
  606. */
  607. public function get username() : String
  608. {
  609. return URI.unescapeChars(_username);
  610. }
  611. public function set username(usernameStr:String) : void
  612. {
  613. _username = URI.fastEscapeChars(usernameStr, URI.URIuserpassExcludedBitmap);
  614. // Only hierarchical URI's can have a username.
  615. this.hierState = true;
  616. }
  617. /**
  618. * The password of the URI. Similar to username.
  619. * @see URI.username
  620. */
  621. public function get password() : String
  622. {
  623. return URI.unescapeChars(_password);
  624. }
  625. public function set password(passwordStr:String) : void
  626. {
  627. _password = URI.fastEscapeChars(passwordStr,
  628. URI.URIuserpassExcludedBitmap);
  629. // Only hierarchical URI's can have a password.
  630. this.hierState = true;
  631. }
  632. /**
  633. * The host port number. Only valid for hierarchical URI's. If
  634. * the URI is relative, this will be an empty string. URI's can
  635. * contain the port number of the remote host:
  636. *
  637. * <p>http://site.com:8080/index.htm</p>
  638. */
  639. public function get port() : String
  640. {
  641. return URI.unescapeChars(_port);
  642. }
  643. public function set port(portStr:String) : void
  644. {
  645. _port = URI.escapeChars(portStr);
  646. // Only hierarchical URI's can have a port.
  647. this.hierState = true;
  648. }
  649. /**
  650. * The path portion of the URI. Only valid for hierarchical
  651. * URI's. When setting this value, the string
  652. * given is assumed to be unescaped. When retrieving this
  653. * value, the resulting string is unescaped.
  654. *
  655. * <p>The path portion can be in one of two formats. 1) an absolute
  656. * path, or 2) a relative path. An absolute path starts with a
  657. * slash ('/'), a relative path does not.</p>
  658. *
  659. * <p>An absolute path may look like:</p>
  660. * <listing>/full/path/to/my/file.htm</listing>
  661. *
  662. * <p>A relative path may look like:</p>
  663. * <listing>
  664. * path/to/my/file.htm
  665. * ../images/logo.gif
  666. * ../../reports/index.htm
  667. * </listing>
  668. *
  669. * <p>Paths can be absolute or relative. Note that this not the same as
  670. * an absolute or relative URI. An absolute URI can only have absolute
  671. * paths. For example:</p>
  672. *
  673. * <listing>http:/site.com/path/to/file.htm</listing>
  674. *
  675. * <p>This absolute URI has an absolute path of "/path/to/file.htm".</p>
  676. *
  677. * <p>Relative URI's can have either absolute paths or relative paths.
  678. * All of the following relative URI's are valid:</p>
  679. *
  680. * <listing>
  681. * /absolute/path/to/file.htm
  682. * path/to/file.htm
  683. * ../path/to/file.htm
  684. * </listing>
  685. */
  686. public function get path() : String
  687. {
  688. return URI.unescapeChars(_path);
  689. }
  690. public function set path(pathStr:String) : void
  691. {
  692. this._path = URI.fastEscapeChars(pathStr, URI.URIpathExcludedBitmap);
  693. if (this._scheme == UNKNOWN_SCHEME)
  694. {
  695. // We set the path. This is a valid URI now.
  696. this._scheme = "";
  697. }
  698. // Only hierarchical URI's can have a path.
  699. hierState = true;
  700. }
  701. /**
  702. * The query (CGI) portion of the URI. This part is valid for
  703. * both hierarchical and non-hierarchical URI's.
  704. *
  705. * <p>This accessor should only be used if a custom query syntax
  706. * is used. This URI class supports the common "param=value"
  707. * style query syntax via the get/setQueryValue() and
  708. * get/setQueryByMap() functions. Those functions should be used
  709. * instead if the common syntax is being used.
  710. *
  711. * <p>The URI RFC does not specify any particular
  712. * syntax for the query part of a URI. It is intended to allow
  713. * any format that can be agreed upon by the two communicating hosts.
  714. * However, most systems have standardized on the typical CGI
  715. * format:</p>
  716. *
  717. * <listing>http://site.com/script.php?param1=value1&param2=value2</listing>
  718. *
  719. * <p>This class has specific support for this query syntax</p>
  720. *
  721. * <p>This common query format is an array of name/value
  722. * pairs with its own syntax that is different from the overall URI
  723. * syntax. The query has its own escaping logic. For a query part
  724. * to be properly escaped and unescaped, it must be split into its
  725. * component parts. This accessor escapes/unescapes the entire query
  726. * part without regard for it's component parts. This has the
  727. * possibliity of leaving the query string in an ambiguous state in
  728. * regards to its syntax. If the contents of the query part are
  729. * important, it is recommended that get/setQueryValue() or
  730. * get/setQueryByMap() are used instead.</p>
  731. *
  732. * If a different query syntax is being used, a subclass of URI
  733. * can be created to handle that specific syntax.
  734. *
  735. * @see URI.getQueryValue, URI.getQueryByMap
  736. */
  737. public function get query() : String
  738. {
  739. return URI.unescapeChars(_query);
  740. }
  741. public function set query(queryStr:String) : void
  742. {
  743. _query = URI.fastEscapeChars(queryStr, URI.URIqueryExcludedBitmap);
  744. // both hierarchical and non-hierarchical URI's can
  745. // have a query. Do not set the hierState.
  746. }
  747. /**
  748. * Accessor to the raw query data. If you are using a custom query
  749. * syntax, this accessor can be used to get and set the query part
  750. * directly with no escaping/unescaping. This should ONLY be used
  751. * if your application logic is handling custom query logic and
  752. * handling the proper escaping of the query part.
  753. */
  754. public function get queryRaw() : String
  755. {
  756. return _query;
  757. }
  758. public function set queryRaw(queryStr:String) : void
  759. {
  760. _query = queryStr;
  761. }
  762. /**
  763. * The fragment (anchor) portion of the URI. This is valid for
  764. * both hierarchical and non-hierarchical URI's.
  765. */
  766. public function get fragment() : String
  767. {
  768. return URI.unescapeChars(_fragment);
  769. }
  770. public function set fragment(fragmentStr:String) : void
  771. {
  772. _fragment = URI.fastEscapeChars(fragmentStr, URIfragmentExcludedBitmap);
  773. // both hierarchical and non-hierarchical URI's can
  774. // have a fragment. Do not set the hierState.
  775. }
  776. /**
  777. * The non-hierarchical part of the URI. For example, if
  778. * this URI object represents "mailto:somebody@company.com",
  779. * this will contain "somebody@company.com". This is valid only
  780. * for non-hierarchical URI's.
  781. */
  782. public function get nonHierarchical() : String
  783. {
  784. return URI.unescapeChars(_nonHierarchical);
  785. }
  786. public function set nonHierarchical(nonHier:String) : void
  787. {
  788. _nonHierarchical = URI.fastEscapeChars(nonHier, URInonHierexcludedBitmap);
  789. // This is a non-hierarchical URI.
  790. this.hierState = false;
  791. }
  792. /**
  793. * Quick shorthand accessor to set the parts of this URI.
  794. * The given parts are assumed to be in unescaped form. If
  795. * the URI is non-hierarchical (e.g. mailto:) you will need
  796. * to call SetScheme() and SetNonHierarchical().
  797. */
  798. public function setParts(schemeStr:String, authorityStr:String,
  799. portStr:String, pathStr:String, queryStr:String,
  800. fragmentStr:String) : void
  801. {
  802. this.scheme = schemeStr;
  803. this.authority = authorityStr;
  804. this.port = portStr;
  805. this.path = pathStr;
  806. this.query = queryStr;
  807. this.fragment = fragmentStr;
  808. hierState = true;
  809. }
  810. /**
  811. * URI escapes the given character string. This is similar in function
  812. * to the global encodeURIComponent() function in ActionScript, but is
  813. * slightly different in regards to which characters get escaped. This
  814. * escapes the characters specified in the URIbaselineExluded set (see class
  815. * static members). This is needed for this class to work properly.
  816. *
  817. * <p>If a different set of characters need to be used for the escaping,
  818. * you may use fastEscapeChars() and specify a custom URIEncodingBitmap
  819. * that contains the characters your application needs escaped.</p>
  820. *
  821. * <p>Never pass a full URI to this function. A URI can only be properly
  822. * escaped/unescaped when split into its component parts (see RFC 3986
  823. * section 2.4). This is due to the fact that the URI component separators
  824. * could be characters that would normally need to be escaped.</p>
  825. *
  826. * @param unescaped character string to be escaped.
  827. *
  828. * @return escaped character string
  829. *
  830. * @see encodeURIComponent
  831. * @see fastEscapeChars
  832. */
  833. static public function escapeChars(unescaped:String) : String
  834. {
  835. // This uses the excluded set by default.
  836. return fastEscapeChars(unescaped, URI.URIbaselineExcludedBitmap);
  837. }
  838. /**
  839. * Unescape any URI escaped characters in the given character
  840. * string.
  841. *
  842. * <p>Never pass a full URI to this function. A URI can only be properly
  843. * escaped/unescaped when split into its component parts (see RFC 3986
  844. * section 2.4). This is due to the fact that the URI component separators
  845. * could be characters that would normally need to be escaped.</p>
  846. *
  847. * @param escaped the escaped string to be unescaped.
  848. *
  849. * @return unescaped string.
  850. */
  851. static public function unescapeChars(escaped:String /*, onlyHighASCII:Boolean = false*/) : String
  852. {
  853. // We can just use the default AS function. It seems to
  854. // decode everything correctly
  855. var unescaped:String;
  856. unescaped = decodeURIComponent(escaped);
  857. return unescaped;
  858. }
  859. /**
  860. * Performance focused function that escapes the given character
  861. * string using the given URIEncodingBitmap as the rule for what
  862. * characters need to be escaped. This function is used by this
  863. * class and can be used externally to this class to perform
  864. * escaping on custom character sets.
  865. *
  866. * <p>Never pass a full URI to this function. A URI can only be properly
  867. * escaped/unescaped when split into its component parts (see RFC 3986
  868. * section 2.4). This is due to the fact that the URI component separators
  869. * could be characters that would normally need to be escaped.</p>
  870. *
  871. * @param unescaped the unescaped string to be escaped
  872. * @param bitmap the set of characters that need to be escaped
  873. *
  874. * @return the escaped string.
  875. */
  876. static public function fastEscapeChars(unescaped:String, bitmap:URIEncodingBitmap) : String
  877. {
  878. var escaped:String = "";
  879. var c:String;
  880. var x:int, i:int;
  881. for (i = 0; i < unescaped.length; i++)
  882. {
  883. c = unescaped.charAt(i);
  884. x = bitmap.ShouldEscape(c);
  885. if (x)
  886. {
  887. c = x.toString(16);
  888. if (c.length == 1)
  889. c = "0" + c;
  890. c = "%" + c;
  891. c = c.toUpperCase();
  892. }
  893. escaped += c;
  894. }
  895. return escaped;
  896. }
  897. /**
  898. * Is this URI of a particular scheme type? For example,
  899. * passing "http" to a URI object that represents the URI
  900. * "http://site.com/" would return true.
  901. *
  902. * @param scheme scheme to check for
  903. *
  904. * @return true if this URI object is of the given type, false
  905. * otherwise.
  906. */
  907. public function isOfType(scheme:String) : Boolean
  908. {
  909. // Schemes are never case sensitive. Ignore case.
  910. scheme = scheme.toLowerCase();
  911. return (this._scheme == scheme);
  912. }
  913. /**
  914. * Get the value for the specified named in the query part. This
  915. * assumes the query part of the URI is in the common
  916. * "name1=value1&name2=value2" syntax. Do not call this function
  917. * if you are using a custom query syntax.
  918. *
  919. * @param name name of the query value to get.
  920. *
  921. * @return the value of the query name, empty string if the
  922. * query name does not exist.
  923. */
  924. public function getQueryValue(name:String) : String
  925. {
  926. var map:Object;
  927. var item:String;
  928. var value:String;
  929. map = getQueryByMap();
  930. for (item in map)
  931. {
  932. if (item == name)
  933. {
  934. value = map[item];
  935. return value;
  936. }
  937. }
  938. // Didn't find the specified key
  939. return new String("");
  940. }
  941. /**
  942. * Set the given value on the given query name. If the given name
  943. * does not exist, it will automatically add this name/value pair
  944. * to the query. If null is passed as the value, it will remove
  945. * the given item from the query.
  946. *
  947. * <p>This automatically escapes any characters that may conflict with
  948. * the query syntax so that they are "safe" within the query. The
  949. * strings passed are assumed to be literal unescaped name and value.</p>
  950. *
  951. * @param name name of the query value to set
  952. * @param value value of the query item to set. If null, this will
  953. * force the removal of this item from the query.
  954. */
  955. public function setQueryValue(name:String, value:String) : void
  956. {
  957. var map:Object;
  958. map = getQueryByMap();
  959. // If the key doesn't exist yet, this will create a new pair in
  960. // the map. If it does exist, this will overwrite the previous
  961. // value, which is what we want.
  962. map[name] = value;
  963. setQueryByMap(map);
  964. }
  965. /**
  966. * Get the query of the URI in an Object class that allows for easy
  967. * access to the query data via Object accessors. For example:
  968. *
  969. * <listing>
  970. * var query:Object = uri.getQueryByMap();
  971. * var value:String = query["param"]; // get a value
  972. * query["param2"] = "foo"; // set a new value
  973. * </listing>
  974. *
  975. * @return Object that contains the name/value pairs of the query.
  976. *
  977. * @see #setQueryByMap
  978. * @see #getQueryValue
  979. * @see #setQueryValue
  980. */
  981. public function getQueryByMap() : Object
  982. {
  983. var queryStr:String;
  984. var pair:String;
  985. var pairs:Array;
  986. var item:Array;
  987. var name:String, value:String;
  988. var index:int;
  989. var map:Object = new Object();
  990. // We need the raw query string, no unescaping.
  991. queryStr = this._query;
  992. pairs = queryStr.split('&');
  993. for each (pair in pairs)
  994. {
  995. if (pair.length == 0)
  996. continue;
  997. item = pair.split('=');
  998. if (item.length > 0)
  999. name = item[0];
  1000. else
  1001. continue; // empty array
  1002. if (item.length > 1)
  1003. value = item[1];
  1004. else
  1005. value = "";
  1006. name = queryPartUnescape(name);
  1007. value = queryPartUnescape(value);
  1008. map[name] = value;
  1009. }
  1010. return map;
  1011. }
  1012. /**
  1013. * Set the query part of this URI using the given object as the
  1014. * content source. Any member of the object that has a value of
  1015. * null will not be in the resulting query.
  1016. *
  1017. * @param map object that contains the name/value pairs as
  1018. * members of that object.
  1019. *
  1020. * @see #getQueryByMap
  1021. * @see #getQueryValue
  1022. * @see #setQueryValue
  1023. */
  1024. public function setQueryByMap(map:Object) : void
  1025. {
  1026. var item:String;
  1027. var name:String, value:String;
  1028. var queryStr:String = "";
  1029. var tmpPair:String;
  1030. var foo:String;
  1031. for (item in map)
  1032. {
  1033. name = item;
  1034. value = map[item];
  1035. if (value == null)
  1036. value = "";
  1037. // Need to escape the name/value pair so that they
  1038. // don't conflict with the query syntax (specifically
  1039. // '=', '&', and <whitespace>).
  1040. name = queryPartEscape(name);
  1041. value = queryPartEscape(value);
  1042. tmpPair = name;
  1043. if (value.length > 0)
  1044. {
  1045. tmpPair += "=";
  1046. tmpPair += value;
  1047. }
  1048. if (queryStr.length != 0)
  1049. queryStr += '&'; // Add the separator
  1050. queryStr += tmpPair;
  1051. }
  1052. // We don't want to escape. We already escaped the
  1053. // individual name/value pairs. If we escaped the
  1054. // query string again by assigning it to "query",
  1055. // we would have double escaping.
  1056. _query = queryStr;
  1057. }
  1058. /**
  1059. * Similar to Escape(), except this also escapes characters that
  1060. * would conflict with the name/value pair query syntax. This is
  1061. * intended to be called on each individual "name" and "value"
  1062. * in the query making sure that nothing in the name or value
  1063. * strings contain characters that would conflict with the query
  1064. * syntax (e.g. '=' and '&').
  1065. *
  1066. * @param unescaped unescaped string that is to be escaped.
  1067. *
  1068. * @return escaped string.
  1069. *
  1070. * @see #queryUnescape
  1071. */
  1072. static public function queryPartEscape(unescaped:String) : String
  1073. {
  1074. var escaped:String = unescaped;
  1075. escaped = URI.fastEscapeChars(unescaped, URI.URIqueryPartExcludedBitmap);
  1076. return escaped;
  1077. }
  1078. /**
  1079. * Unescape the individual name/value string pairs.
  1080. *
  1081. * @param escaped escaped string to be unescaped
  1082. *
  1083. * @return unescaped string
  1084. *
  1085. * @see #queryEscape
  1086. */
  1087. static public function queryPartUnescape(escaped:String) : String
  1088. {
  1089. var unescaped:String = escaped;
  1090. unescaped = unescapeChars(unescaped);
  1091. return unescaped;
  1092. }
  1093. /**
  1094. * Output this URI as a string. The resulting string is properly
  1095. * escaped and well formed for machine processing.
  1096. */
  1097. public function toString() : String
  1098. {
  1099. if (this == null)
  1100. return "";
  1101. else
  1102. return toStringInternal(false);
  1103. }
  1104. /**
  1105. * Output the URI as a string that is easily readable by a human.
  1106. * This outputs the URI with all escape sequences unescaped to
  1107. * their character representation. This makes the URI easier for
  1108. * a human to read, but the URI could be completely invalid
  1109. * because some unescaped characters may now cause ambiguous parsing.
  1110. * This function should only be used if you want to display a URI to
  1111. * a user. This function should never be used outside that specific
  1112. * case.
  1113. *
  1114. * @return the URI in string format with all escape sequences
  1115. * unescaped.
  1116. *
  1117. * @see #toString
  1118. */
  1119. public function toDisplayString() : String
  1120. {
  1121. return toStringInternal(true);
  1122. }
  1123. /**
  1124. * @private
  1125. *
  1126. * The guts of toString()
  1127. */
  1128. protected function toStringInternal(forDisplay:Boolean) : String
  1129. {
  1130. var uri:String = "";
  1131. var part:String = "";
  1132. if (isHierarchical() == false)
  1133. {
  1134. // non-hierarchical URI
  1135. uri += (forDisplay ? this.scheme : _scheme);
  1136. uri += ":";
  1137. uri += (forDisplay ? this.nonHierarchical : _nonHierarchical);
  1138. }
  1139. else
  1140. {
  1141. // Hierarchical URI
  1142. if (isRelative() == false)
  1143. {
  1144. // If it is not a relative URI, then we want the scheme and
  1145. // authority parts in the string. If it is relative, we
  1146. // do NOT want this stuff.
  1147. if (_scheme.length != 0)
  1148. {
  1149. part = (forDisplay ? this.scheme : _scheme);
  1150. uri += part + ":";
  1151. }
  1152. if (_authority.length != 0 || isOfType("file"))
  1153. {
  1154. uri += "//";
  1155. // Add on any username/password associated with this
  1156. // authority
  1157. if (_username.length != 0)
  1158. {
  1159. part = (forDisplay ? this.username : _username);
  1160. uri += part;
  1161. if (_password.length != 0)
  1162. {
  1163. part = (forDisplay ? this.password : _password);
  1164. uri += ":" + part;
  1165. }
  1166. uri += "@";
  1167. }
  1168. // add the authority
  1169. part = (forDisplay ? this.authority : _authority);
  1170. uri += part;
  1171. // Tack on the port number, if any
  1172. if (port.length != 0)
  1173. uri += ":" + port;
  1174. }
  1175. }
  1176. // Tack on the path
  1177. part = (forDisplay ? this.path : _path);
  1178. uri += part;
  1179. } // end hierarchical part
  1180. // Both non-hier and hierarchical have query and fragment parts
  1181. // Add on the query and fragment parts
  1182. if (_query.length != 0)
  1183. {
  1184. part = (forDisplay ? this.query : _query);
  1185. uri += "?" + part;
  1186. }
  1187. if (fragment.length != 0)
  1188. {
  1189. part = (forDisplay ? this.fragment : _fragment);
  1190. uri += "#" + part;
  1191. }
  1192. return uri;
  1193. }
  1194. /**
  1195. * Forcefully ensure that this URI is properly escaped.
  1196. *
  1197. * <p>Sometimes URI's are constructed by hand using strings outside
  1198. * this class. In those cases, it is unlikely the URI has been
  1199. * properly escaped. This function forcefully escapes this URI
  1200. * by unescaping each part and then re-escaping it. If the URI
  1201. * did not have any escaping, the first unescape will do nothing
  1202. * and then the re-escape will properly escape everything. If
  1203. * the URI was already escaped, the unescape and re-escape will
  1204. * essentally be a no-op. This provides a safe way to make sure
  1205. * a URI is in the proper escaped form.</p>
  1206. */
  1207. public function forceEscape() : void
  1208. {
  1209. // The accessors for each of the members will unescape
  1210. // and then re-escape as we get and assign them.
  1211. // Handle the parts that are common for both hierarchical
  1212. // and non-hierarchical URI's
  1213. this.scheme = this.scheme;
  1214. this.setQueryByMap(this.getQueryByMap());
  1215. this.fragment = this.fragment;
  1216. if (isHierarchical())
  1217. {
  1218. this.authority = this.authority;
  1219. this.path = this.path;
  1220. this.port = this.port;
  1221. this.username = this.username;
  1222. this.password = this.password;
  1223. }
  1224. else
  1225. {
  1226. this.nonHierarchical = this.nonHierarchical;
  1227. }
  1228. }
  1229. /**
  1230. * Does this URI point to a resource of the given file type?
  1231. * Given a file extension (or just a file name, this will strip the
  1232. * extension), check to see if this URI points to a file of that
  1233. * type.
  1234. *
  1235. * @param extension string that contains a file extension with or
  1236. * without a dot ("html" and ".html" are both valid), or a file
  1237. * name with an extension (e.g. "index.html").
  1238. *
  1239. * @return true if this URI points to a resource with the same file
  1240. * file extension as the extension provided, false otherwise.
  1241. */
  1242. public function isOfFileType(extension:String) : Boolean
  1243. {
  1244. var thisExtension:String;
  1245. var index:int;
  1246. index = extension.lastIndexOf(".");
  1247. if (index != -1)
  1248. {
  1249. // Strip the extension
  1250. extension = extension.substr(index + 1);
  1251. }
  1252. else
  1253. {
  1254. // The caller passed something without a dot in it. We
  1255. // will assume that it is just a plain extension (e.g. "html").
  1256. // What they passed is exactly what we want
  1257. }
  1258. thisExtension = getExtension(true);
  1259. if (thisExtension == "")
  1260. return false;
  1261. // Compare the extensions ignoring case
  1262. if (compareStr(thisExtension, extension, false) == 0)
  1263. return true;
  1264. else
  1265. return false;
  1266. }
  1267. /**
  1268. * Get the ".xyz" file extension from the filename in the URI.
  1269. * For example, if we have the following URI:
  1270. *
  1271. * <listing>http://something.com/path/to/my/page.html?form=yes&name=bob#anchor</listing>
  1272. *
  1273. * <p>This will return ".html".</p>
  1274. *
  1275. * @param minusDot If true, this will strip the dot from the extension.
  1276. * If true, the above example would have returned "html".
  1277. *
  1278. * @return the file extension
  1279. */
  1280. public function getExtension(minusDot:Boolean = false) : String
  1281. {
  1282. var filename:String = getFilename();
  1283. var extension:String;
  1284. var index:int;
  1285. if (filename == "")
  1286. return String("");
  1287. index = filename.lastIndexOf(".");
  1288. // If it doesn't have an extension, or if it is a "hidden" file,
  1289. // it doesn't have an extension. Hidden files on unix start with
  1290. // a dot (e.g. ".login").
  1291. if (index == -1 || index == 0)
  1292. return String("");
  1293. extension = filename.substr(index);
  1294. // If the caller does not want the dot, remove it.
  1295. if (minusDot && extension.charAt(0) == ".")
  1296. extension = extension.substr(1);
  1297. return extension;
  1298. }
  1299. /**
  1300. * Quick function to retrieve the file name off the end of a URI.
  1301. *
  1302. * <p>For example, if the URI is:</p>
  1303. * <listing>http://something.com/some/path/to/my/file.html</listing>
  1304. * <p>this function will return "file.html".</p>
  1305. *
  1306. * @param minusExtension true if the file extension should be stripped
  1307. *
  1308. * @return the file name. If this URI is a directory, the return
  1309. * value will be empty string.
  1310. */
  1311. public function getFilename(minusExtension:Boolean = false) : String
  1312. {
  1313. if (isDirectory())
  1314. return String("");
  1315. var pathStr:String = this.path;
  1316. var filename:String;
  1317. var index:int;
  1318. // Find the last path separator.
  1319. index = pathStr.lastIndexOf("/");
  1320. if (index != -1)
  1321. filename = pathStr.substr(index + 1);
  1322. else
  1323. filename = pathStr;
  1324. if (minusExtension)
  1325. {
  1326. // The caller has requested that the extension be removed
  1327. index = filename.lastIndexOf(".");
  1328. if (index != -1)
  1329. filename = filename.substr(0, index);
  1330. }
  1331. return filename;
  1332. }
  1333. /**
  1334. * @private
  1335. * Helper function to compare strings.
  1336. *
  1337. * @return true if the two strings are identical, false otherwise.
  1338. */
  1339. static protected function compareStr(str1:String, str2:String,
  1340. sensitive:Boolean = true) : Boolean
  1341. {
  1342. if (sensitive == false)
  1343. {
  1344. str1 = str1.toLowerCase();
  1345. str2 = str2.toLowerCase();
  1346. }
  1347. return (str1 == str2)
  1348. }
  1349. /**
  1350. * Based on the type of this URI (http, ftp, etc.) get
  1351. * the default port used for that protocol. This is
  1352. * just intended to be a helper function for the most
  1353. * common cases.
  1354. */
  1355. public function getDefaultPort() : String
  1356. {
  1357. if (_scheme == "http")
  1358. return String("80");
  1359. else if (_scheme == "ftp")
  1360. return String("21");
  1361. else if (_scheme == "file")
  1362. return String("");
  1363. else if (_scheme == "sftp")
  1364. return String("22"); // ssh standard port
  1365. else
  1366. {
  1367. // Don't know the port for this URI type
  1368. return String("");
  1369. }
  1370. }
  1371. /**
  1372. * @private
  1373. *
  1374. * This resolves the given URI if the application has a
  1375. * resolver interface defined. This function does not
  1376. * modify the passed in URI and returns a new URI.
  1377. */
  1378. static protected function resolve(uri:URI) : URI
  1379. {
  1380. var copy:URI = new URI();
  1381. copy.copyURI(uri);
  1382. if (_resolver != null)
  1383. {
  1384. // A resolver class has been registered. Call it.
  1385. return _resolver.resolve(copy);
  1386. }
  1387. else
  1388. {
  1389. // No resolver. Nothing to do, but we don't
  1390. // want to reuse the one passed in.
  1391. return copy;
  1392. }
  1393. }
  1394. /**
  1395. * Accessor to set and get the resolver object used by all URI
  1396. * objects to dynamically resolve URI's before comparison.
  1397. */
  1398. static public function set resolver(resolver:IURIResolver) : void
  1399. {
  1400. _resolver = resolver;
  1401. }
  1402. static public function get resolver() : IURIResolver
  1403. {
  1404. return _resolver;
  1405. }
  1406. /**
  1407. * Given another URI, return this URI object's relation to the one given.
  1408. * URI's can have 1 of 4 possible relationships. They can be unrelated,
  1409. * equal, parent, or a child of the given URI.
  1410. *
  1411. * @param uri URI to compare this URI object to.
  1412. * @param caseSensitive true if the URI comparison should be done
  1413. * taking case into account, false if the comparison should be
  1414. * performed case insensitive.
  1415. *
  1416. * @return URI.NOT_RELATED, URI.CHILD, URI.PARENT, or URI.EQUAL
  1417. */
  1418. public function getRelation(uri:URI, caseSensitive:Boolean = true) : int
  1419. {
  1420. // Give the app a chance to resolve these URI's before we compare them.
  1421. var thisURI:URI = URI.resolve(this);
  1422. var thatURI:URI = URI.resolve(uri);
  1423. if (thisURI.isRelative() || thatURI.isRelative())
  1424. {
  1425. // You cannot compare relative URI's due to their lack of context.
  1426. // You could have two relative URI's that look like:
  1427. // ../../images/
  1428. // ../../images/marketing/logo.gif
  1429. // These may appear related, but you have no overall context
  1430. // from which to make the comparison. The first URI could be
  1431. // from one site and the other URI could be from another site.
  1432. return URI.NOT_RELATED;
  1433. }
  1434. else if (thisURI.isHierarchical() == false || thatURI.isHierarchical() == false)
  1435. {
  1436. // One or both of the URI's are non-hierarchical.
  1437. if (((thisURI.isHierarchical() == false) && (thatURI.isHierarchical() == true)) ||
  1438. ((thisURI.isHierarchical() == true) && (thatURI.isHierarchical() == false)))
  1439. {
  1440. // XOR. One is hierarchical and the other is
  1441. // non-hierarchical. They cannot be compared.
  1442. return URI.NOT_RELATED;
  1443. }
  1444. else
  1445. {
  1446. // They are both non-hierarchical
  1447. if (thisURI.scheme != thatURI.scheme)
  1448. return URI.NOT_RELATED;
  1449. if (thisURI.nonHierarchical != thatURI.nonHierarchical)
  1450. return URI.NOT_RELATED;
  1451. // The two non-hierarcical URI's are equal.
  1452. return URI.EQUAL;
  1453. }
  1454. }
  1455. // Ok, this URI and the one we are being compared to are both
  1456. // absolute hierarchical URI's.
  1457. if (thisURI.scheme != thatURI.scheme)
  1458. return URI.NOT_RELATED;
  1459. if (thisURI.authority != thatURI.authority)
  1460. return URI.NOT_RELATED;
  1461. var thisPort:String = thisURI.port;
  1462. var thatPort:String = thatURI.port;
  1463. // Different ports are considered completely different servers.
  1464. if (thisPort == "")
  1465. thisPort = thisURI.getDefaultPort();
  1466. if (thatPort == "")
  1467. thatPort = thatURI.getDefaultPort();
  1468. // Check to see if the port is the default port.
  1469. if (thisPort != thatPort)
  1470. return URI.NOT_RELATED;
  1471. if (compareStr(thisURI.path, thatURI.path, caseSensitive))
  1472. return URI.EQUAL;
  1473. // Special case check. If we are here, the scheme, authority,
  1474. // and port match, and it is not a relative path, but the
  1475. // paths did not match. There is a special case where we
  1476. // could have:
  1477. // http://something.com/
  1478. // http://something.com
  1479. // Technically, these are equal. So lets, check for this case.
  1480. var thisPath:String = thisURI.path;
  1481. var thatPath:String = thatURI.path;
  1482. if ( (thisPath == "/" || thatPath == "/") &&
  1483. (thisPath == "" || thatPath == "") )
  1484. {
  1485. // We hit the special case. These two are equal.
  1486. return URI.EQUAL;
  1487. }
  1488. // Ok, the paths do not match, but one path may be a parent/child
  1489. // of the other. For example, we may have:
  1490. // http://something.com/path/to/homepage/
  1491. // http://something.com/path/to/homepage/images/logo.gif
  1492. // In this case, the first is a parent of the second (or the second
  1493. // is a child of the first, depending on which you compare to the
  1494. // other). To make this comparison, we must split the path into
  1495. // its component parts (split the string on the '/' path delimiter).
  1496. // We then compare the
  1497. var thisParts:Array, thatParts:Array;
  1498. var thisPart:String, thatPart:String;
  1499. var i:int;
  1500. thisParts = thisPath.split("/");
  1501. thatParts = thatPath.split("/");
  1502. if (thisParts.length > thatParts.length)
  1503. {
  1504. thatPart = thatParts[thatParts.length - 1];
  1505. if (thatPart.length > 0)
  1506. {
  1507. // if the last part is not empty, the passed URI is
  1508. // not a directory. There is no way the passed URI
  1509. // can be a parent.
  1510. return URI.NOT_RELATED;
  1511. }
  1512. else
  1513. {
  1514. // Remove the empty trailing part
  1515. thatParts.pop();
  1516. }
  1517. // This may be a child of the one passed in
  1518. for (i = 0; i < thatParts.length; i++)
  1519. {
  1520. thisPart = thisParts[i];
  1521. thatPart = thatParts[i];
  1522. if (compareStr(thisPart, thatPart, caseSensitive) == false)
  1523. return URI.NOT_RELATED;
  1524. }
  1525. return URI.CHILD;
  1526. }
  1527. else if (thisParts.length < thatParts.length)
  1528. {
  1529. thisPart = thisParts[thisParts.length - 1];
  1530. if (thisPart.length > 0)
  1531. {
  1532. // if the last part is not empty, this URI is not a
  1533. // directory. There is no way this object can be
  1534. // a parent.
  1535. return URI.NOT_RELATED;
  1536. }
  1537. else
  1538. {
  1539. // Remove the empty trailing part
  1540. thisParts.pop();
  1541. }
  1542. // This may be the parent of the one passed in
  1543. for (i = 0; i < thisParts.length; i++)
  1544. {
  1545. thisPart = thisParts[i];
  1546. thatPart = thatParts[i];
  1547. if (compareStr(thisPart, thatPart, caseSensitive) == false)
  1548. return URI.NOT_RELATED;
  1549. }
  1550. return URI.PARENT;
  1551. }
  1552. else
  1553. {
  1554. // Both URI's have the same number of path components, but
  1555. // it failed the equivelence check above. This means that
  1556. // the two URI's are not related.
  1557. return URI.NOT_RELATED;
  1558. }
  1559. // If we got here, the scheme and authority are the same,
  1560. // but the paths pointed to two different locations that
  1561. // were in different parts of the file system tree
  1562. return URI.NOT_RELATED;
  1563. }
  1564. /**
  1565. * Given another URI, return the common parent between this one
  1566. * and the provided URI.
  1567. *
  1568. * @param uri the other URI from which to find a common parent
  1569. * @para caseSensitive true if this operation should be done
  1570. * with case sensitive comparisons.
  1571. *
  1572. * @return the parent URI if successful, null otherwise.
  1573. */
  1574. public function getCommonParent(uri:URI, caseSensitive:Boolean = true) : URI
  1575. {
  1576. var thisURI:URI = URI.resolve(this);
  1577. var thatURI:URI = URI.resolve(uri);
  1578. if(!thisURI.isAbsolute() || !thatURI.isAbsolute() ||
  1579. thisURI.isHierarchical() == false ||
  1580. thatURI.isHierarchical() == false)
  1581. {
  1582. // Both URI's must be absolute hierarchical for this to
  1583. // make sense.
  1584. return null;
  1585. }
  1586. var relation:int = thisURI.getRelation(thatURI);
  1587. if (relation == URI.NOT_RELATED)
  1588. {
  1589. // The given URI is not related to this one. No
  1590. // common parent.
  1591. return null;
  1592. }
  1593. thisURI.chdir(".");
  1594. thatURI.chdir(".");
  1595. var strBefore:String, strAfter:String;
  1596. do
  1597. {
  1598. relation = thisURI.getRelation(thatURI, caseSensitive);
  1599. if(relation == URI.EQUAL || relation == URI.PARENT)
  1600. break;
  1601. // If strBefore and strAfter end up being the same,
  1602. // we know we are at the root of the path because
  1603. // chdir("..") is doing nothing.
  1604. strBefore = thisURI.toString();
  1605. thisURI.chdir("..");
  1606. strAfter = thisURI.toString();
  1607. }
  1608. while(strBefore != strAfter);
  1609. return thisURI;
  1610. }
  1611. /**
  1612. * This function is used to move around in a URI in a way similar
  1613. * to the 'cd' or 'chdir' commands on Unix. These operations are
  1614. * completely string based, using the context of the URI to
  1615. * determine the position within the path. The heuristics used
  1616. * to determine the action are based off Appendix C in RFC 2396.
  1617. *
  1618. * <p>URI paths that end in '/' are considered paths that point to
  1619. * directories, while paths that do not end in '/' are files. For
  1620. * example, if you execute chdir("d") on the following URI's:<br/>
  1621. * 1. http://something.com/a/b/c/ (directory)<br/>
  1622. * 2. http://something.com/a/b/c (not directory)<br/>
  1623. * you will get:<br/>
  1624. * 1. http://something.com/a/b/c/d<br/>
  1625. * 2. http://something.com/a/b/d<br/></p>
  1626. *
  1627. * <p>See RFC 2396, Appendix C for more info.</p>
  1628. *
  1629. * @param reference the URI or path to "cd" to.
  1630. * @param escape true if the passed reference string should be URI
  1631. * escaped before using it.
  1632. *
  1633. * @return true if the chdir was successful, false otherwise.
  1634. */
  1635. public function chdir(reference:String, escape:Boolean = false) : Boolean
  1636. {
  1637. var uriReference:URI;
  1638. var ref:String = reference;
  1639. if (escape)
  1640. ref = URI.escapeChars(reference);
  1641. if (ref == "")
  1642. {
  1643. // NOOP
  1644. return true;
  1645. }
  1646. else if (ref.substr(0, 2) == "//")
  1647. {
  1648. // Special case. This is an absolute URI but without the scheme.
  1649. // Take the scheme from this URI and tack it on. This is
  1650. // intended to make working with chdir() a little more
  1651. // tolerant.
  1652. var f:String = this.scheme + ":" + ref;
  1653. return constructURI(f);
  1654. }
  1655. else if (ref.charAt(0) == "?")
  1656. {
  1657. // A relative URI that is just a query part is essentially
  1658. // a "./?query". We tack on the "./" here to make the rest
  1659. // of our logic work.
  1660. ref = "./" + ref;
  1661. }
  1662. // Parse the reference passed in as a URI. This way we
  1663. // get any query and fragments parsed out as well.
  1664. uriReference = new URI(ref);
  1665. if (uriReference.isAbsolute() ||
  1666. uriReference.isHierarchical() == false)
  1667. {
  1668. // If the URI given is a full URI, it replaces this one.
  1669. copyURI(uriReference);
  1670. return true;
  1671. }
  1672. var thisPath:String, thatPath:String;
  1673. var thisParts:Array, thatParts:Array;
  1674. var thisIsDir:Boolean = false, thatIsDir:Boolean = false;
  1675. var thisIsAbs:Boolean = false, thatIsAbs:Boolean = false;
  1676. var lastIsDotOperation:Boolean = false;
  1677. var curDir:String;
  1678. var i:int;
  1679. thisPath = this.path;
  1680. thatPath = uriReference.path;
  1681. if (thisPath.length > 0)
  1682. thisParts = thisPath.split("/");
  1683. else
  1684. thisParts = new Array();
  1685. if (thatPath.length > 0)
  1686. thatParts = thatPath.split("/");
  1687. else
  1688. thatParts = new Array();
  1689. if (thisParts.length > 0 && thisParts[0] == "")
  1690. {
  1691. thisIsAbs = true;
  1692. thisParts.shift(); // pop the first one off the array
  1693. }
  1694. if (thisParts.length > 0 && thisParts[thisParts.length - 1] == "")
  1695. {
  1696. thisIsDir = true;
  1697. thisParts.pop(); // pop the last one off the array
  1698. }
  1699. if (thatParts.length > 0 && thatParts[0] == "")
  1700. {
  1701. thatIsAbs = true;
  1702. thatParts.shift(); // pop the first one off the array
  1703. }
  1704. if (thatParts.length > 0 && thatParts[thatParts.length - 1] == "")
  1705. {
  1706. thatIsDir = true;
  1707. thatParts.pop(); // pop the last one off the array
  1708. }
  1709. if (thatIsAbs)
  1710. {
  1711. // The reference is an absolute path (starts with a slash).
  1712. // It replaces this path wholesale.
  1713. this.path = uriReference.path;
  1714. // And it inherits the query and fragment
  1715. this.queryRaw = uriReference.queryRaw;
  1716. this.fragment = uriReference.fragment;
  1717. return true;
  1718. }
  1719. else if (thatParts.length == 0 && uriReference.query == "")
  1720. {
  1721. // The reference must have only been a fragment. Fragments just
  1722. // get appended to whatever the current path is. We don't want
  1723. // to overwrite any query that may already exist, so this case
  1724. // only takes on the new fragment.
  1725. this.fragment = uriReference.fragment;
  1726. return true;
  1727. }
  1728. else if (thisIsDir == false && thisParts.length > 0)
  1729. {
  1730. // This path ends in a file. It goes away no matter what.
  1731. thisParts.pop();
  1732. }
  1733. // By default, this assumes the query and fragment of the reference
  1734. this.queryRaw = uriReference.queryRaw;
  1735. this.fragment = uriReference.fragment;
  1736. // Append the parts of the path from the passed in reference
  1737. // to this object's path.
  1738. thisParts = thisParts.concat(thatParts);
  1739. for(i = 0; i < thisParts.length; i++)
  1740. {
  1741. curDir = thisParts[i];
  1742. lastIsDotOperation = false;
  1743. if (curDir == ".")
  1744. {
  1745. thisParts.splice(i, 1);
  1746. i = i - 1; // account for removing this item
  1747. lastIsDotOperation = true;
  1748. }
  1749. else if (curDir == "..")
  1750. {
  1751. if (i >= 1)
  1752. {
  1753. if (thisParts[i - 1] == "..")
  1754. {
  1755. // If the previous is a "..", we must have skipped
  1756. // it due to this URI being relative. We can't
  1757. // collapse leading ".."s in a relative URI, so
  1758. // do nothing.
  1759. }
  1760. else
  1761. {
  1762. thisParts.splice(i - 1, 2);
  1763. i = i - 2; // move back to account for the 2 we removed
  1764. }
  1765. }
  1766. else
  1767. {
  1768. // This is the first thing in the path.
  1769. if (isRelative())
  1770. {
  1771. // We can't collapse leading ".."s in a relative
  1772. // path. Do noting.
  1773. }
  1774. else
  1775. {
  1776. // This is an abnormal case. We have dot-dotted up
  1777. // past the base of our "file system". This is a
  1778. // case where we had a /path/like/this.htm and were
  1779. // given a path to chdir to like this:
  1780. // ../../../../../../mydir
  1781. // Obviously, it has too many ".." and will take us
  1782. // up beyond the top of the URI. However, according
  1783. // RFC 2396 Appendix C.2, we should try to handle
  1784. // these abnormal cases appropriately. In this case,
  1785. // we will do what UNIX command lines do if you are
  1786. // at the root (/) of the filesystem and execute:
  1787. // # cd ../../../../../bin
  1788. // Which will put you in /bin. Essentially, the extra
  1789. // ".."'s will just get eaten.
  1790. thisParts.splice(i, 1);
  1791. i = i - 1; // account for the ".." we just removed
  1792. }
  1793. }
  1794. lastIsDotOperation = true;
  1795. }
  1796. }
  1797. var finalPath:String = "";
  1798. // If the last thing in the path was a "." or "..", then this thing is a
  1799. // directory. If the last thing isn't a dot-op, then we don't want to
  1800. // blow away any information about the directory (hence the "|=" binary
  1801. // assignment).
  1802. thatIsDir = thatIsDir || lastIsDotOperation;
  1803. // Reconstruct the path with the abs/dir info we have
  1804. finalPath = joinPath(thisParts, thisIsAbs, thatIsDir);
  1805. // Set the path (automatically escaping it)
  1806. this.path = finalPath;
  1807. return true;
  1808. }
  1809. /**
  1810. * @private
  1811. * Join an array of path parts back into a URI style path string.
  1812. * This is used by the various path logic functions to recombine
  1813. * a path. This is different than the standard Array.join()
  1814. * function because we need to take into account the starting and
  1815. * ending path delimiters if this is an absolute path or a
  1816. * directory.
  1817. *
  1818. * @param parts the Array that contains strings of each path part.
  1819. * @param isAbs true if the given path is absolute
  1820. * @param isDir true if the given path is a directory
  1821. *
  1822. * @return the combined path string.
  1823. */
  1824. protected function joinPath(parts:Array, isAbs:Boolean, isDir:Boolean) : String
  1825. {
  1826. var pathStr:String = "";
  1827. var i:int;
  1828. for (i = 0; i < parts.length; i++)
  1829. {
  1830. if (pathStr.length > 0)
  1831. pathStr += "/";
  1832. pathStr += parts[i];
  1833. }
  1834. // If this path is a directory, tack on the directory delimiter,
  1835. // but only if the path contains something. Adding this to an
  1836. // empty path would make it "/", which is an absolute path that
  1837. // starts at the root.
  1838. if (isDir && pathStr.length > 0)
  1839. pathStr += "/";
  1840. if (isAbs)
  1841. pathStr = "/" + pathStr;
  1842. return pathStr;
  1843. }
  1844. /**
  1845. * Given an absolute URI, make this relative URI absolute using
  1846. * the given URI as a base. This URI instance must be relative
  1847. * and the base_uri must be absolute.
  1848. *
  1849. * @param base_uri URI to use as the base from which to make
  1850. * this relative URI into an absolute URI.
  1851. *
  1852. * @return true if successful, false otherwise.
  1853. */
  1854. public function makeAbsoluteURI(base_uri:URI) : Boolean
  1855. {
  1856. if (isAbsolute() || base_uri.isRelative())
  1857. {
  1858. // This URI needs to be relative, and the base needs to be
  1859. // absolute otherwise we won't know what to do!
  1860. return false;
  1861. }
  1862. // Make a copy of the base URI. We don't want to modify
  1863. // the passed URI.
  1864. var base:URI = new URI();
  1865. base.copyURI(base_uri);
  1866. // ChDir on the base URI. This will preserve any query
  1867. // and fragment we have.
  1868. if (base.chdir(toString()) == false)
  1869. return false;
  1870. // It worked, so copy the base into this one
  1871. copyURI(base);
  1872. return true;
  1873. }
  1874. /**
  1875. * Given a URI to use as a base from which this object should be
  1876. * relative to, convert this object into a relative URI. For example,
  1877. * if you have:
  1878. *
  1879. * <listing>
  1880. * var uri1:URI = new URI("http://something.com/path/to/some/file.html");
  1881. * var uri2:URI = new URI("http://something.com/path/to/another/file.html");
  1882. *
  1883. * uri1.MakeRelativePath(uri2);</listing>
  1884. *
  1885. * <p>uri1 will have a final value of "../some/file.html"</p>
  1886. *
  1887. * <p>Note! This function is brute force. If you have two URI's
  1888. * that are completely unrelated, this will still attempt to make
  1889. * the relative URI. In that case, you will most likely get a
  1890. * relative path that looks something like:</p>
  1891. *
  1892. * <p>../../../../../../some/path/to/my/file.html</p>
  1893. *
  1894. * @param base_uri the URI from which to make this URI relative
  1895. *
  1896. * @return true if successful, false if the base_uri and this URI
  1897. * are not related, of if error.
  1898. */
  1899. public function makeRelativeURI(base_uri:URI, caseSensitive:Boolean = true) : Boolean
  1900. {
  1901. var base:URI = new URI();
  1902. base.copyURI(base_uri);
  1903. var thisParts:Array, thatParts:Array;
  1904. var finalParts:Array = new Array();
  1905. var thisPart:String, thatPart:String, finalPath:String;
  1906. var pathStr:String = this.path;
  1907. var queryStr:String = this.queryRaw;
  1908. var fragmentStr:String = this.fragment;
  1909. var i:int;
  1910. var diff:Boolean = false;
  1911. var isDir:Boolean = false;
  1912. if (isRelative())
  1913. {
  1914. // We're already relative.
  1915. return true;
  1916. }
  1917. if (base.isRelative())
  1918. {
  1919. // The base is relative. A relative base doesn't make sense.
  1920. return false;
  1921. }
  1922. if ( (isOfType(base_uri.scheme) == false) ||
  1923. (this.authority != base_uri.authority) )
  1924. {
  1925. // The schemes and/or authorities are different. We can't
  1926. // make a relative path to something that is completely
  1927. // unrelated.
  1928. return false;
  1929. }
  1930. // Record the state of this URI
  1931. isDir = isDirectory();
  1932. // We are based of the directory of the given URI. We need to
  1933. // make sure the URI is pointing to a directory. Changing
  1934. // directory to "." will remove any file name if the base is
  1935. // not a directory.
  1936. base.chdir(".");
  1937. thisParts = pathStr.split("/");
  1938. thatParts = base.path.split("/");
  1939. if (thisParts.length > 0 && thisParts[0] == "")
  1940. thisParts.shift();
  1941. if (thisParts.length > 0 && thisParts[thisParts.length - 1] == "")
  1942. {
  1943. isDir = true;
  1944. thisParts.pop();
  1945. }
  1946. if (thatParts.length > 0 && thatParts[0] == "")
  1947. thatParts.shift();
  1948. if (thatParts.length > 0 && thatParts[thatParts.length - 1] == "")
  1949. thatParts.pop();
  1950. // Now that we have the paths split into an array of directories,
  1951. // we can compare the two paths. We start from the left of side
  1952. // of the path and start comparing. When we either run out of
  1953. // directories (one path is longer than the other), or we find
  1954. // a directory that is different, we stop. The remaining parts
  1955. // of each path is then used to determine the relative path. For
  1956. // example, lets say we have:
  1957. // path we want to make relative: /a/b/c/d/e.txt
  1958. // path to use as base for relative: /a/b/f/
  1959. //
  1960. // This loop will start at the left, and remove directories
  1961. // until we get a mismatch or run off the end of one of them.
  1962. // In this example, the result will be:
  1963. // c/d/e.txt
  1964. // f
  1965. //
  1966. // For every part left over in the base path, we prepend a ".."
  1967. // to the relative to get the final path:
  1968. // ../c/d/e.txt
  1969. while(thatParts.length > 0)
  1970. {
  1971. if (thisParts.length == 0)
  1972. {
  1973. // we matched all there is to match, we are done.
  1974. // This is the case where "this" object is a parent
  1975. // path of the given URI. eg:
  1976. // this.path = /a/b/ (thisParts)
  1977. // base.path = /a/b/c/d/e/ (thatParts)
  1978. break;
  1979. }
  1980. thisPart = thisParts[0];
  1981. thatPart = thatParts[0];
  1982. if (compareStr(thisPart, thatPart, caseSensitive))
  1983. {
  1984. thisParts.shift();
  1985. thatParts.shift();
  1986. }
  1987. else
  1988. break;
  1989. }
  1990. // If there are any path info left from the base URI, that means
  1991. // **this** object is above the given URI in the file tree. For
  1992. // each part left over in the given URI, we need to move up one
  1993. // directory to get where we are.
  1994. var dotdot:String = "..";
  1995. for (i = 0; i < thatParts.length; i++)
  1996. {
  1997. finalParts.push(dotdot);
  1998. }
  1999. // Append the parts of this URI to any dot-dot's we have
  2000. finalParts = finalParts.concat(thisParts);
  2001. // Join the parts back into a path
  2002. finalPath = joinPath(finalParts, false /* not absolute */, isDir);
  2003. if (finalPath.length == 0)
  2004. {
  2005. // The two URI's are exactly the same. The proper relative
  2006. // path is:
  2007. finalPath = "./";
  2008. }
  2009. // Set the parts of the URI, preserving the original query and
  2010. // fragment parts.
  2011. setParts("", "", "", finalPath, queryStr, fragmentStr);
  2012. return true;
  2013. }
  2014. /**
  2015. * Given a string, convert it to a URI. The string could be a
  2016. * full URI that is improperly escaped, a malformed URI (e.g.
  2017. * missing a protocol like "www.something.com"), a relative URI,
  2018. * or any variation there of.
  2019. *
  2020. * <p>The intention of this function is to take anything that a
  2021. * user might manually enter as a URI/URL and try to determine what
  2022. * they mean. This function differs from the URI constructor in
  2023. * that it makes some assumptions to make it easy to import user
  2024. * entered URI data.</p>
  2025. *
  2026. * <p>This function is intended to be a helper function.
  2027. * It is not all-knowning and will probably make mistakes
  2028. * when attempting to parse a string of unknown origin. If
  2029. * your application is receiving input from the user, your
  2030. * application should already have a good idea what the user
  2031. * should be entering, and your application should be
  2032. * pre-processing the user's input to make sure it is well formed
  2033. * before passing it to this function.</p>
  2034. *
  2035. * <p>It is assumed that the string given to this function is
  2036. * something the user may have manually entered. Given this,
  2037. * the URI string is probably unescaped or improperly escaped.
  2038. * This function will attempt to properly escape the URI by
  2039. * using forceEscape(). The result is that a toString() call
  2040. * on a URI that was created from unknownToURI() may not match
  2041. * the input string due to the difference in escaping.</p>
  2042. *
  2043. * @param unknown a potential URI string that should be parsed
  2044. * and loaded into this object.
  2045. * @param defaultScheme if it is determined that the passed string
  2046. * looks like a URI, but it is missing the scheme part, this
  2047. * string will be used as the missing scheme.
  2048. *
  2049. * @return true if the given string was successfully parsed into
  2050. * a valid URI object, false otherwise.
  2051. */
  2052. public function unknownToURI(unknown:String, defaultScheme:String = "http") : Boolean
  2053. {
  2054. var temp:String;
  2055. if (unknown.length == 0)
  2056. {
  2057. this.initialize();
  2058. return false;
  2059. }
  2060. // Some users love the backslash key. Fix it.
  2061. unknown = unknown.replace(/\\/g, "/");
  2062. // Check for any obviously missing scheme.
  2063. if (unknown.length >= 2)
  2064. {
  2065. temp = unknown.substr(0, 2);
  2066. if (temp == "//")
  2067. unknown = defaultScheme + ":" + unknown;
  2068. }
  2069. if (unknown.length >= 3)
  2070. {
  2071. temp = unknown.substr(0, 3);
  2072. if (temp == "://")
  2073. unknown = defaultScheme + unknown;
  2074. }
  2075. // Try parsing it as a normal URI
  2076. var uri:URI = new URI(unknown);
  2077. if (uri.isHierarchical() == false)
  2078. {
  2079. if (uri.scheme == UNKNOWN_SCHEME)
  2080. {
  2081. this.initialize();
  2082. return false;
  2083. }
  2084. // It's a non-hierarchical URI
  2085. copyURI(uri);
  2086. forceEscape();
  2087. return true;
  2088. }
  2089. else if ((uri.scheme != UNKNOWN_SCHEME) &&
  2090. (uri.scheme.length > 0))
  2091. {
  2092. if ( (uri.authority.length > 0) ||
  2093. (uri.scheme == "file") )
  2094. {
  2095. // file://... URI
  2096. copyURI(uri);
  2097. forceEscape(); // ensure proper escaping
  2098. return true;
  2099. }
  2100. else if (uri.authority.length == 0 && uri.path.length == 0)
  2101. {
  2102. // It's is an incomplete URI (eg "http://")
  2103. setParts(uri.scheme, "", "", "", "", "");
  2104. return false;
  2105. }
  2106. }
  2107. else
  2108. {
  2109. // Possible relative URI. We can only detect relative URI's
  2110. // that start with "." or "..". If it starts with something
  2111. // else, the parsing is ambiguous.
  2112. var path:String = uri.path;
  2113. if (path == ".." || path == "." ||
  2114. (path.length >= 3 && path.substr(0, 3) == "../") ||
  2115. (path.length >= 2 && path.substr(0, 2) == "./") )
  2116. {
  2117. // This is a relative URI.
  2118. copyURI(uri);
  2119. forceEscape();
  2120. return true;
  2121. }
  2122. }
  2123. // Ok, it looks like we are just a normal URI missing the scheme. Tack
  2124. // on the scheme.
  2125. uri = new URI(defaultScheme + "://" + unknown);
  2126. // Check to see if we are good now
  2127. if (uri.scheme.length > 0 && uri.authority.length > 0)
  2128. {
  2129. // It was just missing the scheme.
  2130. copyURI(uri);
  2131. forceEscape(); // Make sure we are properly encoded.
  2132. return true;
  2133. }
  2134. // don't know what this is
  2135. this.initialize();
  2136. return false;
  2137. }
  2138. } // end URI class
  2139. } // end package