Geocaching.com + Project-GC

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

2018-10-29 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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