Geocaching.com + Project-GC

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

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

  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.4
  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. // Add an alert in top if there are Found it-logs which doesn't seem to fulfill the requirements
  568. if(challengeCheckerResults !== false) {
  569. var suspiciousFoundItLogs = [];
  570. for(var logId in challengeCheckerResults) {
  571. if(typeof challengeCheckerResults[logId] !== 'undefined' && challengeCheckerResults[logId]['status'] == 'fail') {
  572. suspiciousFoundItLogs.push(logId);
  573. }
  574. }
  575.  
  576. if(suspiciousFoundItLogs.length != 0) {
  577. var suspiciousFoundItLog = '<p style="color: #ff6c00;" class=" NoBottomSpacing"><strong>Cache Issues:</strong></p>\
  578. <ul style="color: #ff6c00;" class="">\
  579. <li>The following Found it logs might not fulfill the requirements:<br>';
  580.  
  581. for(var i = 0 ; i < suspiciousFoundItLogs.length ; i++) {
  582. suspiciousFoundItLog = suspiciousFoundItLog + ' <a href="https://www.geocaching.com/seek/log.aspx?LID=' + suspiciousFoundItLogs[i] + '">' + challengeCheckerResults[suspiciousFoundItLogs[i]]['profileName'] + '</a><br>';
  583. }
  584. 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>';
  585.  
  586. $('div.span-6.right.last').last().next().after(suspiciousFoundItLog);
  587. }
  588. }
  589. //--
  590.  
  591.  
  592. if (result.status == 'OK' && typeof cacheData !== 'undefined') {
  593.  
  594. // If placed by != owner, show the real owner as well.
  595. if (placedBy !== cacheOwner) {
  596. $('#ctl00_ContentBody_mcd1 span.message__owner').before(' (' + cacheOwner + ')');
  597. }
  598.  
  599. // Append link to Profile Stats for the cache owner
  600. // Need to real cache owner name from PGC since the web only has placed by
  601. if (IsSettingEnabled('profileStatsLinks')) {
  602. $('#ctl00_ContentBody_mcd1 span.message__owner').before('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(cacheOwner) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>');
  603. }
  604.  
  605. // Add FP/FP%/FPW below the current FP
  606. if (IsSettingEnabled('addPgcFp')) {
  607. fp = parseInt(+cacheData.favorite_points, 10),
  608. fpp = parseInt(+cacheData.favorite_points_pct, 10),
  609. fpw = parseInt(+cacheData.favorite_points_wilson, 10);
  610. $('#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>');
  611. $('.favorite-container').css({
  612. "border-bottom-left-radius": "0",
  613. "border-bottom-right-radius": "0"
  614. });
  615. }
  616.  
  617. // Add elevation (Metres above mean sea level = mamsl)
  618. if (IsSettingEnabled('addElevation')) {
  619. var formattedElevation = FormatDistance(cacheData.elevation),
  620. elevationUnit = IsSettingEnabled('imperial') ? 'ft' : 'm',
  621. elevationArrow = (cacheData.elevation >= 0) ? '&#x21a5;' : '&#x21a7;';
  622. elevation = formattedElevation + ' ' + elevationUnit + ' ' + elevationArrow;
  623.  
  624. if (cacheData.elevation >= 0) {
  625. html = '<span> (' + elevation + ')</span>';
  626. } else {
  627. html = '<span class="OldWarning"> (' + elevation + ')</span>';
  628. }
  629.  
  630. ($('#uxLatLonLink').length > 0 ? $('#uxLatLonLink') : $('#uxLatLon').parent()).after(html);
  631. }
  632.  
  633. // Add PGC location
  634. if (IsSettingEnabled('addPGCLocation')) {
  635. if (cacheData.country.length > 0) {
  636. location.push(cacheData.country);
  637. }
  638. if (cacheData.region !== null && cacheData.region.length > 0) {
  639. location.push(cacheData.region);
  640. }
  641. if (cacheData.county !== null && cacheData.county.length > 0) {
  642. location.push(cacheData.county);
  643. }
  644. location = location.join(' / ');
  645.  
  646. var gccomLocationData = $('#ctl00_ContentBody_Location').html();
  647. $('#ctl00_ContentBody_Location').html('<span style="text-decoration: line-through;">' + gccomLocationData + '</span><br><span>' + location + '</span>');
  648. }
  649.  
  650.  
  651. // Add challenge checkers
  652. if (IsSettingEnabled('addChallengeCheckers') && challengeCheckerTagIds.length > 0) {
  653. html = '<div id="checkerWidget" class="CacheDetailNavigationWidget TopSpacing BottomSpacing"><h3 class="WidgetHeader">Challenge checker(s)</h3><div class="WidgetBody" id="PGC_ChallengeCheckers">';
  654. for (var i = 0; i < challengeCheckerTagIds.length; i++) {
  655. 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>';
  656. }
  657. html += '</div></div>';
  658. $('#ctl00_ContentBody_detailWidget').before(html);
  659. }
  660.  
  661. // Display warning message if cache is logged and no longer be logged
  662. if (cacheData.locked) {
  663. $('ul.OldWarning').append('<li>This cache has been locked and can no longer be logged.</li>');
  664. }
  665.  
  666. // Add geocache logs per profile country table
  667. if (IsSettingEnabled('addGeocacheLogsPerProfileCountry')) {
  668. html = '<div id="geocacheLogsPerCountry" style="border: dashed; border-color: #aaa; border-width: thin;">';
  669.  
  670. if(typeof(geocacheLogsPerCountry['willAttend']) != 'undefined' && geocacheLogsPerCountry['willAttend'].length > 0) {
  671. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong>Will attend logs per country</strong> <small>according to Project-GC.com</small></p>';
  672. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  673. for (var i = 0; i < geocacheLogsPerCountry['willAttend'].length; i++) {
  674. 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>';
  675. }
  676. html += '</ul>';
  677. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['willAttend'].length + ' unique countries</small></span>';
  678. 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>';
  679. }
  680.  
  681. if(typeof(geocacheLogsPerCountry['found']) != 'undefined' && geocacheLogsPerCountry['found'].length > 0) {
  682. html += '<p style="margin-left: 10px; margin-bottom: 0;"><strong>Found logs per country</strong> <small>according to Project-GC.com</small></p>';
  683. html += '<ul style="list-style: none; margin-left: 0; margin-bottom: 0;">';
  684. for (var i = 0; i < geocacheLogsPerCountry['found'].length; i++) {
  685. 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>';
  686. }
  687. html += '</ul>';
  688. html += '<span style="display: block; text-align: right; padding-right: 10px;"><small>' + geocacheLogsPerCountry['found'].length + ' unique countries</small></span>';
  689. }
  690.  
  691. html += '</div>';
  692.  
  693. $('#ctl00_ContentBody_lblFindCounts').append(html);
  694. }
  695.  
  696. // Add my number of logs above the log button
  697. if (IsSettingEnabled('addMyNumberOfLogs')) {
  698. $('<p style="margin: 0;"><small>You have ' + myNumberOfLogs + ' logs according to Project-GC</small></p>').insertBefore('#ctl00_ContentBody_GeoNav_logButton');
  699. }
  700.  
  701. // Append the same number to the added logbook link
  702. if (IsSettingEnabled('logbookLinks')) {
  703. $('#pgc-logbook-yours').html('Yours (' + myNumberOfLogs + ')')
  704.  
  705. }
  706. }
  707.  
  708.  
  709. // Since everything in the logbook is ajax, we need to wait for the elements
  710. // We also want to wait on challengeCheckerResults
  711. waitForKeyElements('#cache_logs_table tbody tr', Logbook);
  712. }
  713. });
  714. }
  715.  
  716. // Tidy the web
  717. if (IsSettingEnabled('tidy')) {
  718. $('#ctl00_divContentMain p.Clear').css('margin', '0');
  719. $('div.Note.PersonalCacheNote').css('margin', '0');
  720. $('h3.CacheDescriptionHeader').remove();
  721. $('#ctl00_ContentBody_EncryptionKey').remove();
  722. $('#ctl00_ContentBody_GeoNav_foundStatus').css('margin-bottom', '0');
  723. }
  724.  
  725. // Make it easier to copy the gccode
  726. if (IsSettingEnabled('makeCopyFriendly')) {
  727. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').
  728. html('<div style="margin-right: 15px; margin-bottom: 10px;"><p id="ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoCode" style="font-size: 125%; margin-bottom: 0">' + gccode + '</p>' +
  729. '<input size="25" type="text" value="https://coord.info/' + encodeURIComponent(gccode) + '" onclick="this.setSelectionRange(0, this.value.length);"></div>');
  730. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').css('font-weight', 'inherit').css('margin-right', '27px');
  731. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div').css('margin', '0 0 5px 0');
  732. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel div p').css('font-weight', 'bold');
  733. }
  734.  
  735. // Add PGC Map links
  736. if (IsSettingEnabled('addPgcMapLinks')) {
  737. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  738. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  739. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1");
  740. // var mapUrl = pgcUrl + 'Maps/mapcompare/?profile_name=' + gccomUsername +
  741. // '&nonefound=on&ownfound=on&location=' + latitude + ',' + longitude +
  742. // '&max_distance=5&submit=Filter';
  743. var mapUrl = pgcUrl + 'LiveMap/#c=' + latitude + ',' + longitude + ';z=14';
  744.  
  745. // $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  746. // '<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>'
  747. // );
  748. $('#ctl00_ContentBody_CoordInfoLinkControl1_uxCoordInfoLinkPanel').append(
  749. '<div style="margin-bottom: 8px;"><a target="_blank" href="' + mapUrl + '">Project-GC Live map</a></div>'
  750. );
  751. }
  752.  
  753. // Remove the UTM coordinates
  754. // $('#ctl00_ContentBody_CacheInformationTable div.LocationData div.span-9 p.NoBottomSpacing br').remove();
  755. if (IsSettingEnabled('removeUTM')) {
  756. $('#ctl00_ContentBody_LocationSubPanel').html('');
  757.  
  758. // And move the "N 248.3 km from your home location"
  759. $('#ctl00_ContentBody_LocationSubPanel').after($('#lblDistFromHome'));
  760. }
  761.  
  762. // Remove ads
  763. // PGC can't really do this officially
  764. // $('#ctl00_ContentBody_uxBanManWidget').remove();
  765.  
  766. // Remove disclaimer
  767. if (IsSettingEnabled('removeDisclaimer')) {
  768. $('#divContentMain div.span-17 div.Note.Disclaimer').remove();
  769. }
  770.  
  771. // If the first log is a DNF, display a blue warning on top of the page
  772. if($('#cache_logs_table tr:first td div.LogDisplayRight strong img').attr('src') === '/images/logtypes/3.png') {
  773. var htmlFirstLogDnf = '<p style="color: #006cff;" class=" NoBottomSpacing"><strong>Cache Issues:</strong></p>\
  774. <ul style="color: #006cff;" class="">\
  775. <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>\
  776. </ul>';
  777. $('div.span-6.right.last').last().next().after(htmlFirstLogDnf);
  778.  
  779. }
  780.  
  781. // Collapse download links
  782. // http://www.w3schools.com/charsets/ref_utf_geometric.asp (x25BA, x25BC)
  783. if (IsSettingEnabled('collapseDownloads')) {
  784. $('<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');
  785. $('#divContentMain div.DownloadLinks, #DownloadLinksToggle .arrow.open').hide();
  786. }
  787.  
  788. // Resolve the coordinates into an address
  789. if (IsSettingEnabled('addAddress')) {
  790. coordinates = $('#ctl00_ContentBody_MapLinks_MapLinks li a').attr('href'),
  791. latitude = coordinates.replace(/.*lat=([^&]*)&lng=.*/, "$1"),
  792. longitude = coordinates.replace(/.*&lng=(.*)$/, "$1"),
  793. url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=false';
  794.  
  795. GM.xmlHttpRequest({
  796. method: "GET",
  797. url: url,
  798. onload: function(response) {
  799. var result = JSON.parse(response.responseText);
  800. if (result.status !== 'OK') {
  801. return false;
  802. }
  803. var formattedAddress = result.results[0].formatted_address;
  804. $('#ctl00_ContentBody_LocationSubPanel').append(formattedAddress + '<br />');
  805. }
  806. });
  807. }
  808.  
  809. // Add number of finds per type to the top
  810. if (IsSettingEnabled('cloneLogsPerType') && typeof $('#ctl00_ContentBody_lblFindCounts').html() !== 'undefined') {
  811. $('#ctl00_ContentBody_CacheInformationTable').before('<div>' + $('#ctl00_ContentBody_lblFindCounts').html() + '</div>');
  812. }
  813.  
  814. // Add link to PGC gallery
  815. if (subscription && IsSettingEnabled('addPgcGalleryLinks')) {
  816. var html = '<a href="' + pgcUrl + 'Tools/Gallery?gccode=' + gccode + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a> ';
  817. $('.CacheDetailNavigation ul li:first').append(html);
  818. }
  819.  
  820. // Add map links for each bookmarklist
  821. if (IsSettingEnabled('addMapBookmarkListLinks')) {
  822. $('ul.BookmarkList li').each(function() {
  823. var guid = $(this).children(':nth-child(1)').attr('href').replace(/.*\?guid=(.*)/, "$1");
  824. var owner = $(this).children(':nth-child(3)').text();
  825.  
  826. // Add the map link
  827. url = 'https://project-gc.com/Tools/MapBookmarklist?owner_name=' + encodeURIComponent(owner) + '&guid=' + encodeURIComponent(guid);
  828. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + mapLinkIcon + '" title="Map with Project-GC"></a>');
  829.  
  830. // Add gallery link for the bookmark list
  831. url = 'https://project-gc.com/Tools/Gallery?bml_owner=' + encodeURIComponent(owner) + '&bml_guid=' + encodeURIComponent(guid) + '&submit=Filter';
  832. $(this).children(':nth-child(1)').append('&nbsp;<a href="' + url + '"><img src="' + galleryLinkIcon + '" title="Project-GC Gallery"></a>');
  833.  
  834. // Add profile stats link to the owner
  835. url = 'https://project-gc.com/ProfileStats/' + encodeURIComponent(owner);
  836. $(this).children(':nth-child(3)').append('&nbsp;<a href="' + url + '"><img src="' + externalLinkIcon + '" title="Project-GC Profile stats"></a>');
  837. });
  838. }
  839.  
  840. // Decrypt the hint
  841. if (IsSettingEnabled('decryptHints')) {
  842. unsafeWindow.dht();
  843. }
  844.  
  845. // VGPS form
  846. if (IsSettingEnabled('showVGPS')) {
  847. GM.xmlHttpRequest({
  848. method: "GET",
  849. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  850. onload: function(response) {
  851. var result = JSON.parse(response.responseText),
  852. vgpsLists = result.data.lists,
  853. selected = result.data.selected,
  854. existsIn = result.data.existsIn,
  855. selectedContent,
  856. existsContent,
  857. html = '<li><img width="16" height="16" src="https://cdn2.project-gc.com/images/mobile_telephone_32.png"> <strong>Add to VGPS</strong><br />',
  858. listId;
  859.  
  860. html += '<select id="comboVGPS" style="width: 138px;">';
  861. for (listId in vgpsLists) {
  862. selectedContent = '';
  863. if (+selected === +listId) {
  864. selectedContent = ' selected="selected"';
  865. }
  866.  
  867. existsContent = '';
  868. if (existsIn.indexOf(listId) > -1) {
  869. existsContent = ' data-exists="true"';
  870. }
  871. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  872. }
  873. html += '</select>';
  874. if (existsIn.indexOf(String(selected)) == -1) {
  875. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  876. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  877. } else {
  878. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  879. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  880. }
  881. html += '</li>';
  882.  
  883. $('div.CacheDetailNavigation ul:first').append(html);
  884.  
  885. $('#comboVGPS').change(function() {
  886. selected = $(this).find(':selected').val();
  887. if (existsIn.indexOf(String(selected)) == -1) {
  888. $('#btnAddToVGPS').css('display', '');
  889. $('#btnRemoveFromVGPS').css('display', 'none');
  890. } else {
  891. $('#btnAddToVGPS').css('display', 'none');
  892. $('#btnRemoveFromVGPS').css('display', '');
  893. }
  894. });
  895. $('#btnAddToVGPS').click(function(event) {
  896. event.preventDefault();
  897. addToVGPS();
  898. });
  899. $('#btnRemoveFromVGPS').click(function(event) {
  900. event.preventDefault();
  901. removeFromVGPS();
  902. });
  903. }
  904. });
  905. }
  906.  
  907. // Change font in personal cache note to monospaced
  908. if (IsSettingEnabled('cachenoteFont')) {
  909. $("#cache_note").css("font-family", "monospace").css("font-size", "12px");
  910. $("#cache_note").on("DOMSubtreeModified", function() {
  911. $(".inplace_field").css("font-family", "monospace").css("font-size", "12px");
  912. });
  913. }
  914.  
  915.  
  916. if (IsSettingEnabled('logbookLinks')) {
  917. $('\
  918. <span>&nbsp;|&nbsp;</span><a id="pgc-logbook-yours" href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-2">Yours</a>\
  919. <span>&nbsp;|&nbsp;</span><a href="' + $('#ctl00_ContentBody_uxLogbookLink').attr('href') + '#tabs-3">Friends\'</a>\
  920. ').insertAfter( $('#ctl00_ContentBody_uxLogbookLink') );
  921. }
  922. }
  923.  
  924. function Page_Logbook() {
  925. // Since everything in the logbook is ajax, we need to wait for the elements
  926. waitForKeyElements('#AllLogs tbody tr', Logbook);
  927. waitForKeyElements('#PersonalLogs tbody tr', Logbook);
  928. waitForKeyElements('#FriendLogs tbody tr', Logbook);
  929. }
  930.  
  931. function Logbook(jNode) {
  932. // Add Profile stats and gallery links after each user
  933. if (IsSettingEnabled('profileStatsLinks')) {
  934. var profileNameElm = $(jNode).find('a.h5');
  935. var profileName = profileNameElm.html();
  936.  
  937. if (typeof profileName !== 'undefined') {
  938. profileName = profileNameElm.append('<a href="' + pgcUrl + 'ProfileStats/' + encodeURIComponent(profileName) + '"><img src="' + externalLinkIcon + '" title="PGC Profile Stats"></a>')
  939. .append('<a href="' + pgcUrl + 'Tools/Gallery?profile_name=' + encodeURIComponent(profileName) + '&submit=Filter"><img src="' + galleryLinkIcon + '" title="PGC Gallery"></a>');
  940. }
  941. }
  942.  
  943. if(IsSettingEnabled('parseExifLocation')) {
  944. $(jNode).find('ul.LogImagesTable li>a').each(function() {
  945. var url = $(this).attr('href');
  946. var thumbnailUrl = url.replace('/img.geocaching.com/cache/log/large/', '/img.geocaching.com/cache/log/thumb/');
  947.  
  948. var imgElm = $(this).find('img');
  949. $(imgElm).attr('src', thumbnailUrl);
  950. $(imgElm).removeAttr('width');
  951. $(imgElm).removeAttr('height');
  952. $(imgElm).next().css('vertical-align', 'top');
  953.  
  954. $(imgElm).load(function() {
  955. EXIF.getData($(imgElm)[0], function() {
  956. // console.log(EXIF.pretty(this));
  957. var coords = GetCoordinatesFromExif(this);
  958. if(coords != false) {
  959. $('<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());
  960. }
  961. });
  962. });
  963.  
  964. });
  965. }
  966.  
  967. if(IsSettingEnabled('addCachedChallengeCheckerResults')) {
  968. var classes = $(jNode).attr('class');
  969. var logId = classes.match(/l-[0-9]+/)[0].replace('l-', '');
  970. if(typeof challengeCheckerResults[logId] !== 'undefined') {
  971. if(challengeCheckerResults[logId]['status'] == 'success') {
  972. $(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>');
  973. }
  974. else if(challengeCheckerResults[logId]['status'] == 'fail') {
  975. $(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>');
  976. }
  977. }
  978. }
  979.  
  980.  
  981. // Save to latest logs
  982. if (latestLogs.length < 5) {
  983. var node = $(jNode).find('div.HalfLeft.LogType h4 img[src]'),
  984. logType = {};
  985.  
  986. if (node.length === 0)
  987. return false;
  988.  
  989. logType = {
  990. 'src': node.attr('src'),
  991. 'alt': node.attr('alt'),
  992. 'title': node.attr('title')
  993. };
  994.  
  995. logType.id = +logType.src.replace(/.*logtypes\/(\d+)\.png/, "$1");
  996.  
  997. // First entry is undefined, due to ajax
  998. if (logType.src) {
  999. latestLogs.push('<img src="' + logType.src + '" alt="' + logType.alt + '" title="' + logType.title + '" style="margin-bottom: -4px; margin-right: 1px;">');
  1000. // 2 = found, 3 = dnf, 4 = note, 5 = archive, 22 = disable, 24 = publish, 45 = nm, 46 = owner maintenance, 68 = reviewer note
  1001. if ($.inArray(logType.id, [3, 5, 22, 45, 68]) !== -1) {
  1002. latestLogsAlert = true;
  1003. }
  1004. }
  1005.  
  1006. // Show latest logs
  1007. // Enhanced Nov 2016 to show icons for up to 5 of the latest logs
  1008. if (IsSettingEnabled('addLatestLogs') && latestLogs.length <= 5) {
  1009. var images = latestLogs.join('');
  1010.  
  1011. $('#latestLogIcons').remove();
  1012. $('#ctl00_ContentBody_size p').removeClass('AlignCenter').addClass('NoBottomSpacing');
  1013.  
  1014. if (latestLogsAlert) {
  1015. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing OldWarning" id="latestLogIcons"><strong>Latest logs:</strong> <span>' + images + '</span></p>');
  1016. } else {
  1017. $('#ctl00_ContentBody_size').append('<p class="NoBottomSpacing" id="latestLogIcons">Latest logs: <span>' + images + '</span></p>');
  1018. }
  1019. }
  1020. }
  1021. }
  1022.  
  1023. function Page_Map() {
  1024. if (IsSettingEnabled('showVGPS')) {
  1025.  
  1026. setTimeout(function() {
  1027. $('#map_canvas div.leaflet-popup-pane').bind('DOMSubtreeModified', function() {
  1028. if ($('#pgc_vgps').length === 0) {
  1029. var gccode = $('#gmCacheInfo div.code').text();
  1030.  
  1031. $('#gmCacheInfo div.links').after('<div id="pgc_vgps"></div>');
  1032.  
  1033. GM.xmlHttpRequest({
  1034. method: "GET",
  1035. url: pgcApiUrl + 'GetExistingVGPSLists?gccode=' + gccode,
  1036. onload: function(response) {
  1037.  
  1038. var result = JSON.parse(response.responseText),
  1039. vgpsLists = result.data.lists,
  1040. selected = result.data.selected,
  1041. existsIn = result.data.existsIn,
  1042. selectedContent,
  1043. existsContent,
  1044. html,
  1045. listId;
  1046.  
  1047.  
  1048. html = '<img src="https://cdn2.project-gc.com/images/mobile_telephone_32.png" style="width: 24px; height: 24px; margin-bottom: -6px;">';
  1049.  
  1050. html += '<select id="comboVGPS" style="margin-bottom: 4px;">';
  1051. for (listId in vgpsLists) {
  1052. selectedContent = '';
  1053. if (+selected === +listId) {
  1054. selectedContent = ' selected="selected"';
  1055. }
  1056.  
  1057. html += '<option value="' + listId + '"' + selectedContent + existsContent + '>' + vgpsLists[listId].name + '</option>';
  1058. }
  1059. html += '</select>';
  1060.  
  1061. if (existsIn.indexOf(String(selected)) == -1) {
  1062. html += '&nbsp;<button id="btnAddToVGPS">+</button>';
  1063. html += '&nbsp;<button id="btnRemoveFromVGPS" style="display: none;">-</button>';
  1064. } else {
  1065. html += '&nbsp;<button id="btnAddToVGPS" style="display: none;">+</button>';
  1066. html += '&nbsp;<button id="btnRemoveFromVGPS">-</button>';
  1067. }
  1068.  
  1069. $('#pgc_vgps').html(html);
  1070.  
  1071.  
  1072. $('#btnAddToVGPS').click(function(event) {
  1073. event.preventDefault();
  1074. addToVGPS(gccode);
  1075. });
  1076. $('#btnRemoveFromVGPS').click(function(event) {
  1077. event.preventDefault();
  1078. removeFromVGPS(gccode);
  1079. });
  1080. }
  1081. });
  1082. }
  1083. });
  1084. }, 500);
  1085. }
  1086.  
  1087. }
  1088.  
  1089. function Page_Gallery() {
  1090. // Find location data in exif tags
  1091. if(IsSettingEnabled('parseExifLocation')) {
  1092. $(window).load(function() { // Wait until page is loaded. If the images aren't loaded before this starts it will fail.
  1093. $('#ctl00_ContentBody_GalleryItems_DataListGallery img').each(function() {
  1094. EXIF.getData($(this)[0], function() {
  1095. // console.log(EXIF.pretty(this));
  1096. var coords = GetCoordinatesFromExif(this);
  1097. if(coords != false) {
  1098. $('<span class="OldWarning">EXIF Location<br><a href="https://maps.google.com/?q=' + coords + '" target="_blank">' + coords + '</a></span>').insertAfter(this.parentNode);
  1099. }
  1100. });
  1101. });
  1102. });
  1103. }
  1104. }
  1105.  
  1106. function Page_Bookmarks() {
  1107. var owner_name = $("#ctl00_ContentBody_ListInfo_uxListOwner").text();
  1108.  
  1109. var search = window.location.search;
  1110. var guid_start = search.indexOf("guid=");
  1111. if (guid_start == -1) {
  1112. /* the guid= not found in URL
  1113. * something is wrong so we will not generate bad URL
  1114. */
  1115. return;
  1116. }
  1117. var guid = search.substr(guid_start + 5/*, eof */);
  1118.  
  1119. var url = "https://project-gc.com/Tools/MapBookmarklist?owner_name=" + owner_name + "&guid=" + guid;
  1120. var icon = "https://cdn2.project-gc.com/images/map_app_16.png";
  1121.  
  1122. /* Heading link */
  1123. var html = ' <a href="' + url + '" title="Map this Bookmark list using Project-GC" style="padding-left:20px;"><img src="' + icon + '" /> Map this!</a>';
  1124.  
  1125. $("#ctl00_ContentBody_lbHeading").after(html);
  1126.  
  1127. /* Footer button */
  1128. var html2 = '<p><input type="button" onclick="window.location.href= \'' + url + '\'" value="Map this Bookmark list on Project-GC" /></p>';
  1129.  
  1130. $("#ctl00_ContentBody_ListInfo_btnDownload").parent().before(html2);
  1131. }
  1132.  
  1133. function Page_Drafts() {
  1134. if (IsSettingEnabled("openDraftLogInSameWindow")) {
  1135. waitForKeyElements('#draftsHub > ul.draft-list > li.draft-item', Draft);
  1136. }
  1137. }
  1138.  
  1139. function Draft(jNode) {
  1140. $(jNode).find(".draft-content > a").removeAttr('target');
  1141. }
  1142.  
  1143. function Page_Messagecenter() {
  1144. var target = document.getElementById('currentMessage');
  1145. var observer = new MutationObserver(function(mutations) {
  1146. mutations.forEach(function(mutation) {
  1147. if(mutation.type === "childList") {
  1148. var userlink = $(".user-meta a.current-user-image").attr("href"), username = $(".user-meta span.current-user-name").html();
  1149. $(".user-meta span.current-user-name").html("<a href='"+userlink+"'>"+username+"</a>");
  1150. }
  1151. });
  1152. });
  1153.  
  1154. var config = { childList: true };
  1155. observer.observe(target, config);
  1156. }
  1157.  
  1158. function Page_PrintCachePage() {
  1159. // Remove the disclaimer
  1160. $('div.TermsWidget').css('display', 'none');
  1161.  
  1162.  
  1163. // 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.
  1164. if( getUrlParameter('lc') === false ) {
  1165. $('div.item.ui-widget > div.item-header > h2.ui-sortable-handle').each(function() {
  1166. if( $(this).html() == 'Logs' ) { // Will only work with English
  1167. $(this).parent().parent().addClass('no-print').css('display', 'none');
  1168. return false; // Break .each loop
  1169. }
  1170. });
  1171. }
  1172.  
  1173.  
  1174. if(IsSettingEnabled('hideMapFromPrintCachePage')) {
  1175. $('#map').parent().parent().addClass('no-print');
  1176. $('#map').parent().prev().children('span.ui-icon').removeClass('ui-icon-minusthick').addClass('ui-icon-plusthick');
  1177. $('#map').parent().css('display', 'none');
  1178. }
  1179. }
  1180.  
  1181.  
  1182. function padLeft(str, n, padstr){
  1183. return Array(n-String(str).length+1).join(padstr||'0')+str;
  1184. }
  1185.  
  1186. function getUrlParameter(sParam) {
  1187. var sPageURL = decodeURIComponent(window.location.search.substring(1)),
  1188. sURLVariables = sPageURL.split('&'),
  1189. sParameterName,
  1190. i;
  1191.  
  1192. for (i = 0; i < sURLVariables.length; i++) {
  1193. sParameterName = sURLVariables[i].split('=');
  1194.  
  1195. if (sParameterName[0] === sParam) {
  1196. return sParameterName[1] === undefined ? true : sParameterName[1];
  1197. }
  1198. }
  1199.  
  1200. return false;
  1201. }
  1202. }());
  1203.  
  1204.  
  1205.  
  1206. // https://github.com/exif-js/exif-js adjusted to use GM.xmlHttpRequest
  1207. (function() {
  1208. var debug = false;
  1209.  
  1210. var root = this;
  1211.  
  1212. var EXIF = function(obj) {
  1213. if (obj instanceof EXIF) return obj;
  1214. if (!(this instanceof EXIF)) return new EXIF(obj);
  1215. this.EXIFwrapped = obj;
  1216. };
  1217.  
  1218. if (typeof exports !== 'undefined') {
  1219. if (typeof module !== 'undefined' && module.exports) {
  1220. exports = module.exports = EXIF;
  1221. }
  1222. exports.EXIF = EXIF;
  1223. } else {
  1224. root.EXIF = EXIF;
  1225. }
  1226.  
  1227. var ExifTags = EXIF.Tags = {
  1228.  
  1229. // version tags
  1230. 0x9000 : "ExifVersion", // EXIF version
  1231. 0xA000 : "FlashpixVersion", // Flashpix format version
  1232.  
  1233. // colorspace tags
  1234. 0xA001 : "ColorSpace", // Color space information tag
  1235.  
  1236. // image configuration
  1237. 0xA002 : "PixelXDimension", // Valid width of meaningful image
  1238. 0xA003 : "PixelYDimension", // Valid height of meaningful image
  1239. 0x9101 : "ComponentsConfiguration", // Information about channels
  1240. 0x9102 : "CompressedBitsPerPixel", // Compressed bits per pixel
  1241.  
  1242. // user information
  1243. 0x927C : "MakerNote", // Any desired information written by the manufacturer
  1244. 0x9286 : "UserComment", // Comments by user
  1245.  
  1246. // related file
  1247. 0xA004 : "RelatedSoundFile", // Name of related sound file
  1248.  
  1249. // date and time
  1250. 0x9003 : "DateTimeOriginal", // Date and time when the original image was generated
  1251. 0x9004 : "DateTimeDigitized", // Date and time when the image was stored digitally
  1252. 0x9290 : "SubsecTime", // Fractions of seconds for DateTime
  1253. 0x9291 : "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
  1254. 0x9292 : "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
  1255.  
  1256. // picture-taking conditions
  1257. 0x829A : "ExposureTime", // Exposure time (in seconds)
  1258. 0x829D : "FNumber", // F number
  1259. 0x8822 : "ExposureProgram", // Exposure program
  1260. 0x8824 : "SpectralSensitivity", // Spectral sensitivity
  1261. 0x8827 : "ISOSpeedRatings", // ISO speed rating
  1262. 0x8828 : "OECF", // Optoelectric conversion factor
  1263. 0x9201 : "ShutterSpeedValue", // Shutter speed
  1264. 0x9202 : "ApertureValue", // Lens aperture
  1265. 0x9203 : "BrightnessValue", // Value of brightness
  1266. 0x9204 : "ExposureBias", // Exposure bias
  1267. 0x9205 : "MaxApertureValue", // Smallest F number of lens
  1268. 0x9206 : "SubjectDistance", // Distance to subject in meters
  1269. 0x9207 : "MeteringMode", // Metering mode
  1270. 0x9208 : "LightSource", // Kind of light source
  1271. 0x9209 : "Flash", // Flash status
  1272. 0x9214 : "SubjectArea", // Location and area of main subject
  1273. 0x920A : "FocalLength", // Focal length of the lens in mm
  1274. 0xA20B : "FlashEnergy", // Strobe energy in BCPS
  1275. 0xA20C : "SpatialFrequencyResponse", //
  1276. 0xA20E : "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
  1277. 0xA20F : "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
  1278. 0xA210 : "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
  1279. 0xA214 : "SubjectLocation", // Location of subject in image
  1280. 0xA215 : "ExposureIndex", // Exposure index selected on camera
  1281. 0xA217 : "SensingMethod", // Image sensor type
  1282. 0xA300 : "FileSource", // Image source (3 == DSC)
  1283. 0xA301 : "SceneType", // Scene type (1 == directly photographed)
  1284. 0xA302 : "CFAPattern", // Color filter array geometric pattern
  1285. 0xA401 : "CustomRendered", // Special processing
  1286. 0xA402 : "ExposureMode", // Exposure mode
  1287. 0xA403 : "WhiteBalance", // 1 = auto white balance, 2 = manual
  1288. 0xA404 : "DigitalZoomRation", // Digital zoom ratio
  1289. 0xA405 : "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
  1290. 0xA406 : "SceneCaptureType", // Type of scene
  1291. 0xA407 : "GainControl", // Degree of overall image gain adjustment
  1292. 0xA408 : "Contrast", // Direction of contrast processing applied by camera
  1293. 0xA409 : "Saturation", // Direction of saturation processing applied by camera
  1294. 0xA40A : "Sharpness", // Direction of sharpness processing applied by camera
  1295. 0xA40B : "DeviceSettingDescription", //
  1296. 0xA40C : "SubjectDistanceRange", // Distance to subject
  1297.  
  1298. // other tags
  1299. 0xA005 : "InteroperabilityIFDPointer",
  1300. 0xA420 : "ImageUniqueID" // Identifier assigned uniquely to each image
  1301. };
  1302.  
  1303. var TiffTags = EXIF.TiffTags = {
  1304. 0x0100 : "ImageWidth",
  1305. 0x0101 : "ImageHeight",
  1306. 0x8769 : "ExifIFDPointer",
  1307. 0x8825 : "GPSInfoIFDPointer",
  1308. 0xA005 : "InteroperabilityIFDPointer",
  1309. 0x0102 : "BitsPerSample",
  1310. 0x0103 : "Compression",
  1311. 0x0106 : "PhotometricInterpretation",
  1312. 0x0112 : "Orientation",
  1313. 0x0115 : "SamplesPerPixel",
  1314. 0x011C : "PlanarConfiguration",
  1315. 0x0212 : "YCbCrSubSampling",
  1316. 0x0213 : "YCbCrPositioning",
  1317. 0x011A : "XResolution",
  1318. 0x011B : "YResolution",
  1319. 0x0128 : "ResolutionUnit",
  1320. 0x0111 : "StripOffsets",
  1321. 0x0116 : "RowsPerStrip",
  1322. 0x0117 : "StripByteCounts",
  1323. 0x0201 : "JPEGInterchangeFormat",
  1324. 0x0202 : "JPEGInterchangeFormatLength",
  1325. 0x012D : "TransferFunction",
  1326. 0x013E : "WhitePoint",
  1327. 0x013F : "PrimaryChromaticities",
  1328. 0x0211 : "YCbCrCoefficients",
  1329. 0x0214 : "ReferenceBlackWhite",
  1330. 0x0132 : "DateTime",
  1331. 0x010E : "ImageDescription",
  1332. 0x010F : "Make",
  1333. 0x0110 : "Model",
  1334. 0x0131 : "Software",
  1335. 0x013B : "Artist",
  1336. 0x8298 : "Copyright"
  1337. };
  1338.  
  1339. var GPSTags = EXIF.GPSTags = {
  1340. 0x0000 : "GPSVersionID",
  1341. 0x0001 : "GPSLatitudeRef",
  1342. 0x0002 : "GPSLatitude",
  1343. 0x0003 : "GPSLongitudeRef",
  1344. 0x0004 : "GPSLongitude",
  1345. 0x0005 : "GPSAltitudeRef",
  1346. 0x0006 : "GPSAltitude",
  1347. 0x0007 : "GPSTimeStamp",
  1348. 0x0008 : "GPSSatellites",
  1349. 0x0009 : "GPSStatus",
  1350. 0x000A : "GPSMeasureMode",
  1351. 0x000B : "GPSDOP",
  1352. 0x000C : "GPSSpeedRef",
  1353. 0x000D : "GPSSpeed",
  1354. 0x000E : "GPSTrackRef",
  1355. 0x000F : "GPSTrack",
  1356. 0x0010 : "GPSImgDirectionRef",
  1357. 0x0011 : "GPSImgDirection",
  1358. 0x0012 : "GPSMapDatum",
  1359. 0x0013 : "GPSDestLatitudeRef",
  1360. 0x0014 : "GPSDestLatitude",
  1361. 0x0015 : "GPSDestLongitudeRef",
  1362. 0x0016 : "GPSDestLongitude",
  1363. 0x0017 : "GPSDestBearingRef",
  1364. 0x0018 : "GPSDestBearing",
  1365. 0x0019 : "GPSDestDistanceRef",
  1366. 0x001A : "GPSDestDistance",
  1367. 0x001B : "GPSProcessingMethod",
  1368. 0x001C : "GPSAreaInformation",
  1369. 0x001D : "GPSDateStamp",
  1370. 0x001E : "GPSDifferential"
  1371. };
  1372.  
  1373. var StringValues = EXIF.StringValues = {
  1374. ExposureProgram : {
  1375. 0 : "Not defined",
  1376. 1 : "Manual",
  1377. 2 : "Normal program",
  1378. 3 : "Aperture priority",
  1379. 4 : "Shutter priority",
  1380. 5 : "Creative program",
  1381. 6 : "Action program",
  1382. 7 : "Portrait mode",
  1383. 8 : "Landscape mode"
  1384. },
  1385. MeteringMode : {
  1386. 0 : "Unknown",
  1387. 1 : "Average",
  1388. 2 : "CenterWeightedAverage",
  1389. 3 : "Spot",
  1390. 4 : "MultiSpot",
  1391. 5 : "Pattern",
  1392. 6 : "Partial",
  1393. 255 : "Other"
  1394. },
  1395. LightSource : {
  1396. 0 : "Unknown",
  1397. 1 : "Daylight",
  1398. 2 : "Fluorescent",
  1399. 3 : "Tungsten (incandescent light)",
  1400. 4 : "Flash",
  1401. 9 : "Fine weather",
  1402. 10 : "Cloudy weather",
  1403. 11 : "Shade",
  1404. 12 : "Daylight fluorescent (D 5700 - 7100K)",
  1405. 13 : "Day white fluorescent (N 4600 - 5400K)",
  1406. 14 : "Cool white fluorescent (W 3900 - 4500K)",
  1407. 15 : "White fluorescent (WW 3200 - 3700K)",
  1408. 17 : "Standard light A",
  1409. 18 : "Standard light B",
  1410. 19 : "Standard light C",
  1411. 20 : "D55",
  1412. 21 : "D65",
  1413. 22 : "D75",
  1414. 23 : "D50",
  1415. 24 : "ISO studio tungsten",
  1416. 255 : "Other"
  1417. },
  1418. Flash : {
  1419. 0x0000 : "Flash did not fire",
  1420. 0x0001 : "Flash fired",
  1421. 0x0005 : "Strobe return light not detected",
  1422. 0x0007 : "Strobe return light detected",
  1423. 0x0009 : "Flash fired, compulsory flash mode",
  1424. 0x000D : "Flash fired, compulsory flash mode, return light not detected",
  1425. 0x000F : "Flash fired, compulsory flash mode, return light detected",
  1426. 0x0010 : "Flash did not fire, compulsory flash mode",
  1427. 0x0018 : "Flash did not fire, auto mode",
  1428. 0x0019 : "Flash fired, auto mode",
  1429. 0x001D : "Flash fired, auto mode, return light not detected",
  1430. 0x001F : "Flash fired, auto mode, return light detected",
  1431. 0x0020 : "No flash function",
  1432. 0x0041 : "Flash fired, red-eye reduction mode",
  1433. 0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
  1434. 0x0047 : "Flash fired, red-eye reduction mode, return light detected",
  1435. 0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
  1436. 0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
  1437. 0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
  1438. 0x0059 : "Flash fired, auto mode, red-eye reduction mode",
  1439. 0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
  1440. 0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
  1441. },
  1442. SensingMethod : {
  1443. 1 : "Not defined",
  1444. 2 : "One-chip color area sensor",
  1445. 3 : "Two-chip color area sensor",
  1446. 4 : "Three-chip color area sensor",
  1447. 5 : "Color sequential area sensor",
  1448. 7 : "Trilinear sensor",
  1449. 8 : "Color sequential linear sensor"
  1450. },
  1451. SceneCaptureType : {
  1452. 0 : "Standard",
  1453. 1 : "Landscape",
  1454. 2 : "Portrait",
  1455. 3 : "Night scene"
  1456. },
  1457. SceneType : {
  1458. 1 : "Directly photographed"
  1459. },
  1460. CustomRendered : {
  1461. 0 : "Normal process",
  1462. 1 : "Custom process"
  1463. },
  1464. WhiteBalance : {
  1465. 0 : "Auto white balance",
  1466. 1 : "Manual white balance"
  1467. },
  1468. GainControl : {
  1469. 0 : "None",
  1470. 1 : "Low gain up",
  1471. 2 : "High gain up",
  1472. 3 : "Low gain down",
  1473. 4 : "High gain down"
  1474. },
  1475. Contrast : {
  1476. 0 : "Normal",
  1477. 1 : "Soft",
  1478. 2 : "Hard"
  1479. },
  1480. Saturation : {
  1481. 0 : "Normal",
  1482. 1 : "Low saturation",
  1483. 2 : "High saturation"
  1484. },
  1485. Sharpness : {
  1486. 0 : "Normal",
  1487. 1 : "Soft",
  1488. 2 : "Hard"
  1489. },
  1490. SubjectDistanceRange : {
  1491. 0 : "Unknown",
  1492. 1 : "Macro",
  1493. 2 : "Close view",
  1494. 3 : "Distant view"
  1495. },
  1496. FileSource : {
  1497. 3 : "DSC"
  1498. },
  1499.  
  1500. Components : {
  1501. 0 : "",
  1502. 1 : "Y",
  1503. 2 : "Cb",
  1504. 3 : "Cr",
  1505. 4 : "R",
  1506. 5 : "G",
  1507. 6 : "B"
  1508. }
  1509. };
  1510.  
  1511. function addEvent(element, event, handler) {
  1512. if (element.addEventListener) {
  1513. element.addEventListener(event, handler, false);
  1514. } else if (element.attachEvent) {
  1515. element.attachEvent("on" + event, handler);
  1516. }
  1517. }
  1518.  
  1519. function imageHasData(img) {
  1520. return !!(img.exifdata);
  1521. }
  1522.  
  1523.  
  1524. function base64ToArrayBuffer(base64, contentType) {
  1525. contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
  1526. base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
  1527. var binary = atob(base64);
  1528. var len = binary.length;
  1529. var buffer = new ArrayBuffer(len);
  1530. var view = new Uint8Array(buffer);
  1531. for (var i = 0; i < len; i++) {
  1532. view[i] = binary.charCodeAt(i);
  1533. }
  1534. return buffer;
  1535. }
  1536.  
  1537. function objectURLToBlob(url, callback) {
  1538. // var http = new XMLHttpRequest();
  1539. // http.open("GET", url, true);
  1540. // http.responseType = "blob";
  1541. // http.onload = function(e) {
  1542. // if (this.status == 200 || this.status === 0) {
  1543. // callback(this.response);
  1544. // }
  1545. // };
  1546. // http.send();
  1547.  
  1548. // GM.xmlHttpRequest({
  1549. // method: "GET",
  1550. // url: url,
  1551. // onload: function(e) {
  1552. // if (this.status == 200 || this.status === 0) {
  1553. // callback(this.response);
  1554. // }
  1555. // }
  1556. // });
  1557. }
  1558.  
  1559. function getImageData(img, callback) {
  1560. function handleBinaryFile(binFile) {
  1561. var data = findEXIFinJPEG(binFile);
  1562. var iptcdata = findIPTCinJPEG(binFile);
  1563. img.exifdata = data || {};
  1564. img.iptcdata = iptcdata || {};
  1565. if (callback) {
  1566. callback.call(img);
  1567. }
  1568. }
  1569.  
  1570. if (img.src) {
  1571. if (/^data\:/i.test(img.src)) { // Data URI
  1572. var arrayBuffer = base64ToArrayBuffer(img.src);
  1573. handleBinaryFile(arrayBuffer);
  1574.  
  1575. } else if (/^blob\:/i.test(img.src)) { // Object URL
  1576. var fileReader = new FileReader();
  1577. fileReader.onload = function(e) {
  1578. handleBinaryFile(e.target.result);
  1579. };
  1580. objectURLToBlob(img.src, function (blob) {
  1581. fileReader.readAsArrayBuffer(blob);
  1582. });
  1583. } else {
  1584. // var http = new XMLHttpRequest();
  1585. // http.onload = function() {
  1586. // if (this.status == 200 || this.status === 0) {
  1587. // handleBinaryFile(http.response);
  1588. // } else {
  1589. // throw "Could not load image";
  1590. // }
  1591. // http = null;
  1592. // };
  1593. // http.open("GET", img.src, true);
  1594. // http.responseType = "arraybuffer";
  1595. // http.send(null);
  1596.  
  1597. GM.xmlHttpRequest({
  1598. method: "GET",
  1599. url: img.src,
  1600. responseType: 'arraybuffer',
  1601. onload: function(response) {
  1602. if (response.status == 200 || response.status === 0) {
  1603. handleBinaryFile(response.response);
  1604. }
  1605. }
  1606. });
  1607. }
  1608. } else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
  1609. var fileReader = new FileReader();
  1610. fileReader.onload = function(e) {
  1611. if (debug) console.log("Got file of length " + e.target.result.byteLength);
  1612. handleBinaryFile(e.target.result);
  1613. };
  1614.  
  1615. fileReader.readAsArrayBuffer(img);
  1616. }
  1617. }
  1618.  
  1619. function findEXIFinJPEG(file) {
  1620. var dataView = new DataView(file);
  1621.  
  1622. if (debug) console.log("Got file of length " + file.byteLength);
  1623. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1624. if (debug) console.log("Not a valid JPEG");
  1625. return false; // not a valid jpeg
  1626. }
  1627.  
  1628. var offset = 2,
  1629. length = file.byteLength,
  1630. marker;
  1631.  
  1632. while (offset < length) {
  1633. if (dataView.getUint8(offset) != 0xFF) {
  1634. if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
  1635. return false; // not a valid marker, something is wrong
  1636. }
  1637.  
  1638. marker = dataView.getUint8(offset + 1);
  1639. if (debug) console.log(marker);
  1640.  
  1641. // we could implement handling for other markers here,
  1642. // but we're only looking for 0xFFE1 for EXIF data
  1643.  
  1644. if (marker == 225) {
  1645. if (debug) console.log("Found 0xFFE1 marker");
  1646.  
  1647. return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
  1648.  
  1649. // offset += 2 + file.getShortAt(offset+2, true);
  1650.  
  1651. } else {
  1652. offset += 2 + dataView.getUint16(offset+2);
  1653. }
  1654.  
  1655. }
  1656.  
  1657. }
  1658.  
  1659. function findIPTCinJPEG(file) {
  1660. var dataView = new DataView(file);
  1661.  
  1662. if (debug) console.log("Got file of length " + file.byteLength);
  1663. if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
  1664. if (debug) console.log("Not a valid JPEG");
  1665. return false; // not a valid jpeg
  1666. }
  1667.  
  1668. var offset = 2,
  1669. length = file.byteLength;
  1670.  
  1671.  
  1672. var isFieldSegmentStart = function(dataView, offset){
  1673. return (
  1674. dataView.getUint8(offset) === 0x38 &&
  1675. dataView.getUint8(offset+1) === 0x42 &&
  1676. dataView.getUint8(offset+2) === 0x49 &&
  1677. dataView.getUint8(offset+3) === 0x4D &&
  1678. dataView.getUint8(offset+4) === 0x04 &&
  1679. dataView.getUint8(offset+5) === 0x04
  1680. );
  1681. };
  1682.  
  1683. while (offset < length) {
  1684.  
  1685. if ( isFieldSegmentStart(dataView, offset )){
  1686.  
  1687. // Get the length of the name header (which is padded to an even number of bytes)
  1688. var nameHeaderLength = dataView.getUint8(offset+7);
  1689. if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
  1690. // Check for pre photoshop 6 format
  1691. if(nameHeaderLength === 0) {
  1692. // Always 4
  1693. nameHeaderLength = 4;
  1694. }
  1695.  
  1696. var startOffset = offset + 8 + nameHeaderLength;
  1697. var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
  1698.  
  1699. return readIPTCData(file, startOffset, sectionLength);
  1700.  
  1701. break;
  1702.  
  1703. }
  1704.  
  1705.  
  1706. // Not the marker, continue searching
  1707. offset++;
  1708.  
  1709. }
  1710.  
  1711. }
  1712. var IptcFieldMap = {
  1713. 0x78 : 'caption',
  1714. 0x6E : 'credit',
  1715. 0x19 : 'keywords',
  1716. 0x37 : 'dateCreated',
  1717. 0x50 : 'byline',
  1718. 0x55 : 'bylineTitle',
  1719. 0x7A : 'captionWriter',
  1720. 0x69 : 'headline',
  1721. 0x74 : 'copyright',
  1722. 0x0F : 'category'
  1723. };
  1724. function readIPTCData(file, startOffset, sectionLength){
  1725. var dataView = new DataView(file);
  1726. var data = {};
  1727. var fieldValue, fieldName, dataSize, segmentType, segmentSize;
  1728. var segmentStartPos = startOffset;
  1729. while(segmentStartPos < startOffset+sectionLength) {
  1730. if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
  1731. segmentType = dataView.getUint8(segmentStartPos+2);
  1732. if(segmentType in IptcFieldMap) {
  1733. dataSize = dataView.getInt16(segmentStartPos+3);
  1734. segmentSize = dataSize + 5;
  1735. fieldName = IptcFieldMap[segmentType];
  1736. fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
  1737. // Check if we already stored a value with this name
  1738. if(data.hasOwnProperty(fieldName)) {
  1739. // Value already stored with this name, create multivalue field
  1740. if(data[fieldName] instanceof Array) {
  1741. data[fieldName].push(fieldValue);
  1742. }
  1743. else {
  1744. data[fieldName] = [data[fieldName], fieldValue];
  1745. }
  1746. }
  1747. else {
  1748. data[fieldName] = fieldValue;
  1749. }
  1750. }
  1751.  
  1752. }
  1753. segmentStartPos++;
  1754. }
  1755. return data;
  1756. }
  1757.  
  1758.  
  1759.  
  1760. function readTags(file, tiffStart, dirStart, strings, bigEnd) {
  1761. var entries = file.getUint16(dirStart, !bigEnd),
  1762. tags = {},
  1763. entryOffset, tag,
  1764. i;
  1765.  
  1766. for (i=0;i<entries;i++) {
  1767. entryOffset = dirStart + i*12 + 2;
  1768. tag = strings[file.getUint16(entryOffset, !bigEnd)];
  1769. if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
  1770. tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
  1771. }
  1772. return tags;
  1773. }
  1774.  
  1775.  
  1776. function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
  1777. var type = file.getUint16(entryOffset+2, !bigEnd),
  1778. numValues = file.getUint32(entryOffset+4, !bigEnd),
  1779. valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
  1780. offset,
  1781. vals, val, n,
  1782. numerator, denominator;
  1783.  
  1784. switch (type) {
  1785. case 1: // byte, 8-bit unsigned int
  1786. case 7: // undefined, 8-bit byte, value depending on field
  1787. if (numValues == 1) {
  1788. return file.getUint8(entryOffset + 8, !bigEnd);
  1789. } else {
  1790. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1791. vals = [];
  1792. for (n=0;n<numValues;n++) {
  1793. vals[n] = file.getUint8(offset + n);
  1794. }
  1795. return vals;
  1796. }
  1797.  
  1798. case 2: // ascii, 8-bit byte
  1799. offset = numValues > 4 ? valueOffset : (entryOffset + 8);
  1800. return getStringFromDB(file, offset, numValues-1);
  1801.  
  1802. case 3: // short, 16 bit int
  1803. if (numValues == 1) {
  1804. return file.getUint16(entryOffset + 8, !bigEnd);
  1805. } else {
  1806. offset = numValues > 2 ? valueOffset : (entryOffset + 8);
  1807. vals = [];
  1808. for (n=0;n<numValues;n++) {
  1809. vals[n] = file.getUint16(offset + 2*n, !bigEnd);
  1810. }
  1811. return vals;
  1812. }
  1813.  
  1814. case 4: // long, 32 bit int
  1815. if (numValues == 1) {
  1816. return file.getUint32(entryOffset + 8, !bigEnd);
  1817. } else {
  1818. vals = [];
  1819. for (n=0;n<numValues;n++) {
  1820. vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
  1821. }
  1822. return vals;
  1823. }
  1824.  
  1825. case 5: // rational = two long values, first is numerator, second is denominator
  1826. if (numValues == 1) {
  1827. numerator = file.getUint32(valueOffset, !bigEnd);
  1828. denominator = file.getUint32(valueOffset+4, !bigEnd);
  1829. val = new Number(numerator / denominator);
  1830. val.numerator = numerator;
  1831. val.denominator = denominator;
  1832. return val;
  1833. } else {
  1834. vals = [];
  1835. for (n=0;n<numValues;n++) {
  1836. numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
  1837. denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
  1838. vals[n] = new Number(numerator / denominator);
  1839. vals[n].numerator = numerator;
  1840. vals[n].denominator = denominator;
  1841. }
  1842. return vals;
  1843. }
  1844.  
  1845. case 9: // slong, 32 bit signed int
  1846. if (numValues == 1) {
  1847. return file.getInt32(entryOffset + 8, !bigEnd);
  1848. } else {
  1849. vals = [];
  1850. for (n=0;n<numValues;n++) {
  1851. vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
  1852. }
  1853. return vals;
  1854. }
  1855.  
  1856. case 10: // signed rational, two slongs, first is numerator, second is denominator
  1857. if (numValues == 1) {
  1858. return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
  1859. } else {
  1860. vals = [];
  1861. for (n=0;n<numValues;n++) {
  1862. vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
  1863. }
  1864. return vals;
  1865. }
  1866. }
  1867. }
  1868.  
  1869. function getStringFromDB(buffer, start, length) {
  1870. var outstr = "";
  1871. for (n = start; n < start+length; n++) {
  1872. outstr += String.fromCharCode(buffer.getUint8(n));
  1873. }
  1874. return outstr;
  1875. }
  1876.  
  1877. function readEXIFData(file, start) {
  1878. if (getStringFromDB(file, start, 4) != "Exif") {
  1879. if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
  1880. return false;
  1881. }
  1882.  
  1883. var bigEnd,
  1884. tags, tag,
  1885. exifData, gpsData,
  1886. tiffOffset = start + 6;
  1887.  
  1888. // test for TIFF validity and endianness
  1889. if (file.getUint16(tiffOffset) == 0x4949) {
  1890. bigEnd = false;
  1891. } else if (file.getUint16(tiffOffset) == 0x4D4D) {
  1892. bigEnd = true;
  1893. } else {
  1894. if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
  1895. return false;
  1896. }
  1897.  
  1898. if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
  1899. if (debug) console.log("Not valid TIFF data! (no 0x002A)");
  1900. return false;
  1901. }
  1902.  
  1903. var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);
  1904.  
  1905. if (firstIFDOffset < 0x00000008) {
  1906. if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
  1907. return false;
  1908. }
  1909.  
  1910. tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
  1911.  
  1912. if (tags.ExifIFDPointer) {
  1913. exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
  1914. for (tag in exifData) {
  1915. switch (tag) {
  1916. case "LightSource" :
  1917. case "Flash" :
  1918. case "MeteringMode" :
  1919. case "ExposureProgram" :
  1920. case "SensingMethod" :
  1921. case "SceneCaptureType" :
  1922. case "SceneType" :
  1923. case "CustomRendered" :
  1924. case "WhiteBalance" :
  1925. case "GainControl" :
  1926. case "Contrast" :
  1927. case "Saturation" :
  1928. case "Sharpness" :
  1929. case "SubjectDistanceRange" :
  1930. case "FileSource" :
  1931. exifData[tag] = StringValues[tag][exifData[tag]];
  1932. break;
  1933.  
  1934. case "ExifVersion" :
  1935. case "FlashpixVersion" :
  1936. exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
  1937. break;
  1938.  
  1939. case "ComponentsConfiguration" :
  1940. exifData[tag] =
  1941. StringValues.Components[exifData[tag][0]] +
  1942. StringValues.Components[exifData[tag][1]] +
  1943. StringValues.Components[exifData[tag][2]] +
  1944. StringValues.Components[exifData[tag][3]];
  1945. break;
  1946. }
  1947. tags[tag] = exifData[tag];
  1948. }
  1949. }
  1950.  
  1951. if (tags.GPSInfoIFDPointer) {
  1952. gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
  1953. for (tag in gpsData) {
  1954. switch (tag) {
  1955. case "GPSVersionID" :
  1956. gpsData[tag] = gpsData[tag][0] +
  1957. "." + gpsData[tag][1] +
  1958. "." + gpsData[tag][2] +
  1959. "." + gpsData[tag][3];
  1960. break;
  1961. }
  1962. tags[tag] = gpsData[tag];
  1963. }
  1964. }
  1965.  
  1966. return tags;
  1967. }
  1968.  
  1969. EXIF.getData = function(img, callback) {
  1970. if ((img instanceof Image || img instanceof HTMLImageElement) && !img.complete) return false;
  1971.  
  1972. if (!imageHasData(img)) {
  1973. getImageData(img, callback);
  1974. } else {
  1975. if (callback) {
  1976. callback.call(img);
  1977. }
  1978. }
  1979. return true;
  1980. }
  1981.  
  1982. EXIF.getTag = function(img, tag) {
  1983. if (!imageHasData(img)) return;
  1984. return img.exifdata[tag];
  1985. }
  1986.  
  1987. EXIF.getAllTags = function(img) {
  1988. if (!imageHasData(img)) return {};
  1989. var a,
  1990. data = img.exifdata,
  1991. tags = {};
  1992. for (a in data) {
  1993. if (data.hasOwnProperty(a)) {
  1994. tags[a] = data[a];
  1995. }
  1996. }
  1997. return tags;
  1998. }
  1999.  
  2000. EXIF.pretty = function(img) {
  2001. if (!imageHasData(img)) return "";
  2002. var a,
  2003. data = img.exifdata,
  2004. strPretty = "";
  2005. for (a in data) {
  2006. if (data.hasOwnProperty(a)) {
  2007. if (typeof data[a] == "object") {
  2008. if (data[a] instanceof Number) {
  2009. strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
  2010. } else {
  2011. strPretty += a + " : [" + data[a].length + " values]\r\n";
  2012. }
  2013. } else {
  2014. strPretty += a + " : " + data[a] + "\r\n";
  2015. }
  2016. }
  2017. }
  2018. return strPretty;
  2019. }
  2020.  
  2021. EXIF.readFromBinaryFile = function(file) {
  2022. return findEXIFinJPEG(file);
  2023. }
  2024.  
  2025. if (typeof define === 'function' && define.amd) {
  2026. define('exif-js', [], function() {
  2027. return EXIF;
  2028. });
  2029. }
  2030. }.call(this));
  2031. // -- https://github.com/exif-js/exif-js