Geocaching.com + Project-GC

Adds links and data to Geocaching.com to make it collaborate with PGC

2022-12-13 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

  1. /* global $: true */
  2. /* global waitForKeyElements: true */
  3. /* global GM_xmlhttpRequest: true */
  4. /* global GM_getValue: true */
  5. /* global GM_setValue: true */
  6. /* global unsafeWindow: true */
  7. /* globals i18next, i18nextXHRBackend, i18nextBrowserLanguageDetector */
  8. // jshint newcap:false
  9. // jshint multistr:true
  10.  
  11. // ==UserScript==
  12. // @author Ground Zero Communications AB
  13. // @license The MIT License (MIT)
  14. // @name Geocaching.com + Project-GC
  15. // @namespace PGC
  16. // @description Adds links and data to Geocaching.com to make it collaborate with PGC
  17. // @icon https://project-gc.com/favicon-32x32.png
  18. // @match http://www.geocaching.com/*
  19. // @match https://www.geocaching.com/*
  20. // @exclude https://www.geocaching.com/profile/profilecontent.html
  21. // @version 2.4.5
  22. // @require http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
  23. // @require https://greatest.deepsurf.us/scripts/383527-wait-for-key-elements/code/Wait_for_key_elements.js?version=701631
  24. // @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
  25. // @require https://unpkg.com/i18next@21.9.1/i18next.min.js
  26. // @require https://unpkg.com/i18next-xhr-backend@3.2.2/i18nextXHRBackend.js
  27. // @require https://unpkg.com/i18next-browser-languagedetector@6.1.4/i18nextBrowserLanguageDetector.js
  28. // @grant GM_xmlhttpRequest
  29. // @grant GM_setValue
  30. // @grant GM_getValue
  31. // @grant GM_addStyle
  32. // @grant GM.xmlHttpRequest
  33. // @grant GM.setValue
  34. // @grant GM.getValue
  35. // @connect maps.googleapis.com
  36. // @connect project-gc.com
  37. // @connect img.geocaching.com
  38. // @connect s3.amazonaws.com
  39. // @connect nominatim.openstreetmap.org
  40. // @connect *
  41. // ==/UserScript==
  42.  
  43.  
  44. // MIT License
  45. // Copyright (c) 2014 Ground Zero Communications AB
  46. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
  47. // (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
  48. // merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished
  49. // to do so, subject to the following conditions:
  50. // The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial
  51. // portions of the Software.
  52. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  53. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  54. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  55. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  56.  
  57. (function() {
  58.  
  59. 'use strict';
  60.  
  61. var pgcUrl = 'https://project-gc.com/',
  62. cdnDomain = 'https://cdn2.project-gc.com/',
  63. pgcApiUrl = pgcUrl + 'api/gm/v1/',
  64. externalLinkIcon = 'https://cdn2.project-gc.com/images/external_small.png',
  65. galleryLinkIcon = 'https://cdn2.project-gc.com/images/pictures_16.png',
  66. challengeCheckerSuccessIcon = 'https://cdn2.project-gc.com/images/check16.png',
  67. challengeCheckerFailIcon = 'https://cdn2.project-gc.com/images/cancel16.png',
  68. mapLinkIcon = 'https://cdn2.project-gc.com/images/map_app_16.png',
  69. loggedIn = null,
  70. subscription = null,
  71. pgcUsername = null,
  72. // Issue 113; fixed 2022-08-30 (Units of elevation obtained from Project-GC)
  73. imperialFlag = null,
  74. gccomUsername = null,
  75. latestLogs = [],
  76. latestLogsAlert = false,
  77. settings = {},
  78. path = window.location.pathname,
  79. challengeCheckerResults = null,
  80. _language = "";
  81.  
  82.  
  83. // Don't run the script for iframes
  84. if (window.top == window.self) {
  85. loadTranslations(); // Will call Main() when completed
  86. }
  87.  
  88. function Main() {
  89. ReadSettings();
  90. CheckPGCLogin();
  91. }
  92.  
  93. function loadTranslations() {
  94. i18next
  95. .use(i18nextXHRBackend)
  96. .use(i18nextBrowserLanguageDetector)
  97. .init({
  98. supportedLngs: ['ca_ES', 'cs_CZ', 'da_DK', 'de_DE', 'en_AU', 'en_CA', 'en_GB', 'en_US', 'es_ES', 'fi_FI', 'fr_FR', 'hu_HU', 'it_IT', 'ko_KR', 'lv_LV', 'nb_NO', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'sk_SK', 'sl_SI', 'sv_SE', 'tr_TR', 'zh_TW'],
  99. whitelist: ['ca_ES', 'cs_CZ', 'da_DK', 'de_DE', 'en_AU', 'en_CA', 'en_GB', 'en_US', 'es_ES', 'fi_FI', 'fr_FR', 'hu_HU', 'it_IT', 'ko_KR', 'lv_LV', 'nb_NO', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'sk_SK', 'sl_SI', 'sv_SE', 'tr_TR', 'zh_TW'],
  100. preload: ['ca_ES', 'cs_CZ', 'da_DK', 'de_DE', 'en_AU', 'en_CA', 'en_GB', 'en_US', 'es_ES', 'fi_FI', 'fr_FR', 'hu_HU', 'it_IT', 'ko_KR', 'lv_LV', 'nb_NO', 'nl_NL', 'pl_PL', 'pt_BR', 'pt_PT', 'sk_SK', 'sl_SI', 'sv_SE', 'tr_TR', 'zh_TW'],
  101. fallbackLng: ['en_US', 'nb_NO', 'sv_SE'],
  102. 'lng': navigator.language || navigator.userLanguage,
  103. ns: ['userscript'],
  104. defaultNS: ['userscript'],
  105. backend: {
  106. loadPath: pgcUrl + 'locale/{{ns}}.php?lng={{lng}}',
  107. crossDomain: true
  108. }
  109. }, (err, t) => {
  110. if (err) {
  111. if (err.indexOf("failed parsing" > -1)) {
  112. i18next.changeLanguage('en_US');
  113.  
  114. return loadTranslations();
  115. }
  116. return console.log("Error occurred when loading language data", err);
  117. }
  118.  
  119. Main();
  120. });
  121. }
  122. function Router() {
  123. if (path.match(/^\/geocache\/.*/) !== null) {
  124. Page_CachePage();
  125. } else if (path.match(/^\/seek\/cache_details\.aspx.*/) !== null) {
  126. Page_CachePage();
  127. } else if (path.match(/^\/seek\/cache_logbook\.aspx.*/) !== null) {
  128. Page_Logbook();
  129. } else if (path.match(/^\/bookmarks\/.*/) !== null) {
  130. Page_Bookmarks();
  131. } else if (path.match(/^\/map\/.*/) !== null) {
  132. Page_Map();
  133. } else if(path.match(/^\/seek\/gallery\.aspx.*/) !== null) {
  134. Page_Gallery();
  135. } else if(path.match(/^\/profile\/.*/) !== null) {
  136. Page_Profile();
  137. } else if (path.match(/^\/account\/drafts/) !== null) {
  138. Page_Drafts();
  139. } else if (path.match(/^\/account\/messagecenter/) !== null) {
  140. Page_Messagecenter();
  141. } else if (path.match(/^\/seek\/cdpf\.aspx/) !== null) {
  142. Page_PrintCachePage();
  143. }
  144. }
  145.  
  146. function GetSettingsItems() {
  147. var items = {
  148. showVGPS: {
  149. title: i18next.t('menu.showvpgs'),
  150. default: true
  151. },
  152. addChallengeCheckers: {
  153. title: i18next.t('menu.addcc'),
  154. default: true
  155. },
  156. makeCopyFriendly: {
  157. title: i18next.t('menu.makeCopyFriendly'),
  158. default: true
  159. },
  160. addPgcMapLinks: {
  161. title: i18next.t('menu.addPgcMapLinks'),
  162. default: true
  163. },
  164. addLatestLogs: {
  165. title: i18next.t('menu.addLatestLogs'),
  166. default: true
  167. },
  168. cloneLogsPerType: {
  169. title: i18next.t('menu.cloneLogsPerType'),
  170. default: true
  171. },
  172. addPGCLocation: {
  173. title: i18next.t('menu.addPGCLocation'),
  174. default: true
  175. },
  176. addAddress: {
  177. title: i18next.t('menu.addAddress'),
  178. default: true
  179. },
  180. removeUTM: {
  181. title: i18next.t('menu.removeUTM'),
  182. default: true
  183. },
  184. addPgcFp: {
  185. title: i18next.t('menu.addPgcFp'),
  186. default: true
  187. },
  188. showWeekday: {
  189. title: i18next.t('menu.showWeekday'),
  190. default: true
  191. },
  192. profileStatsLinks: {
  193. title: i18next.t('menu.profileStatsLinks'),
  194. default: true
  195. },
  196. tidy: {
  197. title: i18next.t('menu.tidy'),
  198. default: true
  199. },
  200. collapseDownloads: {
  201. title: i18next.t('menu.collapseDownloads'),
  202. default: false
  203. },
  204. addPgcGalleryLinks: {
  205. title: i18next.t('menu.addPgcGalleryLinks'),
  206. default: true
  207. },
  208. addMapBookmarkListLinks: {
  209. title: i18next.t('menu.addMapBookmarkListLinks'),
  210. default: true
  211. },
  212. decryptHints: {
  213. title: i18next.t('menu.decryptHints'),
  214. default: true
  215. },
  216. addElevation: {
  217. title: i18next.t('menu.addElevation'),
  218. default: true
  219. },
  220. // Issue 113; fixed 2022-08-30 (Units of elevation obtained from Project-GC)
  221. removeDisclaimer: {
  222. title: i18next.t('menu.removeDisclaimer'),
  223. default: true
  224. },
  225. parseExifLocation: {
  226. title: i18next.t('menu.parseExifLocation'),
  227. default: true
  228. },
  229. addGeocacheLogsPerProfileCountry: {
  230. title: i18next.t('menu.addGeocacheLogsPerProfileCountry'),
  231. default: true
  232. },
  233. openDraftLogInSameWindow: {
  234. title: i18next.t('menu.openDraftLogInSameWindow'),
  235. default: true
  236. },
  237. cachenoteFont: {
  238. title: i18next.t('menu.cachenoteFont'),
  239. default: true
  240. },
  241. logbookLinks: {
  242. title: i18next.t('menu.logbookLinks'),
  243. default: true
  244. },
  245. addMyNumberOfLogs: {
  246. title: i18next.t('menu.addMyNumberOfLogs'),
  247. default: true
  248. },
  249. hideMapFromPrintCachePage: {
  250. title: i18next.t('menu.hideMapFromPrintCachePage'),
  251. default: true
  252. },
  253. addCachedChallengeCheckerResults: {
  254. title: i18next.t('menu.addCachedChallengeCheckerResults'),
  255. default: true
  256. },
  257. hideLogVoting: {
  258. title: i18next.t('menu.hideLogVoting'),
  259. default: false
  260. }
  261. };
  262. return items;
  263. }
  264.  
  265. async function ReadSettings() {
  266. settings = await GM.getValue('settings');
  267. if (typeof(settings) != 'undefined') {
  268. settings = JSON.parse(settings);
  269. if (settings === null) {
  270. settings = [];
  271. }
  272. } else {
  273. settings = [];
  274. }
  275.  
  276. var items = GetSettingsItems();
  277. for (var item in items) {
  278. if (typeof(settings[item]) == 'undefined') {
  279. settings[item] = items[item].default;
  280. }
  281. }
  282. }
  283.  
  284. function SaveSettings(e) {
  285. e.preventDefault();
  286. settings = {};
  287.  
  288. for (var item in GetSettingsItems()) {
  289. settings[item] = Boolean($('#pgcUserMenuForm input[name="' + item + '"]').is(':checked'));
  290. }
  291.  
  292. var json = JSON.stringify(settings);
  293. GM.setValue('settings', json);
  294.  
  295. $('#pgcUserMenuWarning').css('display', 'inherit');
  296. }
  297.  
  298. function IsSettingEnabled(setting) {
  299. return settings[setting];
  300. }
  301.  
  302. function MetersToFeet(meters) {
  303. return Math.round(meters * 3.28084);
  304. }
  305.  
  306. function FormatDistance(distance) {
  307. distance = parseInt(distance, 10);
  308. // Issue 113; fixed 2022-08-30 (Units of elevation obtained from Project-GC)
  309. distance = imperialFlag ? MetersToFeet(distance) : distance;
  310. distance = distance.toLocaleString();
  311.  
  312. return distance;
  313. }
  314.  
  315. function GetCoordinatesFromExif(exif) {
  316. var GPSLatitudeRef = EXIF.getTag(exif, "GPSLatitudeRef"),
  317. GPSLatitude = EXIF.getTag(exif, "GPSLatitude"),
  318. GPSLongitudeRef = EXIF.getTag(exif, "GPSLongitudeRef"),
  319. GPSLongitude = EXIF.getTag(exif, "GPSLongitude");
  320.  
  321. if (typeof(GPSLatitude) === 'undefined' || isNaN(GPSLatitude[0]) || isNaN(GPSLatitude[1]) || isNaN(GPSLatitude[1]) ||
  322. isNaN(GPSLongitude[0]) || isNaN(GPSLongitude[1]) || isNaN(GPSLongitude[1])) {
  323. return false;
  324. }
  325.  
  326. // Create a latitude DD.DDD
  327. var tmp = Number(GPSLatitude[0]) + Number(GPSLatitude[1]) / 60 + Number(GPSLatitude[2]) / 60 / 60,
  328. coords = '';
  329.  
  330. coords += GPSLatitudeRef;
  331. var d = Math.floor(tmp);
  332. if (d < 10) {
  333. coords += '0' + d;
  334. } else {
  335. coords += d;
  336. }
  337. tmp = (tmp - d) * 60;
  338. coords += ' ' + padLeft(tmp.toFixed(3), 6);
  339.  
  340. coords += ' ';
  341.  
  342. // Create a longitude DD.DDD
  343. var tmp = Number(GPSLongitude[0]) + Number(GPSLongitude[1]) / 60 + Number(GPSLongitude[2]) / 60 / 60;
  344.  
  345. coords += GPSLongitudeRef;
  346. var d = Math.floor(tmp);
  347. if (d < 10) {
  348. coords += '00' + d;
  349. } else if (GPSLongitude[0] < 100) {
  350. coords += '0' + d;
  351. } else {
  352. coords += d;
  353. }
  354. tmp = (tmp - d) * 60;
  355. coords += ' ' + padLeft(tmp.toFixed(3), 6);
  356.  
  357. return coords;
  358. }
  359.  
  360. /**
  361. * Check that we are authenticated at Project-GC.com, and that it's with the same username
  362. */
  363. function CheckPGCLogin() {
  364. GM.xmlHttpRequest({
  365. method: "GET",
  366. url: pgcApiUrl + 'GetMyUsername',
  367. onload: function(response) {
  368. var result = JSON.parse(response.responseText);
  369. if (result.status !== 'OK') {
  370. alert(response.responseText);
  371. return false;
  372. }
  373.  
  374. pgcUsername = result.data.username;
  375. // Issue 113 & #133; fixed 2022-09-04 (Units of elevation obtained from Project-GC)
  376. imperialFlag = result.data.imperialUnits;
  377. loggedIn = Boolean(result.data.loggedIn);
  378. subscription = Boolean(result.data.subscription);
  379. _language = result.data.locale; //untested code
  380. i18next.changeLanguage(_language);//untested code**
  381.  
  382. function waitForHeader(waitCount) {
  383. if ($('.user-menu')[0]) BuildPGCUserMenu();
  384. else {waitCount++; if (waitCount <= 1000) setTimeout(function(){waitForHeader(waitCount);}, 10);}
  385. }
  386. waitForHeader(0);
  387. Router();
  388. },
  389. onerror: function(response) {
  390. alert(response);
  391. return false;
  392. }
  393. });
  394. }
  395.  
  396. function BuildPGCUserMenu() {
  397. var loggedInContent, subscriptionContent = '';
  398.  
  399. gccomUsername = false;
  400. if ($('.username')[0]) {
  401. gccomUsername = $('.username').html();
  402. }
  403.  
  404. if (loggedIn === false) {
  405. loggedInContent = '<a href="' + pgcUrl + 'User/Login" target="_blank">' + i18next.t("header.not") + '</a>';
  406. } else {
  407. loggedInContent = '<a href="' + pgcUrl + 'ProfileStats/' + pgcUsername + '"><strong' + (pgcUsername != gccomUsername ? ' style="color: red;"' : '') + '>' + pgcUsername + '</strong></a>';
  408. subscriptionContent = '<a href="https://project-gc.com/Home/Membership" target="_blank">' + (subscription ? i18next.t("header.Paid") : i18next.t("header.Missing")) + ' ' + i18next.t("header.membership") + '</a>';
  409. }
  410.  
  411. // Issue 113; fixed 2022-08-30
  412. GM_addStyle('\
  413. #pgc .player-profile, #pgc_gclh .li-user-info {width: auto;}\
  414. #pgc .player-profile:hover {text-decoration: none;}\
  415. #pgc .player-profile a:hover {text-decoration: underline;}\
  416. #pgc .player-profile a {text-decoration: none;color: white;}\
  417. #pgc_gclh img:hover {cursor:pointer;}\
  418. #pgc_gclh .draft-indicator {display: none;}\
  419. #pgcUserMenuForm > li:hover, #pgcUserMenuForm_gclh > li:hover { background-color: #e3dfc9; }\
  420. #pgcUserMenuForm > li, #pgcUserMenuForm_gclh > li { display: block; }\
  421. #pgcUserMenuForm input[type="checkbox"], #pgcUserMenuForm_gclh input[type="checkbox"] { opacity: inherit; width: inherit; height:inherit; overflow:inherit; position:inherit; }\
  422. #pgcUserMenuForm button, #pgcUserMenuForm_gclh button { display: inline-block !important; background: #ede5dc url(images/ui-bg_flat_100_ede5dc_40x100.png) 50% 50% repeat-x !important; border: 1px solid #cab6a3 !important; border-radius: 4px; color: #584528 !important; text-decoration: none; width: auto !important; font-size: 14px; padding: 4px 6px !important;}\
  423. #pgcUserMenuForm button:hover, #pgcUserMenuForm_gclh button:hover { background: #e4d8cb url(images/ui-bgflag_100_e4d8cb_40x100.png) 50% 50% repeat-x !important; }\
  424. #pgcUserMenu, #pgcUserMenu_gclh { right: 1rem; }\
  425. #pgcUserMenu > form, #pgcUserMenu_gclh > form { background-color: white; color: #5f452a; }\
  426. .profile-panel .li-user-info {min-width: 160px;}\
  427. ');
  428.  
  429. var settings = '<ul id="pgcUserMenu" class="dropdown-menu menu-user submenu" style="display:none; z-index: 1005;"><form id="pgcUserMenuForm" style="display: block; columns: 2; font-size: 14px; background-color: #fff !important;">';
  430.  
  431. var items = GetSettingsItems();
  432. for (var item in items) {
  433. let isChecked = IsSettingEnabled(item) ? ' checked="checked"' : '';
  434. // Explicitly set the styles as some pages (i.e. https://www.geocaching.com/account/settings/profile) are missing the required css.
  435. settings += '<li style="margin: .2em 1em; white-space: nowrap; display: flex;"><label style="font-weight: inherit; margin-bottom: 0" for="' + item + '"><input type="checkbox" id="' + item + '" name="' + item + '"' + isChecked + ' >&nbsp;' + items[item].title + '</label>&nbsp;<small>(default: ' + items[item].default + ')</small></li>';
  436. }
  437.  
  438. settings += '\
  439. <li style="margin: .2em 1em; background: 0;">\
  440. <button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); document.getElementById(\'pgcUserMenu\').style.display=\"none\"; return false;">' + i18next.t("menu.Cancel") + '</button>\
  441. <button onclick="document.getElementById(\'pgcUserMenuForm\').reset(); return false;">' + i18next.t("menu.Reset") + '</button>\
  442. <button id="pgcUserMenuSave">' + i18next.t("menu.Save") + '</button>\
  443. </li>\
  444. <li id="pgcUserMenuWarning" style="display: none; margin: .5em 1em; color: red; background: 0;"><a href="#" onclick="location.reload();" style="color: red; padding: 0; text-decoration: underline; display: inline;">' + i18next.t("menu.Reload") + '</a> ' + i18next.t("menu.activate") + '</li>\
  445. </form>\
  446. </ul>';
  447.  
  448. let pgc = '<li id="pgc"><div class="player-profile">' + $('#gc-header .player-profile').html() + '</div></li>';
  449. $('.user-menu').prepend(pgc);
  450. // Icon
  451. $('#pgc div').prepend('<a href="' + pgcUrl + '"></a>');
  452. $('#pgc img').attr('src', 'https://cdn2.project-gc.com/favicon.ico');
  453. $('#pgc img').attr('style', 'border-radius:100%;');
  454. $('#pgc img').appendTo('#pgc a');
  455. // Username
  456. $('#pgc .username').html(loggedInContent);
  457. // Subscription
  458. $('#pgc .username + span').html(subscriptionContent);
  459.  
  460. // Menu Toggle
  461. let button = $('.toggle-user-menu').last().parent().clone();
  462. $(button).find('button').attr('id', 'pgcUserMenuButton');
  463. $(button).attr('id', 'pgcButton');
  464. $(button).append(settings);
  465. // Add Toggle Button
  466. $('#pgc').after(button);
  467.  
  468. $("#pgcUserMenuButton").click(function(e) {
  469. $('#pgcUserMenu').show();
  470. // Issue 108; fixed 2022-09-05 (Settings menu now reloading page)
  471. e.preventDefault();
  472. })
  473. $('body').click(function(e) {
  474. if (!$(e.target).parents('#pgcUserMenu')[0] && (!$(e.target).parents('#pgcButton')[0] && $("#pgcUserMenu").css('display') != 'none')) {
  475. $("#pgcUserMenu").hide();
  476. }
  477. })
  478.  
  479. $('#pgcUserMenuSave').click(function(e) {
  480. SaveSettings(e);
  481. });
  482.  
  483. // Workaround for users that also use the GClh
  484. function checkForGClh(waitCount) {
  485. if ($('#GClh_II_running')[0] && $('gclh_nav#ctl00_gcNavigation')[0]) {
  486. let gclh_pgc = '<li id="pgc_gclh" class="li-user"><div class="li-user-info">' + $($('.li-user')[0]).find('a').html() + '</div>'
  487. + '<button id="pgcUserMenuButton_gclh" class="li-user-toggle dropdown">' + $($('.li-user')[0]).find('button').html() + '</button>'
  488. + settings + '</li>';
  489. $('#ctl00_uxLoginStatus_divSignedIn').prepend(gclh_pgc);
  490. // Icon
  491. $('#pgc_gclh img').attr('src', 'https://cdn2.project-gc.com/favicon.ico');
  492. $('#pgc_gclh img').attr('style', 'border-radius:100%;');
  493. $('#pgc_gclh img')[0].onclick = function() {open(pgcUrl);};
  494. // User
  495. $('#pgc_gclh .user-name').html(loggedInContent);
  496. // Subscription
  497. $('#pgc_gclh .cache-count').html(subscriptionContent);
  498.  
  499.  
  500. // Rename the settings
  501. $('#pgc_gclh .dropdown-menu.menu-user').attr('id', 'pgcUserMenu_gclh');
  502. $('#pgc_gclh .dropdown-menu.menu-user form').attr('id', 'pgcUserMenuForm_gclh');
  503. $('#pgc_gclh .dropdown-menu.menu-user form li:nth-last-child(2) button:nth-last-child(1)').attr('id', 'pgcUserMenuSave_gclh');
  504. $('#pgc_gclh .dropdown-menu.menu-user form li:nth-last-child(1)').attr('id', 'pgcUserMenuWarning_gclh');
  505.  
  506. $("#pgcUserMenuButton_gclh").click(function(e) {
  507. e.preventDefault();
  508. $('#pgcUserMenu_gclh').toggle();
  509. })
  510.  
  511. $('#pgcUserMenuSave_gclh').click(function(e) {
  512. SaveSettings(e);
  513. });
  514.  
  515. } else {waitCount++; if (waitCount <= 1000) setTimeout(function(){checkForGClh(waitCount);}, 10);}
  516. }
  517. checkForGClh(0);
  518. }
  519.  
  520. /**
  521. * getGcCodeFromPage
  522. * @return string
  523. */
  524. function getGcCodeFromPage() {
  525. return $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode').html();
  526. }
  527.  
  528. /**
  529. * addToVGPS
  530. */
  531. function addToVGPS(gccode) {
  532. var listId = $('#comboVGPS').val(),
  533. url = null;
  534.  
  535. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  536. gccode = getGcCodeFromPage();
  537. }
  538.  
  539. url = pgcApiUrl + 'AddToVGPSList?listId=' + listId + '&gccode=' + gccode + '&sectionName=GM-script';
  540.  
  541.  
  542. GM.xmlHttpRequest({
  543. method: "GET",
  544. url: url,
  545. onload: function(response) {
  546. var result = JSON.parse(response.responseText),
  547. msg = (result.status === 'OK') ? i18next.t('vpgs.added') : i18next.t('vpgs.notadded');
  548.  
  549. $('#btnAddToVGPS').css('display', 'none');
  550. $('#btnRemoveFromVGPS').css('display', '');
  551.  
  552. alert(msg);
  553.  
  554. return true;
  555. },
  556. onerror: function(response) {
  557. console.log(response);
  558. return false;
  559. }
  560. });
  561. return true;
  562. }
  563.  
  564. /**
  565. * removeFromVGPS
  566. */
  567. function removeFromVGPS(gccode) {
  568. var listId = $('#comboVGPS').val(),
  569. url = null;
  570.  
  571. if (typeof(gccode) === 'undefined') { // The map provides the gccode itself
  572. gccode = getGcCodeFromPage();
  573. }
  574.  
  575. url = pgcApiUrl + 'RemoveFromVGPSList?listId=' + listId + '&gccode=' + gccode;
  576.  
  577.  
  578. GM.xmlHttpRequest({
  579. method: "GET",
  580. url: url,
  581. onload: function(response) {
  582. var result = JSON.parse(response.responseText),
  583. msg = (result.status === 'OK') ? i18next.t('vpgs.removed') : i18next.t('vpgs.notre');
  584.  
  585. $('#btnAddToVGPS').css('display', '');
  586. $('#btnRemoveFromVGPS').css('display', 'none');
  587.  
  588. alert(msg);
  589.  
  590. return true;
  591. },
  592. onerror: function(response) {
  593. console.log(response);
  594. return false;
  595. }
  596. });
  597. }
  598.  
  599. function Page_Profile() {
  600. // Override gc.com function on alerting for external links to not alert for Project-GC URLs
  601. var gcAlertOverride = document.createElement('script');
  602. gcAlertOverride.type = "text/javascript";
  603. gcAlertOverride.innerHTML = `(function() {
  604. var _old_isGeocachingDomain = isGeocachingDomain;
  605. isGeocachingDomain = function(url) {
  606. return (_old_isGeocachingDomain.apply(this, arguments)
  607. || url == "project-gc.com"
  608. || url == "www.project-gc.com");
  609. };
  610. })();`;
  611. document.getElementsByTagName('head')[0].appendChild(gcAlertOverride);
  612. }
  613.  
  614. // ==========================================
  615. // Page_CachePage
  616. // ==========================================
  617. function Page_CachePage() {
  618. var gccode = getGcCodeFromPage(),
  619. placedBy = $('#ctl00_ContentBody_mcd1 a').html(),
  620. lastUpdated = $('#ctl00_ContentBody_bottomSection p small time').get(1),
  621. lastFound = $('#ctl00_ContentBody_bottomSection p small time').get(2),
  622. coordinates, latitude, longitude, url;
  623.  
  624. lastUpdated = (lastUpdated) ? lastUpdated.dateTime : false;
  625. lastFound = (lastFound) ? lastFound.dateTime : false;
  626.  
  627. if (subscription) {
  628.  
  629. // Get geocache data from Project-GC
  630. url = pgcApiUrl + 'GetCacheDataFromGccode&gccode=' + gccode;
  631. if (lastUpdated) {
  632. url += '&lastUpdated=' + lastUpdated;
  633. }
  634. if (lastFound) {
  635. url += '&lastFound=' + lastFound;
  636. }
  637.  
  638. GM.xmlHttpRequest({
  639. method: "GET",
  640. url: url,
  641. onload: function(response) {
  642. var result = JSON.parse(response.responseText),
  643. cacheData = result.data.cacheData,
  644. bearing = result.data.bearing,
  645. cacheOwner = result.data.owner,
  646. challengeCheckerTagIds = result.data.challengeCheckerTagIds,
  647. geocacheLogsPerCountry = result.data.geocacheLogsPerCountry,
  648. myNumberOfLogs = result.data.myNumberOfLogs,
  649. location = [],
  650. fp = 0,
  651. fpp = 0,
  652. fpw = 0,
  653. elevation = '',
  654. html = '';
  655.  
  656.  
  657. challengeCheckerResults = result.data.challengeCheckerResults;
  658.  
  659. // Add an alert in top if there are Found it-logs which doesn't seem to fulfill the requirements
  660. if(challengeCheckerResults !== false) {
  661. var suspiciousFoundItLogs = [];
  662. for(var logId in challengeCheckerResults) {
  663. if(typeof challengeCheckerResults[logId] !== 'undefined' && challengeCheckerResults[logId]['status'] == 'fail') {
  664. suspiciousFoundItLogs.push(logId);
  665. }
  666. }
  667.  
  668. if(suspiciousFoundItLogs.length != 0) {
  669. var suspiciousFoundItLog = '<p style="color: #ff6c00;" class=" NoBottomSpacing"><strong>' + i18next.t('vpgs.issue') + '</strong></p>\
  670. <ul style="color: #ff6c00;" class="">\
  671. <li>' + i18next.t('vpgs.notfull') + ' <br>';
  672.  
  673. for(var i = 0 ; i < suspiciousFoundItLogs.length ; i++) {
  674. suspiciousFoundItLog = suspiciousFoundItLog + ' <a href="https://www.geocaching.com/seek/log.aspx?LID=' + suspiciousFoundItLogs[i] + '">' + challengeCheckerResults[suspiciousFoundItLogs[i]]['profileName'] + '</a><br>';
  675. }
  676. suspiciousFoundItLog = suspiciousFoundItLog + i18next.t('cpage.suspiciousFoundItLog') +'</li></ul>';
  677.  
  678. $('div.span-6.right.last').last().next().after(suspiciousFoundItLog);
  679. }
  680. }
  681. //--
  682.  
  683.  
  684. if (result.status == 'OK' && typeof cacheData !== 'undefined') {
  685.  
  686. // If placed by != owner, show the real owner as well.
  687. if (placedBy !== cacheOwner) {
  688. $('#ctl00_ContentBody_mcd1 span.message__owner').before(' (' + cacheOwner + ')');
  689. }
  690.  
  691. // Append link to Profile Stats for the cache owner
  692. // Need to real cache owner name from PGC since the web only has placed by
  693. if (IsSettingEnabled('profileStatsLinks')) {
  694. $('#ctl00_ContentBody_mcd1 span.message__owner').before('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(cacheOwner) + '"><img src="' + externalLinkIcon + '" title="' + i18next.t('cpage.stats') +'"></a>');
  695. }
  696.  
  697. // Add FP/FP%/FPW below the current FP + mouseover for FP% and FPW with decimals
  698. if (IsSettingEnabled('addPgcFp')) {
  699. fp = (+cacheData.favorite_points),
  700. fpp = (+cacheData.favorite_points_pct),
  701. fpw = (+cacheData.favorite_points_wilson);
  702. $('#uxFavContainerLink').append('<p title= "' + parseFloat(fpp) + '%, ' + parseFloat(fpw) + 'W" style="text-align: center; background-color: #f0edeb;border-bottom-left-radius: 5px;border-bottom-right-radius:5px;">PGC: ' + parseInt(fp) + ' FP, ' + Math.round(fpp) + '%, ' + Math.round(fpw) + 'W</p>');
  703. $('.favorite-container').css({
  704. "border-bottom-left-radius": "0",
  705. "border-bottom-right-radius": "0"
  706. });
  707. }
  708.  
  709. // Add elevation (Metres above mean sea level = mamsl)
  710. if (IsSettingEnabled('addElevation')) {
  711. var formattedElevation = FormatDistance(cacheData.elevation),
  712. // Issue 113; fixed 2022-08-30 (Units of elevation obtained from Project-GC)
  713. elevationUnit = imperialFlag ? 'ft' : 'm',
  714. elevationArrow = (cacheData.elevation >= 0) ? '&#x21a5;' : '&#x21a7;';
  715. elevation = formattedElevation + ' ' + elevationUnit + ' ' + elevationArrow;
  716.  
  717. if (cacheData.elevation >= 0) {
  718. html = '<span> (' + elevation + ')</span>';
  719. } else {
  720. html = '<span class="OldWarning"> (' + elevation + ')</span>';
  721. }
  722.  
  723. ($('#uxLatLonLink').length > 0 ? $('#uxLatLonLink') : $('#uxLatLon').parent()).after(html);
  724. }
  725.  
  726. // Add PGC location
  727. if (IsSettingEnabled('addPGCLocation')) {
  728. if (cacheData.country.length > 0) {
  729. location.push(cacheData.country);
  730. }
  731. if (cacheData.region !== null && cacheData.region.length > 0) {
  732. location.push(cacheData.region);
  733. }
  734. if (cacheData.county !== null && cacheData.county.length > 0) {
  735. location.push(cacheData.county);
  736. }
  737. location = location.join(' / ');
  738.  
  739. var gccomLocationData = $('#ctl00_ContentBody_Location').html();
  740. $('#ctl00_ContentBody_Location').html('<span style="text-decoration: line-through;">' + gccomLocationData + '</span><br><span>' + location + '</span>');
  741. }
  742.  
  743. // Add bearing from home
  744. $('#lblDistFromHome').append(' <span>(' + Math.round(bearing*10)/10 + '&deg;)</span>');
  745.  
  746. // Add challenge checkers
  747. if (IsSettingEnabled('addChallengeCheckers') && challengeCheckerTagIds.length > 0) {
  748. html = '<div id="checkerWidget" class="CacheDetailNavigationWidget TopSpacing BottomSpacing"><h3 class="WidgetHeader">' + i18next.t('cpage.checkers') +'' + i18next.t('cpage.plural') +'</h3><div class="WidgetBody" id="PGC_ChallengeCheckers">';
  749. for (var i = 0; i < challengeCheckerTagIds.length; i++) {
  750. html += '<a href="https://project-gc.com/Challenges/' + gccode + '/' + challengeCheckerTagIds[i] + '" style="display: block; width: 200px; margin: 0 auto;"><img src="https://cdn2.project-gc.com/Images/Checker/' + challengeCheckerTagIds[i] + '" title="' + i18next.t('vpgs.title') +'" alt=' + i18next.t('vpgs.alt') +'></a>';
  751. }
  752. html += '</div></div>';
  753. $('#ctl00_ContentBody_detailWidget').before(html);
  754. }
  755.  
  756. // Display warning message if cache is logged and no longer be logged
  757. if (cacheData.locked) {
  758. $('ul.OldWarning').append('<li>' + i18next.t('cpage.locked') +'</li>');
  759. }
  760.  
  761. // Add geocache logs per profile country table
  762. if (IsSettingEnabled('addGeocacheLogsPerProfileCountry')) {
  763. html = '<div id="geocacheLogsPerCountry" style="border: dashed; border-color: #aaa; border-width: thin;">';
  764.  
  765. if(typeof(geocacheLogsPerCountry['willAttend']) != 'undefined' && geocacheLogsPerCountry['willAttend'].length > 0) {
  766. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong>' + i18next.t('cpage.prcountry') +'</strong> <small>' + i18next.t('cpage.pgc') +'</small></p>';
  767. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  768. var unknowns = null;
  769. for (var i = 0; i < geocacheLogsPerCountry['willAttend'].length; i++) {
  770. if(geocacheLogsPerCountry['willAttend'][i].flagIcon.endsWith('blank.gif')) {
  771. unknowns = geocacheLogsPerCountry['willAttend'][i].cnt;
  772. continue;
  773. }
  774. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;"><img src="' + cdnDomain + geocacheLogsPerCountry['willAttend'][i].flagIcon + '" alt="' + $('<div/>').text(geocacheLogsPerCountry['willAttend'][i].country).html() + '" title="' + $('<div/>').text(geocacheLogsPerCountry['willAttend'][i].country).html() + '"> ' + geocacheLogsPerCountry['willAttend'][i].cnt + '</span></li>';
  775. }
  776. if(unknowns !== null) {
  777. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;">(plus ' + unknowns + ' undetermined)</span></li>';
  778. }
  779. html += '</ul>';
  780. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['willAttend'].length + ' unique countries</small></span>';
  781. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small><a href="https://project-gc.com/Tools/EventStatistics?gccode=' + encodeURIComponent(gccode) + '">Event statistics</a></small></span>';
  782. }
  783.  
  784. if(typeof(geocacheLogsPerCountry['found']) != 'undefined' && geocacheLogsPerCountry['found'].length > 0) {
  785. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong> '+i18next.t('other.prcouuntry')+'</strong> <small>'+i18next.t('other.accord')+'</small></p>';
  786. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  787. var unknowns = null;
  788. for (var i = 0; i < geocacheLogsPerCountry['found'].length; i++) {
  789. if(geocacheLogsPerCountry['found'][i].flagIcon.endsWith('blank.gif')) {
  790. unknowns = geocacheLogsPerCountry['found'][i].cnt;
  791. continue;
  792. }
  793. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;"><img src="' + cdnDomain + geocacheLogsPerCountry['found'][i].flagIcon + '" alt="' + $('<div/>').text(geocacheLogsPerCountry['found'][i].country).html() + '" title="' + $('<div/>').text(geocacheLogsPerCountry['found'][i].country).html() + '"> ' + geocacheLogsPerCountry['found'][i].cnt + '</span></li>';
  794. }
  795. if(unknowns !== null) {
  796. html += '<li style="display: inline; padding-right: 20px;"><span style="display: inline-block;">(plus ' + unknowns + ' undetermined)</span></li>';
  797. }
  798. html += '</ul>';
  799. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['found'].length + ' ' +i18next.t('other.unique')+'</small></span>';
  800. }
  801.  
  802. html += '</div>';
  803.  
  804. $('#ctl00_ContentBody_lblFindCounts').append(html);
  805. }
  806.  
  807. // Add my number of logs above the log button
  808. if (IsSettingEnabled('addMyNumberOfLogs')) {
  809. $('<p style="margin: 0;"><small>'+i18next.t('other.have')+' ' + myNumberOfLogs + ' '+i18next.t('other.accordpgc')+'</small></p>').insertBefore('#ctl00_ContentBody_GeoNav_logButton');
  810. }
  811.  
  812. // Append the same number to the added logbook link
  813. if (IsSettingEnabled('logbookLinks')) {
  814. $('#pgc-logbook-yours').html(''+i18next.t('other.yours')+' (' + myNumberOfLogs + ')')
  815.  
  816. }
  817. }
  818.  
  819.  
  820. // Since everything in the logbook is ajax, we need to wait for the elements
  821. // We also want to wait on challengeCheckerResults
  822. waitForKeyElements('#cache_logs_table tbody tr', Logbook);
  823. }
  824. });
  825. }
  826.  
  827. // Add weekday of place date
  828. if (IsSettingEnabled('showWeekday')) {
  829. var match = $('meta[name="description"]')[1].content.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
  830. if (match) {
  831. var date = new Date(match[3], match[1]-1, match[2]);
  832. var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  833. var text = $($('#ctl00_ContentBody_mcd2')[0].childNodes[0]).text();
  834. var pos = text.indexOf(':') + 2;
  835. var newText = text.substring(0, pos);
  836. newText += weekday[date.getDay()] + ', ';
  837. newText += text.substring(pos, text.length);
  838. var newNode = document.createTextNode(newText);
  839. $('#ctl00_ContentBody_mcd2')[0].replaceChild(newNode, $('#ctl00_ContentBody_mcd2')[0].childNodes[0]);
  840. }
  841. }
  842.  
  843. // Tidy the web
  844. if (IsSettingEnabled('tidy')) {
  845. $('#ctl00_divContentMain p.Clear').css('margin', '0');
  846. $('div.Note.PersonalCacheNote').css('margin', '0');
  847. $('h3.CacheDescriptionHeader').remove();
  848. $('#ctl00_ContentBody_EncryptionKey').remove();
  849. $('#ctl00_ContentBody_GeoNav_foundStatus').css('margin-bottom', '0');
  850. }
  851.  
  852. // Make it easier to copy the gccode
  853. if (IsSettingEnabled('makeCopyFriendly')) {
  854. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').
  855. html('<div style="margin-right: 15px; margin-bottom: 10px;"><p id="ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode" style="font-size: 125%; margin-bottom: 0">' + gccode + '</p>' +
  856. '<input size="25" type="text" value="https://coord.info/' + encodeURIComponent(gccode) + '" onclick="this.setSelectionRange(0, this.value.length);"></div>');
  857. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').css('font-weight', 'inherit').css('margin-right', '27px');
  858. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div input').css('padding', '0');
  859. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div').css('margin', '0 0 5px 0');
  860. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div p').css('font-weight', 'bold');
  861. }
  862.  
  863. // Add PGC Map links
  864. if (IsSettingEnabled('addPgcMapLinks')) {
  865. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  866. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  867. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1");
  868. // var mapUrl = pgcUrl + 'Maps/mapcompare/?profile_name=' + gccomUsername +
  869. // '&nonefound=on&ownfound=on&location=' + latitude + ',' + longitude +
  870. // '&max_distance=5&submit=Filter';
  871. var mapUrl = pgcUrl + 'LiveMap/#c=' + latitude + ',' + longitude + ';z=14';
  872.  
  873. // $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  874. // '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC map</a> (<a target="_blank" href="' + mapUrl + '&onefound=on">incl found</a>)</div>'
  875. // );
  876. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  877. '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">'+i18next.t('other.live')+'</a></div>'
  878. );
  879. }
  880.  
  881. // Remove the UTM coordinates
  882. // $('#ctl00_ContentBody_CacheInformationTable div.LocationData div.span-9 p.NoBottomSpacing br').remove();
  883. if (IsSettingEnabled('removeUTM')) {
  884. $('#ctl00_ContentBody_LocationSubPanel').html('');
  885.  
  886. // And move the "N 248.3 km from your home location"
  887. $('#ctl00_ContentBody_LocationSubPanel').after($('#lblDistFromHome'));
  888. }
  889.  
  890. // Remove ads
  891. // PGC can't really do this officially
  892. // $('#ctl00_ContentBody_uxBanManWidget').remove();
  893.  
  894. // Remove disclaimer
  895. if (IsSettingEnabled('removeDisclaimer')) {
  896. $('#divContentMain div.span-17 div.Note.Disclaimer').remove();
  897. }
  898.  
  899. // If the first log is a DNF, display a blue warning on top of the page
  900. // 2022-08-24, Issue #111, fixes display of blue text warning of last log is DNF.
  901. if ($('#cache_logs_table span.h4 img').attr('src') === '/images/logtypes/3.png') {
  902. var htmlFirstLogDnf = '<p style="color: #006cff;" class=" NoBottomSpacing"><strong>'+i18next.t('other.issue')+'</strong></p>\
  903. <ul style="color: #006cff;" class="">\
  904. <li>'+i18next.t('other.latest')+' <a href="#cache_logs_table">'+i18next.t('other.please')+'</a>'+i18next.t('other.before')+' </li>\
  905. </ul>';
  906. $('div.span-6.right.last').last().next().after(htmlFirstLogDnf);
  907.  
  908. }
  909.  
  910. // Collapse download links
  911. // http://www.w3schools.com/charsets/ref_utf_geometric.asp (x25BA, x25BC)
  912. if (IsSettingEnabled('collapseDownloads')) {
  913. $('<p style="cursor: pointer; margin: 0;" id="DownloadLinksToggle" onclick="$(\'#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow\').toggle();"><span class="arrow">&#x25BA;</span><span class="arrow open">&#x25BC;</span>'+i18next.t('other.print')+'</p>').insertBefore('#divContentMain div.DownloadLinks');
  914. $('#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow.open').hide();
  915. }
  916.  
  917. // Resolve the coordinates into an address
  918. if (IsSettingEnabled('addAddress')) {
  919. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  920. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  921. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1"),
  922. url = 'https://nominatim.openstreetmap.org/reverse?lat=' + latitude + '&lon=' + longitude + '&format=json';
  923.  
  924. GM.xmlHttpRequest({
  925. method: "GET",
  926. url: url,
  927. onload: function(response) {
  928. var result = JSON.parse(response.responseText);
  929. if (!result.display_name) {
  930. return false;
  931. }
  932. var formattedAddress = result.address.road;
  933. if (result.address.house_number) {
  934. formattedAddress = formattedAddress + ' ' + result.address.house_number;
  935. }
  936. if (result.address.city) {
  937. formattedAddress = formattedAddress + ', ' + result.address.city;
  938. }
  939. $('#ctl00_ContentBody_LocationSubPanel').append(formattedAddress + '<br />');
  940. }
  941. });
  942. }
  943.  
  944. // Add number of finds per type to the top
  945. if (IsSettingEnabled('cloneLogsPerType') && typeof $('#ctl00_ContentBody_lblFindCounts').html() !== 'undefined') {
  946. $('#ctl00_ContentBody_CacheInformationTable').before('<div>' + $('#ctl00_ContentBody_lblFindCounts').html() + '</div>');
  947. }
  948.  
  949. // Add link to PGC gallery
  950. if (subscription && IsSettingEnabled('addPgcGalleryLinks')) {
  951. var html = '<a href="' + pgcUrl + 'Tools/Gallery?gccode=' + gccode + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="'+i18next.t('other.gallery')+'"></a> ';
  952. $('.CacheDetailNavigation ul li:first').append(html);
  953. }
  954.  
  955. // Add map links for each bookmarklist
  956. if (IsSettingEnabled('addMapBookmarkListLinks')) {
  957. $('ul.BookmarkList li').each(function() {
  958. var guid = $(this).children(':nth-child(1)').attr('href').replace(/.*\?guid=(.*)/, "$1");
  959. var owner = $(this).children(':nth-child(3)').text();
  960.  
  961. // Add the map link
  962. url = 'https://project-gc.com/Tools/MapBookmarklist?owner_name=' + encodeURIComponent(owner) + '&guid=' + encodeURIComponent(guid);
  963. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + mapLinkIcon + '" title="'+i18next.t('other.map')+'"></a>');
  964.  
  965. // Add gallery link for the bookmark list
  966. url = 'https://project-gc.com/Tools/Gallery?bml_owner=' + encodeURIComponent(owner) + '&bml_guid=' + encodeURIComponent(guid) + '&submit=Filter';
  967. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + galleryLinkIcon + '" title="'+i18next.t('other.gallery')+'"></a>');
  968.  
  969. // Add profile stats link to the owner
  970. url = 'https://project-gc.com/ProfileStats/' + encodeURIComponent(owner);
  971. $(this).children(':nth-child(3)').append('&nbsp;<a href="' + url + '"><img src="' + externalLinkIcon + '" title="'+i18next.t('other.prostats')+'"></a>');
  972. });
  973. }
  974.  
  975. // Decrypt the hint
  976. if (IsSettingEnabled('decryptHints') && $('#ctl00_ContentBody_lnkDH')[0].title == i18next.t('other.decrypt')) {
  977. $('#ctl00_ContentBody_lnkDH')[0].click();
  978. }
  979.  
  980. // VGPS form
  981. if (IsSettingEnabled('showVGPS')) {
  982. GM.xmlHttpRequest({
  983. method: "GET",
  984. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  985. onload: function(response) {
  986. var result = JSON.parse(response.responseText),
  987. vgpsLists = result.data.lists,
  988. selected = result.data.selected,
  989. existsIn = result.data.existsIn,
  990. selectedContent,
  991. existsContent,
  992. html = '<li><img width="16" height="16" src="https://cdn2.project-gc.com/images/mobile_telephone_32.png"> <strong> ' + i18next.t('vpgs.send') + ' </strong><br />',
  993. listId;
  994.  
  995. html += '<select id="comboVGPS" style="width: 138px;">';
  996. for (var k in vgpsLists) {
  997. listId = vgpsLists[k].id;
  998.  
  999. selectedContent = '';
  1000. if (+selected === +listId) {
  1001. selectedContent = ' selected="selected"';
  1002. }
  1003.  
  1004. existsContent = '';
  1005. if (existsIn.indexOf(listId) > -1) {
  1006. existsContent = ' data-exists="true"';
  1007. }
  1008. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[k].name + '</option>';
  1009. }
  1010. html += '</select>';
  1011. if (existsIn.indexOf(String(selected)) == -1) {
  1012. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  1013. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  1014. } else {
  1015. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  1016. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  1017. }
  1018. html += '</li>';
  1019.  
  1020. $('div.CacheDetailNavigation ul:first').append(html);
  1021.  
  1022. $('#comboVGPS').change(function() {
  1023. selected = $(this).find(':selected').val();
  1024. if (existsIn.indexOf(String(selected)) == -1) {
  1025. $('#btnAddToVGPS').css('display', '');
  1026. $('#btnRemoveFromVGPS').css('display', 'none');
  1027. } else {
  1028. $('#btnAddToVGPS').css('display', 'none');
  1029. $('#btnRemoveFromVGPS').css('display', '');
  1030. }
  1031. });
  1032. $('#btnAddToVGPS').click(function(event) {
  1033. event.preventDefault();
  1034. addToVGPS();
  1035. });
  1036. $('#btnRemoveFromVGPS').click(function(event) {
  1037. event.preventDefault();
  1038. removeFromVGPS();
  1039. });
  1040. }
  1041. });
  1042. }
  1043.  
  1044. // Change font in personal cache note to monospaced
  1045. if (IsSettingEnabled('cachenoteFont')) {
  1046. $("#viewCacheNote,#cacheNoteText").css("font-family", "monospace").css("font-size", "12px");
  1047. $("#viewCacheNote").on("DOMSubtreeModified", function() {
  1048. $(".inplace_field").css("font-family", "monospace").css("font-size", "12px");
  1049. });
  1050. }
  1051.  
  1052.  
  1053. if (IsSettingEnabled('logbookLinks')) {
  1054. // 2022-08-24, fixes #112: Extra single quote showing up in LogBookLinks near "Friends".
  1055. $('\
  1056. <span>&nbsp;|&nbsp;</span><a id="pgc-logbook-yours" href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-2">Yours</a>\
  1057. <span>&nbsp;|&nbsp;</span><a href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-3">'+i18next.t("other.Friends")+'</a>\
  1058. ').insertAfter( $('#ctl00_ContentBody_uxLogbookLink') );
  1059. }
  1060. }
  1061.  
  1062. function Page_Logbook() {
  1063. // Since everything in the logbook is ajax, we need to wait for the elements
  1064. waitForKeyElements('#AllLogs tr', Logbook);
  1065. waitForKeyElements('#PersonalLogs tr', Logbook);
  1066. waitForKeyElements('#FriendLogs tr', Logbook);
  1067. }
  1068.  
  1069. function Logbook(jNode) {
  1070. // Add Profile stats and gallery links after each user
  1071. if (IsSettingEnabled('profileStatsLinks')) {
  1072. var profileNameElm = $(jNode).find('a.h5');
  1073. var profileName = profileNameElm.html();
  1074.  
  1075. if (typeof profileName !== 'undefined') {
  1076. profileName = profileNameElm.append('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(profileName) + '"><img src="' + externalLinkIcon + '" title="'+i18next.t("other.prostats")+'"></a>')
  1077. .append('<a href="' + pgcUrl + 'Tools/Gallery?profile_name=' + encodeURIComponent(profileName) + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="'+i18next.t("other.gallery")+'"></a>');
  1078. }
  1079. }
  1080.  
  1081. if(IsSettingEnabled('parseExifLocation')) {
  1082. $(jNode).find('ul.LogImagesTable li>a').each(function() {
  1083. var url = $(this).attr('href');
  1084. var thumbnailUrl = url.replace('/img.geocaching.com/cache/log/large/', '/img.geocaching.com/cache/log/thumb/');
  1085.  
  1086. var imgElm = $(this).find('img');
  1087. $(imgElm).attr('src', thumbnailUrl);
  1088. $(imgElm).removeAttr('width');
  1089. $(imgElm).removeAttr('height');
  1090. $(imgElm).next().css('vertical-align', 'top');
  1091.  
  1092. $(imgElm).load(function() {
  1093. EXIF.getData($(imgElm)[0], function() {
  1094. // console.log(EXIF.pretty(this));
  1095. var coords = GetCoordinatesFromExif(this);
  1096. if(coords != false) {
  1097. $('<span style="color: #8c0b0b; font-weight: bold; float: right;">EXIF Location: <a href="https://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter($(imgElm).parent());
  1098. }
  1099. });
  1100. });
  1101.  
  1102. });
  1103. }
  1104.  
  1105. if(IsSettingEnabled('addCachedChallengeCheckerResults') && typeof(challengeCheckerResults) !== 'undefined' && challengeCheckerResults !== null) {
  1106. var classes = $(jNode).attr('class');
  1107. var logId = classes.match(/l-[0-9]+/)[0].replace('l-', '');
  1108. if(typeof(challengeCheckerResults[logId]) !== 'undefined') {
  1109. if(challengeCheckerResults[logId]['status'] == 'success') {
  1110. $(jNode).find('div.LogDisplayLeft').first().append('<hr style="margin-top: 12px; margin-bottom: 12px;"><p><br>' + challengeCheckerResults[logId]['lastRun'] + ' UTC: <img src="' + challengeCheckerSuccessIcon + '"></p>');
  1111. }
  1112. else if(challengeCheckerResults[logId]['status'] == 'fail') {
  1113. $(jNode).find('div.LogDisplayLeft').first().append('<hr style="margin-top: 12px; margin-bottom: 12px;"><p>'+i18next.t("other.checker")+'<br>' + challengeCheckerResults[logId]['lastRun'] + ' UTC: <img src="' + challengeCheckerFailIcon + '"></p>');
  1114. }
  1115. }
  1116. }
  1117.  
  1118. if(IsSettingEnabled('hideLogVoting')) {
  1119. $('div.upvotes').css('display','none');
  1120. $('div.sort-logs').css('display','none');
  1121. }
  1122.  
  1123.  
  1124. // Save to latest logs
  1125. if (latestLogs.length < 5) {
  1126. // 2022-08-23, Issue #109: Fix for latestLogs, using span instead of div.
  1127. var node = $(jNode).find('span.h4 img[src]'),
  1128. logType = {};
  1129.  
  1130. if (node.length === 0) {
  1131. return false;
  1132. }
  1133.  
  1134. logType = {
  1135. 'src': node.attr('src'),
  1136. 'alt': node.attr('alt'),
  1137. 'title': node.attr('title')
  1138. };
  1139.  
  1140. logType.id = +logType.src.replace(/.*logtypes\/(\d+)\.png/, "$1");
  1141.  
  1142. // First entry is undefined, due to ajax
  1143. if (logType.src) {
  1144. latestLogs.push('<img src="' + logType.src + '" alt="' + logType.alt + '" title="' + logType.title + '" style="margin-bottom: -4px; margin-right: 1px;">');
  1145. // 2 = found, 3 = dnf, 4 = note, 5 = archive, 22 = disable, 24 = publish, 45 = nm, 46 = owner maintenance, 68 = reviewer note
  1146. if ($.inArray(logType.id, [3, 5, 22, 45, 68]) !== -1) {
  1147. latestLogsAlert = true;
  1148. }
  1149. }
  1150.  
  1151. // Show latest logs
  1152. // Enhanced Nov 2016 to show icons for up to 5 of the latest logs
  1153. if (IsSettingEnabled('addLatestLogs') && latestLogs.length <= 5) {
  1154. var images = latestLogs.join('');
  1155.  
  1156. $('#latestLogIcons').remove();
  1157. $('#ctl00_ContentBody_size p').removeClass('AlignCenter').addClass('NoBottomSpacing');
  1158.  
  1159. if (latestLogsAlert) {
  1160. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing OldWarning" id="latestLogIcons"><strong>'+i18next.t("other.latest2")+'</strong> <span>' + images + '</span></p>');
  1161. } else {
  1162. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing" id="latestLogIcons">'+i18next.t("other.latest2")+' <span>' + images + '</span></p>');
  1163. }
  1164. }
  1165. }
  1166. }
  1167.  
  1168. function Page_Map() {
  1169. if (IsSettingEnabled('showVGPS')) {
  1170.  
  1171. setTimeout(function() {
  1172. $('#map_canvas div.leaflet-popup-pane').bind('DOMSubtreeModified', function(event) {
  1173. if (event.target.className == 'leaflet-popup-pane' && $('#pgc_vgps').length === 0) {
  1174. var gccode = $('#gmCacheInfo div.code').first().text();
  1175.  
  1176. $('#gmCacheInfo div.links').after('<div id="pgc_vgps"></div>');
  1177.  
  1178. GM.xmlHttpRequest({
  1179. method: "GET",
  1180. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  1181. onload: function(response) {
  1182.  
  1183. var result = JSON.parse(response.responseText),
  1184. vgpsLists = result.data.lists,
  1185. selected = result.data.selected,
  1186. existsIn = result.data.existsIn,
  1187. selectedContent,
  1188. existsContent,
  1189. html,
  1190. listId;
  1191.  
  1192.  
  1193. html = '<img src="https://cdn2.project-gc.com/images/mobile_telephone_32.png" style="width: 24px; height: 24px; margin-bottom: -6px;">';
  1194.  
  1195. html += '<select id="comboVGPS" style="margin-bottom: 4px;">';
  1196. for (let k in vgpsLists) {
  1197. listId = vgpsLists[k].id;
  1198.  
  1199. selectedContent = '';
  1200. if (+selected === +listId) {
  1201. selectedContent = ' selected="selected"';
  1202. }
  1203. existsContent = '';
  1204. if (existsIn.indexOf(listId) > -1) {
  1205. existsContent = ' data-exists="true"';
  1206. }
  1207.  
  1208. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[k].name + '</option>';
  1209. }
  1210. html += '</select>';
  1211.  
  1212. if (existsIn.indexOf(String(selected)) == -1) {
  1213. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  1214. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  1215. } else {
  1216. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  1217. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  1218. }
  1219.  
  1220. $('#pgc_vgps').html(html);
  1221.  
  1222.  
  1223. $('#btnAddToVGPS').click(function(event) {
  1224. event.preventDefault();
  1225. addToVGPS(gccode);
  1226. });
  1227. $('#btnRemoveFromVGPS').click(function(event) {
  1228. event.preventDefault();
  1229. removeFromVGPS(gccode);
  1230. });
  1231. }
  1232. });
  1233. }
  1234. });
  1235. }, 500);
  1236. }
  1237.  
  1238. }
  1239.  
  1240. function Page_Gallery() {
  1241. // Find location data in exif tags
  1242. if(IsSettingEnabled('parseExifLocation')) {
  1243. $(window).load(function() { // Wait until page is loaded. If the images aren't loaded before this starts it will fail.
  1244. $('#ctl00_ContentBody_GalleryItems_DataListGallery img').each(function() {
  1245. EXIF.getData($(this)[0], function() {
  1246. // console.log(EXIF.pretty(this));
  1247. var coords = GetCoordinatesFromExif(this);
  1248. if(coords != false) {
  1249. $('<span class="OldWarning">'+i18next.t("other.exif")+'<br><a href="https://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter(this.parentNode);
  1250. }
  1251. });
  1252. });
  1253. });
  1254. }
  1255. }
  1256.  
  1257. function Page_Bookmarks() {
  1258. var owner_name = $("#ctl00_ContentBody_ListInfo_uxListOwner").text();
  1259.  
  1260. var search = window.location.search;
  1261. var guid_start = search.indexOf("guid=");
  1262. if (guid_start == -1) {
  1263. /* the guid= not found in URL
  1264. * something is wrong so we will not generate bad URL
  1265. */
  1266. return;
  1267. }
  1268. var guid = search.substr(guid_start + 5/*, eof */);
  1269.  
  1270. var url = "https://project-gc.com/Tools/MapBookmarklist?owner_name=" + owner_name + "&guid=" + guid;
  1271. var icon = "https://cdn2.project-gc.com/images/map_app_16.png";
  1272.  
  1273. /* Heading link */
  1274. var html = ' <a href="' + url + '" title="'+i18next.t("other.map3")+'"><img src="' + icon + '" />'+i18next.t("other.map2")+' </a>';
  1275.  
  1276. $("#ctl00_ContentBody_lbHeading").after(html);
  1277.  
  1278. /* Footer button */
  1279. var html2 = '<p><input type="button" onclick="window.location.href= \'' + url + '\'" value='+i18next.t("other.map4")+' /></p>';
  1280.  
  1281. $("#ctl00_ContentBody_ListInfo_btnDownload").parent().before(html2);
  1282. }
  1283.  
  1284. function Page_Drafts() {
  1285. if (IsSettingEnabled("openDraftLogInSameWindow")) {
  1286. waitForKeyElements('#draftsHub > ul.draft-list > li.draft-item', Draft);
  1287. }
  1288. }
  1289.  
  1290. function Draft(jNode) {
  1291. $(jNode).find(".draft-content > a").removeAttr('target');
  1292. }
  1293.  
  1294. function Page_Messagecenter() {
  1295. var target = document.getElementById('currentMessage');
  1296. var observer = new MutationObserver(function(mutations) {
  1297. mutations.forEach(function(mutation) {
  1298. if(mutation.type === "childList") {
  1299. var userlink = $(".user-meta a.current-user-image").attr("href"), username = $(".user-meta span.current-user-name").html();
  1300. $(".user-meta span.current-user-name").html("<a href='"+userlink+"'>"+username+"</a>");
  1301. }
  1302. });
  1303. });
  1304.  
  1305. var config = { childList: true };
  1306. observer.observe(target, config);
  1307. }
  1308.  
  1309. function Page_PrintCachePage() {
  1310. // Remove the disclaimer
  1311. $('div.TermsWidget').css('display', 'none');
  1312.  
  1313.  
  1314. // Get rid of the Logs section if it's not asked for. But keep it if we asked for it, even though there are 0 logs.
  1315. if( getUrlParameter('lc') === false ) {
  1316. $('div.item.ui-widget > div.item-header > h2.ui-sortable-handle').each(function() {
  1317. if( $(this).html() == 'Logs' ) { // Will only work with English
  1318. $(this).parent().parent().addClass('no-print').css('display', 'none');
  1319. return false; // Break .each loop
  1320. }
  1321. });
  1322. }
  1323.  
  1324.  
  1325. if(IsSettingEnabled('hideMapFromPrintCachePage')) {
  1326. $('#map').parent().parent().addClass('no-print');
  1327. $('#map').parent().prev().children('span.ui-icon').removeClass('ui-icon-minusthick').addClass('ui-icon-plusthick');
  1328. $('#map').parent().css('display', 'none');
  1329. }
  1330. }
  1331.  
  1332.  
  1333. function padLeft(str, n, padstr){
  1334. return Array(n-String(str).length+1).join(padstr||'0')+str;
  1335. }
  1336.  
  1337. function getUrlParameter(sParam) {
  1338. var sPageURL = decodeURIComponent(window.location.search.substring(1)),
  1339. sURLVariables = sPageURL.split('&'),
  1340. sParameterName,
  1341. i;
  1342.  
  1343. for (i = 0; i < sURLVariables.length; i++) {
  1344. sParameterName = sURLVariables[i].split('=');
  1345.  
  1346. if (sParameterName[0] === sParam) {
  1347. return sParameterName[1] === undefined ? true : sParameterName[1];
  1348. }
  1349. }
  1350.  
  1351. return false;
  1352. }
  1353. }());
  1354.  
  1355.  
  1356.  
  1357. // https://github.com/exif-js/exif-js adjusted to use GM.xmlHttpRequest
  1358. // Original license:
  1359. // The MIT License (MIT)
  1360. // Copyright (c) 2008 Jacob Seidelin
  1361. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
  1362. // (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
  1363. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to
  1364. // do so, subject to the following conditions:
  1365. // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  1366. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1367. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  1368. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  1369. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1370.  
  1371. (function() {
  1372. var debug = false;
  1373.  
  1374. var root = this;
  1375.  
  1376. var EXIF = function(obj) {
  1377. if (obj instanceof EXIF) return obj;
  1378. if (!(this instanceof EXIF)) return new EXIF(obj);
  1379. this.EXIFwrapped = obj;
  1380. };
  1381.  
  1382. if (typeof exports !== 'undefined') {
  1383. if (typeof module !== 'undefined' && module.exports) {
  1384. exports = module.exports = EXIF;
  1385. }
  1386. exports.EXIF = EXIF;
  1387. } else {
  1388. root.EXIF = EXIF;
  1389. }
  1390.  
  1391. var ExifTags = EXIF.Tags = {
  1392.  
  1393. // version tags
  1394. 0x9000 : "ExifVersion", // EXIF version
  1395. 0xA000 : "FlashpixVersion", // Flashpix format version
  1396.  
  1397. // colorspace tags
  1398. 0xA001 : "ColorSpace", // Color space information tag
  1399.  
  1400. // image configuration
  1401. 0xA002 : "PixelXDimension", // Valid width of meaningful image
  1402. 0xA003 : "PixelYDimension", // Valid height of meaningful image
  1403. 0x9101 : "ComponentsConfiguration", // Information about channels
  1404. 0x9102 : "CompressedBitsPerPixel", // Compressed bits per pixel
  1405.  
  1406. // user information
  1407. 0x927C : "MakerNote", // Any desired information written by the manufacturer
  1408. 0x9286 : "UserComment", // Comments by user
  1409.  
  1410. // related file
  1411. 0xA004 : "RelatedSoundFile", // Name of related sound file
  1412.  
  1413. // date and time
  1414. 0x9003 : "DateTimeOriginal", // Date and time when the original image was generated
  1415. 0x9004 : "DateTimeDigitized", // Date and time when the image was stored digitally
  1416. 0x9290 : "SubsecTime", // Fractions of seconds for DateTime
  1417. 0x9291 : "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
  1418. 0x9292 : "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
  1419.  
  1420. // picture-taking conditions
  1421. 0x829A : "ExposureTime", // Exposure time (in seconds)
  1422. 0x829D : "FNumber", // F number
  1423. 0x8822 : "ExposureProgram", // Exposure program
  1424. 0x8824 : "SpectralSensitivity", // Spectral sensitivity
  1425. 0x8827 : "ISOSpeedRatings", // ISO speed rating
  1426. 0x8828 : "OECF", // Optoelectric conversion factor
  1427. 0x9201 : "ShutterSpeedValue", // Shutter speed
  1428. 0x9202 : "ApertureValue", // Lens aperture
  1429. 0x9203 : "BrightnessValue", // Value of brightness
  1430. 0x9204 : "ExposureBias", // Exposure bias
  1431. 0x9205 : "MaxApertureValue", // Smallest F number of lens
  1432. 0x9206 : "SubjectDistance", // Distance to subject in meters
  1433. 0x9207 : "MeteringMode", // Metering mode
  1434. 0x9208 : "LightSource", // Kind of light source
  1435. 0x9209 : "Flash", // Flash status
  1436. 0x9214 : "SubjectArea", // Location and area of main subject
  1437. 0x920A : "FocalLength", // Focal length of the lens in mm
  1438. 0xA20B : "FlashEnergy", // Strobe energy in BCPS
  1439. 0xA20C : "SpatialFrequencyResponse", //
  1440. 0xA20E : "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
  1441. 0xA20F : "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
  1442. 0xA210 : "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
  1443. 0xA214 : "SubjectLocation", // Location of subject in image
  1444. 0xA215 : "ExposureIndex", // Exposure index selected on camera
  1445. 0xA217 : "SensingMethod", // Image sensor type
  1446. 0xA300 : "FileSource", // Image source (3 == DSC)
  1447. 0xA301 : "SceneType", // Scene type (1 == directly photographed)
  1448. 0xA302 : "CFAPattern", // Color filter array geometric pattern
  1449. 0xA401 : "CustomRendered", // Special processing
  1450. 0xA402 : "ExposureMode", // Exposure mode
  1451. 0xA403 : "WhiteBalance", // 1 = auto white balance, 2 = manual
  1452. 0xA404 : "DigitalZoomRation", // Digital zoom ratio
  1453. 0xA405 : "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
  1454. 0xA406 : "SceneCaptureType", // Type of scene
  1455. 0xA407 : "GainControl", // Degree of overall image gain adjustment
  1456. 0xA408 : "Contrast", // Direction of contrast processing applied by camera
  1457. 0xA409 : "Saturation", // Direction of saturation processing applied by camera
  1458. 0xA40A : "Sharpness", // Direction of sharpness processing applied by camera
  1459. 0xA40B : "DeviceSettingDescription", //
  1460. 0xA40C : "SubjectDistanceRange", // Distance to subject
  1461.  
  1462. // other tags
  1463. 0xA005 : "InteroperabilityIFDPointer",
  1464. 0xA420 : "ImageUniqueID" // Identifier assigned uniquely to each image
  1465. };
  1466.  
  1467. var TiffTags = EXIF.TiffTags = {
  1468. 0x0100 : "ImageWidth",
  1469. 0x0101 : "ImageHeight",
  1470. 0x8769 : "ExifIFDPointer",
  1471. 0x8825 : "GPSInfoIFDPointer",
  1472. 0xA005 : "InteroperabilityIFDPointer",
  1473. 0x0102 : "BitsPerSample",
  1474. 0x0103 : "Compression",
  1475. 0x0106 : "PhotometricInterpretation",
  1476. 0x0112 : "Orientation",
  1477. 0x0115 : "SamplesPerPixel",
  1478. 0x011C : "PlanarConfiguration",
  1479. 0x0212 : "YCbCrSubSampling",
  1480. 0x0213 : "YCbCrPositioning",
  1481. 0x011A : "XResolution",
  1482. 0x011B : "YResolution",
  1483. 0x0128 : "ResolutionUnit",
  1484. 0x0111 : "StripOffsets",
  1485. 0x0116 : "RowsPerStrip",
  1486. 0x0117 : "StripByteCounts",
  1487. 0x0201 : "JPEGInterchangeFormat",
  1488. 0x0202 : "JPEGInterchangeFormatLength",
  1489. 0x012D : "TransferFunction",
  1490. 0x013E : "WhitePoint",
  1491. 0x013F : "PrimaryChromaticities",
  1492. 0x0211 : "YCbCrCoefficients",
  1493. 0x0214 : "ReferenceBlackWhite",
  1494. 0x0132 : "DateTime",
  1495. 0x010E : "ImageDescription",
  1496. 0x010F : "Make",
  1497. 0x0110 : "Model",
  1498. 0x0131 : "Software",
  1499. 0x013B : "Artist",
  1500. 0x8298 : "Copyright"
  1501. };
  1502.  
  1503. var GPSTags = EXIF.GPSTags = {
  1504. 0x0000 : "GPSVersionID",
  1505. 0x0001 : "GPSLatitudeRef",
  1506. 0x0002 : "GPSLatitude",
  1507. 0x0003 : "GPSLongitudeRef",
  1508. 0x0004 : "GPSLongitude",
  1509. 0x0005 : "GPSAltitudeRef",
  1510. 0x0006 : "GPSAltitude",
  1511. 0x0007 : "GPSTimeStamp",
  1512. 0x0008 : "GPSSatellites",
  1513. 0x0009 : "GPSStatus",
  1514. 0x000A : "GPSMeasureMode",
  1515. 0x000B : "GPSDOP",
  1516. 0x000C : "GPSSpeedRef",
  1517. 0x000D : "GPSSpeed",
  1518. 0x000E : "GPSTrackRef",
  1519. 0x000F : "GPSTrack",
  1520. 0x0010 : "GPSImgDirectionRef",
  1521. 0x0011 : "GPSImgDirection",
  1522. 0x0012 : "GPSMapDatum",
  1523. 0x0013 : "GPSDestLatitudeRef",
  1524. 0x0014 : "GPSDestLatitude",
  1525. 0x0015 : "GPSDestLongitudeRef",
  1526. 0x0016 : "GPSDestLongitude",
  1527. 0x0017 : "GPSDestBearingRef",
  1528. 0x0018 : "GPSDestBearing",
  1529. 0x0019 : "GPSDestDistanceRef",
  1530. 0x001A : "GPSDestDistance",
  1531. 0x001B : "GPSProcessingMethod",
  1532. 0x001C : "GPSAreaInformation",
  1533. 0x001D : "GPSDateStamp",
  1534. 0x001E : "GPSDifferential"
  1535. };
  1536.  
  1537. var StringValues = EXIF.StringValues = {
  1538. ExposureProgram : {
  1539. 0 : "Not defined",
  1540. 1 : "Manual",
  1541. 2 : "Normal program",
  1542. 3 : "Aperture priority",
  1543. 4 : "Shutter priority",
  1544. 5 : "Creative program",
  1545. 6 : "Action program",
  1546. 7 : "Portrait mode",
  1547. 8 : "Landscape mode"
  1548. },
  1549. MeteringMode : {
  1550. 0 : "Unknown",
  1551. 1 : "Average",
  1552. 2 : "CenterWeightedAverage",
  1553. 3 : "Spot",
  1554. 4 : "MultiSpot",
  1555. 5 : "Pattern",
  1556. 6 : "Partial",
  1557. 255 : "Other"
  1558. },
  1559. LightSource : {
  1560. 0 : "Unknown",
  1561. 1 : "Daylight",
  1562. 2 : "Fluorescent",
  1563. 3 : "Tungsten (incandescent light)",
  1564. 4 : "Flash",
  1565. 9 : "Fine weather",
  1566. 10 : "Cloudy weather",
  1567. 11 : "Shade",
  1568. 12 : "Daylight fluorescent (D 5700 - 7100K)",
  1569. 13 : "Day white fluorescent (N 4600 - 5400K)",
  1570. 14 : "Cool white fluorescent (W 3900 - 4500K)",
  1571. 15 : "White fluorescent (WW 3200 - 3700K)",
  1572. 17 : "Standard light A",
  1573. 18 : "Standard light B",
  1574. 19 : "Standard light C",
  1575. 20 : "D55",
  1576. 21 : "D65",
  1577. 22 : "D75",
  1578. 23 : "D50",
  1579. 24 : "ISO studio tungsten",
  1580. 255 : "Other"
  1581. },
  1582. Flash : {
  1583. 0x0000 : "Flash did not fire",
  1584. 0x0001 : "Flash fired",
  1585. 0x0005 : "Strobe return light not detected",
  1586. 0x0007 : "Strobe return light detected",
  1587. 0x0009 : "Flash fired, compulsory flash mode",
  1588. 0x000D : "Flash fired, compulsory flash mode, return light not detected",
  1589. 0x000F : "Flash fired, compulsory flash mode, return light detected",
  1590. 0x0010 : "Flash did not fire, compulsory flash mode",
  1591. 0x0018 : "Flash did not fire, auto mode",
  1592. 0x0019 : "Flash fired, auto mode",
  1593. 0x001D : "Flash fired, auto mode, return light not detected",
  1594. 0x001F : "Flash fired, auto mode, return light detected",
  1595. 0x0020 : "No flash function",
  1596. 0x0041 : "Flash fired, red-eye reduction mode",
  1597. 0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
  1598. 0x0047 : "Flash fired, red-eye reduction mode, return light detected",
  1599. 0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
  1600. 0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
  1601. 0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
  1602. 0x0059 : "Flash fired, auto mode, red-eye reduction mode",
  1603. 0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
  1604. 0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
  1605. },
  1606. SensingMethod : {
  1607. 1 : "Not defined",
  1608. 2 : "One-chip color area sensor",
  1609. 3 : "Two-chip color area sensor",
  1610. 4 : "Three-chip color area sensor",
  1611. 5 : "Color sequential area sensor",
  1612. 7 : "Trilinear sensor",
  1613. 8 : "Color sequential linear sensor"
  1614. },
  1615. SceneCaptureType : {
  1616. 0 : "Standard",
  1617. 1 : "Landscape",
  1618. 2 : "Portrait",
  1619. 3 : "Night scene"
  1620. },
  1621. SceneType : {
  1622. 1 : "Directly photographed"
  1623. },
  1624. CustomRendered : {
  1625. 0 : "Normal process",
  1626. 1 : "Custom process"
  1627. },
  1628. WhiteBalance : {
  1629. 0 : "Auto white balance",
  1630. 1 : "Manual white balance"
  1631. },
  1632. GainControl : {
  1633. 0 : "None",
  1634. 1 : "Low gain up",
  1635. 2 : "High gain up",
  1636. 3 : "Low gain down",
  1637. 4 : "High gain down"
  1638. },
  1639. Contrast : {
  1640. 0 : "Normal",
  1641. 1 : "Soft",
  1642. 2 : "Hard"
  1643. },
  1644. Saturation : {
  1645. 0 : "Normal",
  1646. 1 : "Low saturation",
  1647. 2 : "High saturation"
  1648. },
  1649. Sharpness : {
  1650. 0 : "Normal",
  1651. 1 : "Soft",
  1652. 2 : "Hard"
  1653. },
  1654. SubjectDistanceRange : {
  1655. 0 : "Unknown",
  1656. 1 : "Macro",
  1657. 2 : "Close view",
  1658. 3 : "Distant view"
  1659. },
  1660. FileSource : {
  1661. 3 : "DSC"
  1662. },
  1663.  
  1664. Components : {
  1665. 0 : "",
  1666. 1 : "Y",
  1667. 2 : "Cb",
  1668. 3 : "Cr",
  1669. 4 : "R",
  1670. 5 : "G",
  1671. 6 : "B"
  1672. }
  1673. };
  1674.  
  1675. function addEvent(element, event, handler) {
  1676. if (element.addEventListener) {
  1677. element.addEventListener(event, handler, false);
  1678. } else if (element.attachEvent) {
  1679. element.attachEvent("on" + event, handler);
  1680. }
  1681. }
  1682.  
  1683. function imageHasData(img) {
  1684. return !!(img.exifdata);
  1685. }
  1686.  
  1687.  
  1688. function base64ToArrayBuffer(base64, contentType) {
  1689. contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
  1690. base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
  1691. var binary = atob(base64);
  1692. var len = binary.length;
  1693. var buffer = new ArrayBuffer(len);
  1694. var view = new Uint8Array(buffer);
  1695. for (var i = 0; i < len; i++) {
  1696. view[i] = binary.charCodeAt(i);
  1697. }
  1698. return buffer;
  1699. }
  1700.  
  1701. function objectURLToBlob(url, callback) {
  1702. // var http = new XMLHttpRequest();
  1703. // http.open("GET", url, true);
  1704. // http.responseType = "blob";
  1705. // http.onload = function(e) {
  1706. // if (this.status == 200 || this.status === 0) {
  1707. // callback(this.response);
  1708. // }
  1709. // };
  1710. // http.send();
  1711.  
  1712. // GM.xmlHttpRequest({
  1713. // method: "GET",
  1714. // url: url,
  1715. // onload: function(e) {
  1716. // if (this.status == 200 || this.status === 0) {
  1717. // callback(this.response);
  1718. // }
  1719. // }
  1720. // });
  1721. }
  1722.  
  1723. function getImageData(img, callback) {
  1724. function handleBinaryFile(binFile) {
  1725. var data = findEXIFinJPEG(binFile);
  1726. var iptcdata = findIPTCinJPEG(binFile);
  1727. img.exifdata = data || {};
  1728. img.iptcdata = iptcdata || {};
  1729. if (callback) {
  1730. callback.call(img);
  1731. }
  1732. }
  1733.  
  1734. if (img.src) {
  1735. if (/^data\:/i.test(img.src)) { // Data URI
  1736. var arrayBuffer = base64ToArrayBuffer(img.src);
  1737. handleBinaryFile(arrayBuffer);
  1738.  
  1739. } else if (/^blob\:/i.test(img.src)) { // Object URL
  1740. var fileReader = new FileReader();
  1741. fileReader.onload = function(e) {
  1742. handleBinaryFile(e.target.result);
  1743. };
  1744. objectURLToBlob(img.src, function (blob) {
  1745. fileReader.readAsArrayBuffer(blob);
  1746. });
  1747. } else {
  1748. // var http = new XMLHttpRequest();
  1749. // http.onload = function() {
  1750. // if (this.status == 200 || this.status === 0) {
  1751. // handleBinaryFile(http.response);
  1752. // } else {
  1753. // throw "Could not load image";
  1754. // }
  1755. // http = null;
  1756. // };
  1757. // http.open("GET", img.src, true);
  1758. // http.responseType = "arraybuffer";
  1759. // http.send(null);
  1760.  
  1761. GM.xmlHttpRequest({
  1762. method: "GET",
  1763. url: img.src,
  1764. responseType: 'arraybuffer',
  1765. onload: function(response) {
  1766. if (response.status == 200 || response.status === 0) {
  1767. handleBinaryFile(response.response);
  1768. }
  1769. }
  1770. });
  1771. }
  1772. } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
  1773. var fileReader = new FileReader();
  1774. fileReader.onload = function(e) {
  1775. if (debug) console.log("Got file of length " + e.target.result.byteLength);
  1776. handleBinaryFile(e.target.result);
  1777. };
  1778.  
  1779. fileReader.readAsArrayBuffer(img);
  1780. }
  1781. }
  1782.  
  1783. function findEXIFinJPEG(file) {
  1784. var dataView = new DataView(file);
  1785.  
  1786. if (debug) console.log("Got file of length " + file.byteLength);
  1787. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1788. if (debug) console.log("Not a valid JPEG");
  1789. return false; // not a valid jpeg
  1790. }
  1791.  
  1792. var offset = 2,
  1793. length = file.byteLength,
  1794. marker;
  1795.  
  1796. while (offset < length) {
  1797. if (dataView.getUint8(offset) != 0xFF) {
  1798. if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
  1799. return false; // not a valid marker, something is wrong
  1800. }
  1801.  
  1802. marker = dataView.getUint8(offset + 1);
  1803. if (debug) console.log(marker);
  1804.  
  1805. // we could implement handling for other markers here,
  1806. // but we're only looking for 0xFFE1 for EXIF data
  1807.  
  1808. if (marker == 225) {
  1809. if (debug) console.log("Found 0xFFE1 marker");
  1810.  
  1811. return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
  1812.  
  1813. // offset += 2 + file.getShortAt(offset+2, true);
  1814.  
  1815. } else {
  1816. offset += 2 + dataView.getUint16(offset+2);
  1817. }
  1818.  
  1819. }
  1820.  
  1821. }
  1822.  
  1823. function findIPTCinJPEG(file) {
  1824. var dataView = new DataView(file);
  1825.  
  1826. if (debug) console.log("Got file of length " + file.byteLength);
  1827. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1828. if (debug) console.log("Not a valid JPEG");
  1829. return false; // not a valid jpeg
  1830. }
  1831.  
  1832. var offset = 2,
  1833. length = file.byteLength;
  1834.  
  1835.  
  1836. var isFieldSegmentStart = function(dataView, offset){
  1837. return (
  1838. dataView.getUint8(offset) === 0x38 &&
  1839. dataView.getUint8(offset+1) === 0x42 &&
  1840. dataView.getUint8(offset+2) === 0x49 &&
  1841. dataView.getUint8(offset+3) === 0x4D &&
  1842. dataView.getUint8(offset+4) === 0x04 &&
  1843. dataView.getUint8(offset+5) === 0x04
  1844. );
  1845. };
  1846.  
  1847. while (offset < length) {
  1848.  
  1849. if ( isFieldSegmentStart(dataView, offset )){
  1850.  
  1851. // Get the length of the name header (which is padded to an even number of bytes)
  1852. var nameHeaderLength = dataView.getUint8(offset+7);
  1853. if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
  1854. // Check for pre photoshop 6 format
  1855. if(nameHeaderLength === 0) {
  1856. // Always 4
  1857. nameHeaderLength = 4;
  1858. }
  1859.  
  1860. var startOffset = offset + 8 + nameHeaderLength;
  1861. var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
  1862.  
  1863. return readIPTCData(file, startOffset, sectionLength);
  1864.  
  1865. break;
  1866.  
  1867. }
  1868.  
  1869.  
  1870. // Not the marker, continue searching
  1871. offset++;
  1872.  
  1873. }
  1874.  
  1875. }
  1876. var IptcFieldMap = {
  1877. 0x78 : 'caption',
  1878. 0x6E : 'credit',
  1879. 0x19 : 'keywords',
  1880. 0x37 : 'dateCreated',
  1881. 0x50 : 'byline',
  1882. 0x55 : 'bylineTitle',
  1883. 0x7A : 'captionWriter',
  1884. 0x69 : 'headline',
  1885. 0x74 : 'copyright',
  1886. 0x0F : 'category'
  1887. };
  1888. function readIPTCData(file, startOffset, sectionLength){
  1889. var dataView = new DataView(file);
  1890. var data = {};
  1891. var fieldValue, fieldName, dataSize, segmentType, segmentSize;
  1892. var segmentStartPos = startOffset;
  1893. while(segmentStartPos < startOffset+sectionLength) {
  1894. if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
  1895. segmentType = dataView.getUint8(segmentStartPos+2);
  1896. if(segmentType in IptcFieldMap) {
  1897. dataSize = dataView.getInt16(segmentStartPos+3);
  1898. segmentSize = dataSize + 5;
  1899. fieldName = IptcFieldMap[segmentType];
  1900. fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
  1901. // Check if we already stored a value with this name
  1902. if(data.hasOwnProperty(fieldName)) {
  1903. // Value already stored with this name, create multivalue field
  1904. if(data[fieldName] instanceof Array) {
  1905. data[fieldName].push(fieldValue);
  1906. }
  1907. else {
  1908. data[fieldName] = [data[fieldName], fieldValue];
  1909. }
  1910. }
  1911. else {
  1912. data[fieldName] = fieldValue;
  1913. }
  1914. }
  1915.  
  1916. }
  1917. segmentStartPos++;
  1918. }
  1919. return data;
  1920. }
  1921.  
  1922.  
  1923.  
  1924. function readTags(file, tiffStart, dirStart, strings, bigEnd) {
  1925. var entries = file.getUint16(dirStart, !bigEnd),
  1926. tags = {},
  1927. entryOffset, tag,
  1928. i;
  1929.  
  1930. for (i=0;i<entries;i++) {
  1931. entryOffset = dirStart + i*12 + 2;
  1932. tag = strings[file.getUint16(entryOffset, !bigEnd)];
  1933. if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
  1934. tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
  1935. }
  1936. return tags;
  1937. }
  1938.  
  1939.  
  1940. function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
  1941. var type = file.getUint16(entryOffset+2, !bigEnd),
  1942. numValues = file.getUint32(entryOffset+4, !bigEnd),
  1943. valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
  1944. offset,
  1945. vals, val, n,
  1946. numerator, denominator;
  1947.  
  1948. switch (type) {
  1949. case 1: // byte, 8-bit unsigned int
  1950. case 7: // undefined, 8-bit byte, value depending on field
  1951. if (numValues == 1) {
  1952. return file.getUint8(entryOffset + 8, !bigEnd);
  1953. } else {
  1954. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1955. vals = [];
  1956. for (n=0;n<numValues;n++) {
  1957. vals[n] = file.getUint8(offset + n);
  1958. }
  1959. return vals;
  1960. }
  1961.  
  1962. case 2: // ascii, 8-bit byte
  1963. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1964. return getStringFromDB(file, offset, numValues-1);
  1965.  
  1966. case 3: // short, 16 bit int
  1967. if (numValues == 1) {
  1968. return file.getUint16(entryOffset + 8, !bigEnd);
  1969. } else {
  1970. offset = numValues > 2 ? valueOffset : (entryOffset + 8);
  1971. vals = [];
  1972. for (n=0;n<numValues;n++) {
  1973. vals[n] = file.getUint16(offset + 2*n, !bigEnd);
  1974. }
  1975. return vals;
  1976. }
  1977.  
  1978. case 4: // long, 32 bit int
  1979. if (numValues == 1) {
  1980. return file.getUint32(entryOffset + 8, !bigEnd);
  1981. } else {
  1982. vals = [];
  1983. for (n=0;n<numValues;n++) {
  1984. vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
  1985. }
  1986. return vals;
  1987. }
  1988.  
  1989. case 5: // rational = two long values, first is numerator, second is denominator
  1990. if (numValues == 1) {
  1991. numerator = file.getUint32(valueOffset, !bigEnd);
  1992. denominator = file.getUint32(valueOffset+4, !bigEnd);
  1993. val = new Number(numerator / denominator);
  1994. val.numerator = numerator;
  1995. val.denominator = denominator;
  1996. return val;
  1997. } else {
  1998. vals = [];
  1999. for (n=0;n<numValues;n++) {
  2000. numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
  2001. denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
  2002. vals[n] = new Number(numerator / denominator);
  2003. vals[n].numerator = numerator;
  2004. vals[n].denominator = denominator;
  2005. }
  2006. return vals;
  2007. }
  2008.  
  2009. case 9: // slong, 32 bit signed int
  2010. if (numValues == 1) {
  2011. return file.getInt32(entryOffset + 8, !bigEnd);
  2012. } else {
  2013. vals = [];
  2014. for (n=0;n<numValues;n++) {
  2015. vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
  2016. }
  2017. return vals;
  2018. }
  2019.  
  2020. case 10: // signed rational, two slongs, first is numerator, second is denominator
  2021. if (numValues == 1) {
  2022. return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
  2023. } else {
  2024. vals = [];
  2025. for (n=0;n<numValues;n++) {
  2026. vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
  2027. }
  2028. return vals;
  2029. }
  2030. }
  2031. }
  2032.  
  2033. function getStringFromDB(buffer, start, length) {
  2034. var outstr = "";
  2035. for (n = start; n < start+length; n++) {
  2036. outstr += String.fromCharCode(buffer.getUint8(n));
  2037. }
  2038. return outstr;
  2039. }
  2040.  
  2041. function readEXIFData(file, start) {
  2042. if (getStringFromDB(file, start, 4) != "Exif") {
  2043. if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
  2044. return false;
  2045. }
  2046.  
  2047. var bigEnd,
  2048. tags, tag,
  2049. exifData, gpsData,
  2050. tiffOffset = start + 6;
  2051.  
  2052. // test for TIFF validity and endianness
  2053. if (file.getUint16(tiffOffset) == 0x4949) {
  2054. bigEnd = false;
  2055. } else if (file.getUint16(tiffOffset) == 0x4D4D) {
  2056. bigEnd = true;
  2057. } else {
  2058. if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  2059. return false;
  2060. }
  2061.  
  2062. if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
  2063. if (debug) console.log("Not valid TIFF data! (no 0x002A)");
  2064. return false;
  2065. }
  2066.  
  2067. var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);
  2068.  
  2069. if (firstIFDOffset < 0x00000008) {
  2070. if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
  2071. return false;
  2072. }
  2073.  
  2074. tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
  2075.  
  2076. if (tags.ExifIFDPointer) {
  2077. exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
  2078. for (tag in exifData) {
  2079. switch (tag) {
  2080. case "LightSource" :
  2081. case "Flash" :
  2082. case "MeteringMode" :
  2083. case "ExposureProgram" :
  2084. case "SensingMethod" :
  2085. case "SceneCaptureType" :
  2086. case "SceneType" :
  2087. case "CustomRendered" :
  2088. case "WhiteBalance" :
  2089. case "GainControl" :
  2090. case "Contrast" :
  2091. case "Saturation" :
  2092. case "Sharpness" :
  2093. case "SubjectDistanceRange" :
  2094. case "FileSource" :
  2095. exifData[tag] = StringValues[tag][exifData[tag]];
  2096. break;
  2097.  
  2098. case "ExifVersion" :
  2099. case "FlashpixVersion" :
  2100. exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
  2101. break;
  2102.  
  2103. case "ComponentsConfiguration" :
  2104. exifData[tag] =
  2105. StringValues.Components[exifData[tag][0]] +
  2106. StringValues.Components[exifData[tag][1]] +
  2107. StringValues.Components[exifData[tag][2]] +
  2108. StringValues.Components[exifData[tag][3]];
  2109. break;
  2110. }
  2111. tags[tag] = exifData[tag];
  2112. }
  2113. }
  2114.  
  2115. if (tags.GPSInfoIFDPointer) {
  2116. gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
  2117. for (tag in gpsData) {
  2118. switch (tag) {
  2119. case "GPSVersionID" :
  2120. gpsData[tag] = gpsData[tag][0] +
  2121. "." + gpsData[tag][1] +
  2122. "." + gpsData[tag][2] +
  2123. "." + gpsData[tag][3];
  2124. break;
  2125. }
  2126. tags[tag] = gpsData[tag];
  2127. }
  2128. }
  2129.  
  2130. return tags;
  2131. }
  2132.  
  2133. EXIF.getData = function(img, callback) {
  2134. if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false;
  2135.  
  2136. if (!imageHasData(img)) {
  2137. getImageData(img, callback);
  2138. } else {
  2139. if (callback) {
  2140. callback.call(img);
  2141. }
  2142. }
  2143. return true;
  2144. }
  2145.  
  2146. EXIF.getTag = function(img, tag) {
  2147. if (!imageHasData(img)) return;
  2148. return img.exifdata[tag];
  2149. }
  2150.  
  2151. EXIF.getAllTags = function(img) {
  2152. if (!imageHasData(img)) return {};
  2153. var a,
  2154. data = img.exifdata,
  2155. tags = {};
  2156. for (a in data) {
  2157. if (data.hasOwnProperty(a)) {
  2158. tags[a] = data[a];
  2159. }
  2160. }
  2161. return tags;
  2162. }
  2163.  
  2164. EXIF.pretty = function(img) {
  2165. if (!imageHasData(img)) return "";
  2166. var a,
  2167. data = img.exifdata,
  2168. strPretty = "";
  2169. for (a in data) {
  2170. if (data.hasOwnProperty(a)) {
  2171. if (typeof data[a] == "object") {
  2172. if (data[a] instanceof Number) {
  2173. strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
  2174. } else {
  2175. strPretty += a + " : [" + data[a].length + " values]\r\n";
  2176. }
  2177. } else {
  2178. strPretty += a + " : " + data[a] + "\r\n";
  2179. }
  2180. }
  2181. }
  2182. return strPretty;
  2183. }
  2184.  
  2185. EXIF.readFromBinaryFile = function(file) {
  2186. return findEXIFinJPEG(file);
  2187. }
  2188.  
  2189. if (typeof define === 'function' && define.amd) {
  2190. define('exif-js', [], function() {
  2191. return EXIF;
  2192. });
  2193. }
  2194. }.call(this));
  2195. // -- https://github.com/exif-js/exif-js
  2196.