Geocaching.com + Project-GC

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

2020-03-09 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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