URI.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /**
  2. * URI.js
  3. *
  4. * Copyright, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://www.tinymce.com/license
  8. * Contributing: http://www.tinymce.com/contributing
  9. */
  10. /**
  11. * This class handles parsing, modification and serialization of URI/URL strings.
  12. * @class tinymce.util.URI
  13. */
  14. define("tinymce/util/URI", [
  15. "tinymce/util/Tools"
  16. ], function(Tools) {
  17. var each = Tools.each, trim = Tools.trim,
  18. DEFAULT_PORTS = {
  19. 'ftp': 21,
  20. 'http': 80,
  21. 'https': 443,
  22. 'mailto': 25
  23. };
  24. /**
  25. * Constructs a new URI instance.
  26. *
  27. * @constructor
  28. * @method URI
  29. * @param {String} url URI string to parse.
  30. * @param {Object} settings Optional settings object.
  31. */
  32. function URI(url, settings) {
  33. var self = this, baseUri, base_url;
  34. // Trim whitespace
  35. url = trim(url);
  36. // Default settings
  37. settings = self.settings = settings || {};
  38. // Strange app protocol that isn't http/https or local anchor
  39. // For example: mailto,skype,tel etc.
  40. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  41. self.source = url;
  42. return;
  43. }
  44. var isProtocolRelative = url.indexOf('//') === 0;
  45. // Absolute path with no host, fake host and protocol
  46. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  47. url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url;
  48. }
  49. // Relative path http:// or protocol relative //path
  50. if (!/^[\w\-]*:?\/\//.test(url)) {
  51. base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory;
  52. if (settings.base_uri.protocol === "") {
  53. url = '//mce_host' + self.toAbsPath(base_url, url);
  54. } else {
  55. url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url);
  56. }
  57. }
  58. // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
  59. url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
  60. /*jshint maxlen: 255 */
  61. /*eslint max-len: 0 */
  62. url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  63. each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
  64. var part = url[i];
  65. // Zope 3 workaround, they use @@something
  66. if (part) {
  67. part = part.replace(/\(mce_at\)/g, '@@');
  68. }
  69. self[v] = part;
  70. });
  71. baseUri = settings.base_uri;
  72. if (baseUri) {
  73. if (!self.protocol) {
  74. self.protocol = baseUri.protocol;
  75. }
  76. if (!self.userInfo) {
  77. self.userInfo = baseUri.userInfo;
  78. }
  79. if (!self.port && self.host === 'mce_host') {
  80. self.port = baseUri.port;
  81. }
  82. if (!self.host || self.host === 'mce_host') {
  83. self.host = baseUri.host;
  84. }
  85. self.source = '';
  86. }
  87. if (isProtocolRelative) {
  88. self.protocol = '';
  89. }
  90. //t.path = t.path || '/';
  91. }
  92. URI.prototype = {
  93. /**
  94. * Sets the internal path part of the URI.
  95. *
  96. * @method setPath
  97. * @param {string} path Path string to set.
  98. */
  99. setPath: function(path) {
  100. var self = this;
  101. path = /^(.*?)\/?(\w+)?$/.exec(path);
  102. // Update path parts
  103. self.path = path[0];
  104. self.directory = path[1];
  105. self.file = path[2];
  106. // Rebuild source
  107. self.source = '';
  108. self.getURI();
  109. },
  110. /**
  111. * Converts the specified URI into a relative URI based on the current URI instance location.
  112. *
  113. * @method toRelative
  114. * @param {String} uri URI to convert into a relative path/URI.
  115. * @return {String} Relative URI from the point specified in the current URI instance.
  116. * @example
  117. * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm
  118. * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm');
  119. */
  120. toRelative: function(uri) {
  121. var self = this, output;
  122. if (uri === "./") {
  123. return uri;
  124. }
  125. uri = new URI(uri, {base_uri: self});
  126. // Not on same domain/port or protocol
  127. if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port ||
  128. (self.protocol != uri.protocol && uri.protocol !== "")) {
  129. return uri.getURI();
  130. }
  131. var tu = self.getURI(), uu = uri.getURI();
  132. // Allow usage of the base_uri when relative_urls = true
  133. if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) {
  134. return tu;
  135. }
  136. output = self.toRelPath(self.path, uri.path);
  137. // Add query
  138. if (uri.query) {
  139. output += '?' + uri.query;
  140. }
  141. // Add anchor
  142. if (uri.anchor) {
  143. output += '#' + uri.anchor;
  144. }
  145. return output;
  146. },
  147. /**
  148. * Converts the specified URI into a absolute URI based on the current URI instance location.
  149. *
  150. * @method toAbsolute
  151. * @param {String} uri URI to convert into a relative path/URI.
  152. * @param {Boolean} noHost No host and protocol prefix.
  153. * @return {String} Absolute URI from the point specified in the current URI instance.
  154. * @example
  155. * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm
  156. * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm');
  157. */
  158. toAbsolute: function(uri, noHost) {
  159. uri = new URI(uri, {base_uri: this});
  160. return uri.getURI(noHost && this.isSameOrigin(uri));
  161. },
  162. /**
  163. * Determine whether the given URI has the same origin as this URI. Based on RFC-6454.
  164. * Supports default ports for protocols listed in DEFAULT_PORTS. Unsupported protocols will fail safe: they
  165. * won't match, if the port specifications differ.
  166. *
  167. * @method isSameOrigin
  168. * @param {tinymce.util.URI} uri Uri instance to compare.
  169. * @returns {Boolean} True if the origins are the same.
  170. */
  171. isSameOrigin: function(uri) {
  172. if (this.host == uri.host && this.protocol == uri.protocol){
  173. if (this.port == uri.port) {
  174. return true;
  175. }
  176. var defaultPort = DEFAULT_PORTS[this.protocol];
  177. if (defaultPort && ((this.port || defaultPort) == (uri.port || defaultPort))) {
  178. return true;
  179. }
  180. }
  181. return false;
  182. },
  183. /**
  184. * Converts a absolute path into a relative path.
  185. *
  186. * @method toRelPath
  187. * @param {String} base Base point to convert the path from.
  188. * @param {String} path Absolute path to convert into a relative path.
  189. */
  190. toRelPath: function(base, path) {
  191. var items, breakPoint = 0, out = '', i, l;
  192. // Split the paths
  193. base = base.substring(0, base.lastIndexOf('/'));
  194. base = base.split('/');
  195. items = path.split('/');
  196. if (base.length >= items.length) {
  197. for (i = 0, l = base.length; i < l; i++) {
  198. if (i >= items.length || base[i] != items[i]) {
  199. breakPoint = i + 1;
  200. break;
  201. }
  202. }
  203. }
  204. if (base.length < items.length) {
  205. for (i = 0, l = items.length; i < l; i++) {
  206. if (i >= base.length || base[i] != items[i]) {
  207. breakPoint = i + 1;
  208. break;
  209. }
  210. }
  211. }
  212. if (breakPoint === 1) {
  213. return path;
  214. }
  215. for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) {
  216. out += "../";
  217. }
  218. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  219. if (i != breakPoint - 1) {
  220. out += "/" + items[i];
  221. } else {
  222. out += items[i];
  223. }
  224. }
  225. return out;
  226. },
  227. /**
  228. * Converts a relative path into a absolute path.
  229. *
  230. * @method toAbsPath
  231. * @param {String} base Base point to convert the path from.
  232. * @param {String} path Relative path to convert into an absolute path.
  233. */
  234. toAbsPath: function(base, path) {
  235. var i, nb = 0, o = [], tr, outPath;
  236. // Split paths
  237. tr = /\/$/.test(path) ? '/' : '';
  238. base = base.split('/');
  239. path = path.split('/');
  240. // Remove empty chunks
  241. each(base, function(k) {
  242. if (k) {
  243. o.push(k);
  244. }
  245. });
  246. base = o;
  247. // Merge relURLParts chunks
  248. for (i = path.length - 1, o = []; i >= 0; i--) {
  249. // Ignore empty or .
  250. if (path[i].length === 0 || path[i] === ".") {
  251. continue;
  252. }
  253. // Is parent
  254. if (path[i] === '..') {
  255. nb++;
  256. continue;
  257. }
  258. // Move up
  259. if (nb > 0) {
  260. nb--;
  261. continue;
  262. }
  263. o.push(path[i]);
  264. }
  265. i = base.length - nb;
  266. // If /a/b/c or /
  267. if (i <= 0) {
  268. outPath = o.reverse().join('/');
  269. } else {
  270. outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
  271. }
  272. // Add front / if it's needed
  273. if (outPath.indexOf('/') !== 0) {
  274. outPath = '/' + outPath;
  275. }
  276. // Add traling / if it's needed
  277. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  278. outPath += tr;
  279. }
  280. return outPath;
  281. },
  282. /**
  283. * Returns the full URI of the internal structure.
  284. *
  285. * @method getURI
  286. * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false.
  287. */
  288. getURI: function(noProtoHost) {
  289. var s, self = this;
  290. // Rebuild source
  291. if (!self.source || noProtoHost) {
  292. s = '';
  293. if (!noProtoHost) {
  294. if (self.protocol) {
  295. s += self.protocol + '://';
  296. } else {
  297. s += '//';
  298. }
  299. if (self.userInfo) {
  300. s += self.userInfo + '@';
  301. }
  302. if (self.host) {
  303. s += self.host;
  304. }
  305. if (self.port) {
  306. s += ':' + self.port;
  307. }
  308. }
  309. if (self.path) {
  310. s += self.path;
  311. }
  312. if (self.query) {
  313. s += '?' + self.query;
  314. }
  315. if (self.anchor) {
  316. s += '#' + self.anchor;
  317. }
  318. self.source = s;
  319. }
  320. return self.source;
  321. }
  322. };
  323. return URI;
  324. });