decembre

GM - Flickr Functional Suite - NEW (by C. Tilford)

Jan 11th, 2024 (edited)
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name          Flickr Functional Suite - NEW(08.2023) - default profile
  3. // @namespace     http://www.tilford.net/
  4. // @description   Adds some additional functionality to page
  5. // @include       http://*.flickr.com/*
  6. // @include       http://flickr.com/*
  7. // @include       https://*.flickr.com/*
  8. // @include       https://flickr.com/*
  9. // @grant       GM_getValue
  10. // @grant       GM_setValue
  11. // @grant       GM_log
  12. // @grant       GM_xmlhttpRequest
  13.  
  14. //
  15. // ==/UserScript==
  16.  
  17. /*
  18.  
  19. This is a Grease Monkey script. It *requires* FireFox and the Grease
  20. Monkey extension to work:
  21.  
  22. http://www.mozilla.com/firefox/
  23. http://greasemonkey.mozdev.org/
  24.  
  25. Following the instructions on the above web pages
  26. 1. Install FireFox
  27. 2. Install GreaseMonkey
  28. 3. Install this script
  29.  
  30. Author: Charles Tilford  http://www.flickr.com/photos/charlestilford/
  31.   (I am not hosting tilford.net yet)
  32.  
  33. This code is released under the CreativeCommons 'By' license. That is,
  34. you can do anything you want with it, just leave my name as one of the
  35. authors. http://creativecommons.org/licenses/by/2.5/
  36.  
  37. h2. Summary
  38.  
  39. Provides an interface to let you assign colors to users you meet - that way, if you find a user's link on a page in the future, it will automatically be highlighted with thes color you previously gave them.
  40.  
  41. In group pool pages, you can highlight user photos where more than one image is visible from the same user. You can also overlay all comments from a user under the corresponding photos on that page.
  42.  
  43. h2. Features:
  44.  
  45. # Configuration
  46. ** All features can be toggled on / off
  47. ** Access to configuration either through [?] links or main "Organize" menu
  48. ** Colors can be customized.
  49. # User coloration
  50. ** All '/photos/USERNAME/' links will be altered:
  51. *** Clicking on them brings up a mini-menu
  52. *** You can assign a color to any user, which will highlight the user links
  53. *** Colors will be remembered (only on your computer)
  54. *** It is now possible to assign multiple colors to a user
  55. *** Links to their photos, profile and pool images (if in pool page) shown in menu
  56. # Group pool analysis
  57. ** When viewing pool pages, all images on the page are tallied
  58. *** Users posting more than one photo will be noted
  59. *** Images from those users will get a colored background
  60. *** Background colors are unique to each user (but otherwise essentially random)
  61. *** Summary of users posting multiple images shown at top of page
  62. ** Comments for all photos on a pool page are pre-fetched
  63. *** For any poster on a pool page, all their comments can be shown for other photos on the same page
  64. ** NOTE: these functions are off by default, turn them on in the options page ('Organize' Flickr menu)
  65.  
  66. !http://static.flickr.com/69/206732191_399d74d02a.jpg!:http://www.flickr.com/photos/charlestilford/206732191/
  67.  
  68. !http://static.flickr.com/73/219349265_b6b41a139b.jpg!:http://www.flickr.com/photos/charlestilford/219349265/
  69.  
  70. !http://static.flickr.com/90/219349268_a4dd3fa439.jpg!:http://www.flickr.com/photos/charlestilford/219349268/
  71.  
  72.  
  73. Handy Color name reference:
  74. http://www.w3.org/TR/2002/WD-css3-color-20020219/#x11-color
  75.  
  76. !! Caution !!
  77.  
  78. Persistent data, such as colors assigned to users, are stored within
  79. the Grease Monkey / FireFox system itself. If you invest a lot of time in
  80. color-coding users, you run the risk of losing all your assignments if
  81. FireFox's prefs.js is over-written. If you would like to back up your
  82. assignments, you should back up that file - on Windows it will be
  83. somewhere like:
  84.  
  85. C:\Documents and Settings\YourUserName\Application Data\
  86.    Mozilla\Firefox\Profiles\8aabdex06.default\prefs.js
  87.  
  88. and have entries like:
  89.  
  90. user_pref("greasemonkey.scriptvals.http://www.tilford.net//Flickr Functional Suite.UserColorcharlestilford", "Lime");
  91.  
  92. !! About User Identifications
  93.  
  94. Flickr uses a confusing mixture of identifiers for their customers.
  95.  
  96. Flickr     Used Here Example
  97. ---------- --------- -----------------
  98. NSID:      nsid      51159953@N00
  99. username:  uname     listentoreason
  100. photourl:  purl      charlestilford
  101. displayid: dispid    Truncated Username...
  102.  
  103. The NSID is the most useful for getting information, but the least
  104. human friendly. The displayid is not technically an official
  105. identifer, but is encountered when parsing Flickr web pages. It is
  106. used when a user name is too long - the username is truncated,
  107. apparently on a whitespace character, and shown with elipses ie "...".
  108.  
  109. # History
  110. * 25 Aug 2006
  111. ** John Carney suggests a Plays-Nice-With-Others alteration that lets pop-up functionality work fine with other GM scripts
  112. ** Added additional links in user menu, tried to tighten up real estate usage
  113. * 24 Aug 2006
  114. ** Bug fix by John Carney (http://schmickr.innercurmudgeon.com/)
  115. * 19 Aug 2006
  116. ** Implemented interface to Flickr API
  117. ** Use API to fetch comments for all photos on pool page
  118. *** For any pool contributor, show all of their comments on that page
  119. * 15 Aug 2006
  120. ** Allow multiple colors to be assigned to one user
  121. * 6 Aug 2006
  122. ** User settings added
  123. *** Can toggle basic behaviors on and off
  124. *** Can now customize color list, and assign description to each color
  125. ** Altered 'All Pool Photos' to only display when the low-level ID is used as the UID
  126. * 4 August 2006
  127. ** Nice interface to set user color
  128. ** User colors persistently stored with GM_setValue()
  129. ** Multiple posting working well
  130. ** The 'All Pool Photos' usually will not work - I need to implement a method to ajax get the low-level user ID
  131.  
  132.  !! Disclaimer !!
  133.  
  134. Feel free to mine the code for ideas, but be warned that because this
  135. is a Grease Monkey script, I have made no effort at all to make the code
  136. anywhere close to cross-browser compatible - parts of the code will be
  137. specific to FireFox and will not function in other browsers.
  138.  
  139. Boy it is *nice* to develop JS for *ONLY* FireFox!
  140.  
  141. */
  142.  
  143.  
  144. var CatFlickrSuite = {
  145.     // Internal data structures
  146.     privateData: new Object(), // Safe (?) storage of metadata for DOM elements
  147.     env:         new Object(), // Global environmental values
  148.     user:        new Object(), // user-defined values
  149.     doneTask:    new Object(), // Prevent re-fetching some data
  150.     gmMsg: "",                 // Debugging message buffer
  151.     apikey: "b1c88b6a99ffabbf76ace9eab025996f",
  152.     seckey: "79c1cc27f6c7cff9",
  153.     objects: {  }, // Pre-calculated/scanned
  154.     // Sigh. Flickr is changing their object IDs. Their perogative, of course
  155.     // Centralize the IDs here to make code updates easier
  156.     fids: {
  157.         main: 'main',
  158.         navYou: 'flickr_nav_menu_you',
  159.         //        navOrg: 'flickr_nav_menu_organize',
  160.         navOrg: 'explore-panel',
  161.         csfHelp: 'CfsHelpButton',
  162.         csfCols: 'currentColors',
  163.         csfAvl:  'availableColors',
  164.         csfPop:  'CatFlickrSuitePopUp',
  165.         csfTag:  'CFS_Tag_Assoc',
  166.         grpAvl:  'TagMatchAvail'
  167.     },
  168.     // User configurable parameters. Organized by class (the kind of
  169.     // <input> used to represent them) and parameter name, with a
  170.     // description and default value for each.
  171.     userSet: {
  172.         checkbox: {
  173.             colorUser: ["Colorize user IDs",1],
  174.             colorMult: ["Colorize multiple images from same user in group pools",0],
  175.             sumMult:   ["Summarize multi-posters in group pools",0],
  176.             getCom:    ["Pre-fetch all comments associated with photos on a pool page",0],
  177.         },
  178.         text: {
  179.             comWidth:  ["Maximum characters to show for in-line comments",100],
  180.             comSize:   ["Inline comment font size", '9px'],
  181.         },
  182.         textarea: {
  183.             UserColors: ["Colors and descriptions for tagging other users",
  184.                          "Lime Category 1\nAqua Category 2\nFuchsia Category 3\nSilver Category 4\nYellow Category 5\nRed Category 6\nBlack Category 7\nNone"],
  185.         },
  186.     },
  187.     translate: { },
  188.     // The 'minimum RGB spacing' - prevents grays when using string2color and color4string:
  189.     colBuf: 64,
  190.     /* colMin and colMax added for @decembre. Allows the RGB index
  191.        range in pools to be changed from 0-255 to user prefs.
  192.        colMin - increase to prevent 'dark' index values
  193.        colMax - decrease to prevent 'light' index values
  194.        ALWAYS have colMin < colMax, and both between 0 and 255 */
  195.     colMin: 0,
  196.     colMax: 255,
  197.     counter: 0,
  198.     ticket: 0,
  199.     ticketStatus: new Object(),
  200.     // Special links that we want to ignore:
  201.     specialLinks: ['1', '< Prev', 'You', 'Organize', 'Upload', 'upload',
  202.                    'Popular Tags','Organize & Create', "All your content",
  203.                    'Upload Photos and Videos', "Your Photostream",
  204.                    'Your Photos', 'Upload Photos', 'All your photos', ],
  205.     re: {
  206.         // Regular Expression Collection
  207.         frob:       /\?frob=(\S+)$/,             // Authentication frob
  208.         photoID:    /\/photos\/([^\/]+)\/(\d+)/, // PURL and Photo ID
  209.         userPhotos: /\/photos\/([^\/]+)\/$/,     // Link to user photots
  210.         myComs:     /\/photos_comments\.gne/,    // Comments you made
  211.         urlPool1:   /\/([^\/]+)\/pool\//,        // Group pool href
  212.         urlPool2:   /\/in\/pool-([^\/]+)\//,     // Image in pool stream
  213.         urlGroup:   /\/groups\/([^\/]+)\//,      // General group URL
  214.         urlAllGrp:  /\/groups\/?$/,               // Group list page
  215.         statRef:    /\/stats\/([^\/]+)\//,       // Statistics page
  216.         urlSet:     /\/photos\/([^\/]+)\/sets\/(\d+)\/?$/, // Photoset
  217.         elipsed:    /\.\.\.$/,                   // Trailing 3 periods (elipses)
  218.         nsid:       /^\d+\@.{3}$/, // Not sure what the real format is?
  219.         organize:   /\/photos\/organize\//,      // Organize DHTML interface
  220.     },
  221.     init: function() {
  222.         // The primary initialization function
  223.         // GM_log("Starting: " + new Date());
  224.         var now = new Date();
  225.         this.ms = now.getTime().toString();
  226.         this.setEnvironment();
  227.         if (this.env.pageType == 'Organize') return; // Do nothing on Organize
  228.         this.initTransmute();
  229.         this.setSettings();
  230.         this.insertSettings();
  231.         this.refresh();
  232.         this.annotateGroupList();
  233.         this.tagAssociation();
  234.         this.cleanComments();
  235.         this.colorStats();
  236.         this.finalize();
  237.         GM_log("Initialized Flickr Functional Suite");
  238.         window.addEventListener('click', function (e) {
  239.                 // alert('new data!');
  240.                 CatFlickrSuite.checkClickEvent(e);
  241.             }, false);
  242.  
  243.         //window.addEventListener('AutoPagerNewData', function (e) {
  244.         //        document.CatFlickrSuite.refresh();
  245.         //    }, false);
  246.     },
  247.     refresh: function() {
  248.         this.grabFrob();
  249.         this.armLinks();
  250.         this.findMultiPost();
  251.         this.colorUserPhotos();
  252.         this.getAllComments();
  253.     },
  254.     whoami: function() {
  255.         if (this.you == null) {
  256.             var data = this.parseFlickrData();
  257.             this.you = "";
  258.             if (data.flickr && data.flickr.user && data.flickr.user.pathalias) {
  259.                 this.you = data.flickr.user.pathalias;
  260.             } else {
  261.                 GM_log("Could not find path alias");
  262.             }
  263.         }
  264.         return this.you;
  265.     },
  266.     myNSID: function() {
  267.         if (this.nsid == null) {
  268.             var data = this.parseFlickrData();
  269.             this.nsid = 0;
  270.             if (data.flickr && data.flickr.user && data.flickr.user.nsid) {
  271.                 this.nsid = data.flickr.user.nsid;
  272.             } else {
  273.                 GM_log("Could not find NSID");
  274.             }
  275.         }
  276.         return this.nsid;
  277.     },
  278.     parseFlickrData: function () {
  279.         if (!this.yconf) {
  280.             var nodes = document.getElementsByTagName('script');
  281.             for (var n=0; n<nodes.length; n++) {
  282.                 var html = nodes[n].innerHTML;
  283.                 if (!html) continue;
  284.                 var hits = html.match(/\s*var\s+yconf\s+=\s*(\{.+?\})\;\s*/);
  285.                 if (hits) {
  286.                     this.yconf= JSON.parse( hits[1]);
  287.                     break;
  288.                 }
  289.             }
  290.             if (!this.yconf) {
  291.                 this.yconf = new Object();
  292.                 GM_log("Failed to find Flickr yconf hash object");
  293.             }
  294.         }
  295.         return this.yconf;
  296.     },
  297.     groupID: function() {
  298.         if (this.groupid == null) {
  299.             this.groupid = 0;
  300.             var nodes = document.getElementsByTagName('link');
  301.             for (var n=0; n<nodes.length; n++) {
  302.                 if (!nodes[n] || !nodes[n].href) continue;
  303.                 var hits = nodes[n].href.match(/groups_[a-z]+\.gne\?.*id=([^\&]+)/);
  304.                 if (hits) { this.groupid = hits[1]; break; }
  305.             }
  306.             if (!this.groupid) {
  307.                 // Try links
  308.                 nodes = document.getElementsByTagName('a');
  309.                 for (var n=0; n<nodes.length; n++) {
  310.                     if (!nodes[n] || !nodes[n].href) continue;
  311.                     var hits = nodes[n].href.match(/groups_[a-z]+\.gne\?.*id=([^\&]+)/);
  312.                     if (hits) { this.groupid = hits[1]; break; }
  313.                 }
  314.             }
  315.         }
  316.         return this.groupid;
  317.     },
  318.     setEnvironment: function() {
  319.         // Gather some global information
  320.         var href = this.env.href = document.location.href;
  321.         var mat;
  322.         this.env.pageType = this.env.pageView = '';
  323.         // Are we on the organize page?
  324.         mat  = href.match(this.re.organize);
  325.         if (mat) { this.env.pageType = 'Organize';
  326.         this.env.pageView = 'Organize'; return; }
  327.         // Are we on a 'Comments you've made' page?
  328.         mat  = href.match(this.re.myComs);
  329.         if (mat) { this.env.pageType = 'Comment';
  330.         this.env.pageView = 'YourComments'; return; }
  331.         // Are we on a Group's pool page?
  332.         // See if we are in a group pool-related page:
  333.         mat  = href.match(this.re.urlPool1);
  334.         if (mat) { this.env.group = mat[1];
  335.         this.env.pageType = 'Group'; this.env.pageView = 'Pool'; return; }
  336.  
  337.         // Group list page
  338.         mat  = href.match(this.re.urlAllGrp);
  339.         if (mat) { this.env.group = mat[1];
  340.             this.env.pageType = 'Group'; this.env.pageView = 'YourGroups'; return; }
  341.  
  342.         // Generic URL for groups:
  343.         mat  = href.match(this.re.urlGroup);
  344.         if (mat) { this.env.group = mat[1];
  345.         this.env.pageType = 'Group'; return; }
  346.         // A photoset page:
  347.         mat  = href.match(this.re.urlSet);
  348.         if (mat) { this.env.setOwn = mat[1]; this.env.set = mat[2];
  349.         this.env.pageType = this.env.pageView = 'Set'; return; }
  350.         // Statistics Page
  351.         mat  = href.match(this.re.statRef);
  352.         if (mat) {
  353.             this.env.statType = mat[1];
  354.             this.env.pageType = this.env.pageView = 'Stats'; return;
  355.         }
  356.  
  357.     },
  358.     initTransmute: function() {
  359.         // Turn one object type into another This just allows
  360.         // representation of some data structures in a format that is
  361.         // easy for humans to modify, but not the ultimate structure
  362.         // needed by the code.
  363.         this.specLinkHash = new Object();
  364.         for (var i=0; i<this.specialLinks.length;i++) {
  365.             this.specLinkHash[this.specialLinks[i].toLowerCase()] = 1;
  366.         }
  367.         // Flatten settings hash into 2D array
  368.         var uarr = new Array();
  369.         for (var type in this.userSet) {
  370.             // Cycle through each data type
  371.             var info = this.userSet[type];
  372.             for (var tag in info) {
  373.                 // Cycle through each parameter
  374.                 var subarray = [ type, tag ];
  375.                 // Add description, defaultValue:
  376.                 subarray = subarray.concat( info[tag] );
  377.                 uarr.push(subarray);
  378.             }
  379.         }
  380.         this.msg();
  381.         this.userSetArr = uarr;
  382.     },
  383.     setSettings: function() {
  384.         // Scan all configurable tagnames and retrieve value from
  385.         // GreaseMonkey internal store, or set to default value.
  386.         var uarr = this.userSetArr;
  387.         for (var u=0; u < uarr.length; u++) {
  388.             var tag        = uarr[u][1];
  389.             var def        = uarr[u][3];
  390.             this.user[tag] = GM_getValue(tag, def);
  391.         }
  392.         // Special processing of user colors
  393.         var colArr = this.user.UserColors.split(/[\r\n]+/);
  394.         this.user.colList = new Array();
  395.         this.user.colDesc = new Object();
  396.         for (var c=0;c<colArr.length;c++) {
  397.             var cbits = colArr[c].split(/\s+/);
  398.             var cname = cbits.shift();
  399.             if (!cname || cname == '') continue;
  400.             var cdesc = cbits.join(' ');
  401.             this.user.colList.push(cname);
  402.             this.user.colDesc[ cname.toLowerCase() ] = cdesc;
  403.         }
  404.     },
  405.     msg: function() {
  406.         // Record some debugging information. These messages will
  407.         // appear in the FireFox javascript Console, under 'Messages'
  408.         if (this.gmMsg != "") GM_log("Execution messages:\n"+this.gmMsg);
  409.         this.gmMsg = "";
  410.     },
  411.     err: function (msg, e) {
  412.         // Throw an error, also to the JS concole
  413.         if (e) {
  414.             if (e.description) msg += "\n  DESC: " + e.description;
  415.             msg += "\n  ERR: " + e;
  416.         }
  417.         GM_log(msg);
  418.     },
  419.     finalize: function() {
  420.         // Final code to execute after all parsing is done.
  421.         this.msg();
  422.     },
  423.     armLinks: function() {
  424.         // Search for <a> tags on the page that we want to modify
  425.         var links = this.liveUserPhotoList();
  426.         for (var i=0; i < links.length; i++) {
  427.             this.registerUserPhoto( links[i] );
  428.         }
  429.     },
  430.     colors4user: function(purl, asArray) {
  431.         // Get your color(s) for a particular PURL
  432.         // asArray = return array, otherwise return hash
  433.         var rv = asArray ? new Array() : new Object();
  434.         var cstr = GM_getValue("UserColor"+purl);
  435.         if (!cstr) return rv;
  436.         // Split string on spaces
  437.         var clist = cstr.split(/\s+/);
  438.         for (c=0; c < clist.length; c++) {
  439.             var cname = clist[c].toLowerCase();
  440.             if (!cname || cname == 'none') continue; // compatibility with old versions
  441.             if (asArray) {
  442.                 rv.push(cname);
  443.             } else {
  444.                 rv[cname] = clist[c];
  445.             }
  446.         }
  447.         return rv;
  448.     },
  449.     userPhotoClick: function(el, evt) {
  450.         if (evt) {
  451.             evt.preventDefault();
  452.             evt.stopPropagation();
  453.             GM_log(evt);
  454.             evt.returnValue = false;
  455.         }
  456.         // Establish the new pop-up menu that will be used for "/photos/UserName/" links:
  457.         // GM_log(el.id + ' from ' + this.ms);
  458.         var dispid    = this.registerUserPhoto(el);
  459.         var uname     = this.getTranslation(dispid, 'uname');
  460.         var purl      = this.getTranslation(dispid, 'purl');
  461.         var nsid      = this.getTranslation(dispid, 'nsid');
  462.         var colHash   = this.colors4user( purl );
  463.         // GM_log("User click on "+el.id+" ("+el+") = "+dispid);
  464.         // Close box and name:
  465.         var html = "<span class='CancelButt'>[x]</span>&nbsp;<b>"+
  466.         (uname ? uname : dispid)+
  467.         "</b>&nbsp;<span style='color:green;cursor:help' id='"+
  468.         this.fids.csfHelp+"'>[?]</span>\n<div id='currentColors'>";
  469.         for (var ucol in colHash) {
  470.             html += this.userColorBlock( colHash[ucol], 'SetColor' );
  471.         }
  472.         html += "</div>\n";
  473.  
  474.         // Each 'item' is a line in the popup - see makeMenu()
  475.         var items = new Array();
  476.         var links = new Array();
  477.         // This is what the link used to point to:
  478.         links.push( ['Photos', "/photos/"+purl+"/" ] );
  479.         // Add in the user's profile, favorites, sets and tags:
  480.         links.push( [ 'Profile', "/people/"+purl+"/" ] );
  481.         links.push( [ 'Favorites', "/photos/"+purl+"/favorites/"] );
  482. // OK TEST 06.2018 - ARCHIVES   - "/archives/date-taken/detail/?view=sm"
  483. links.push( [ 'Archive', "/photos/"+purl+"/archives/date-taken/detail/?view=sm/"] );
  484.         links.push( [ 'Sets', "/photos/"+purl+"/sets/"] );
  485.         links.push( [ 'Tags', "/photos/"+purl+"/tags/"] );
  486.         if (nsid) {
  487.             links.push( ['Mail', "/messages_write.gne?to="+nsid]);
  488.         }
  489.         if (this.env.pageView == 'Pool') {
  490.             // We are on a pool-related page
  491.             if (nsid) links.push ( ['All Pool Photos', '/groups/'+this.env.group+'/pool/'+nsid]);            if (uname && this.objects.comments) {
  492.                 // Pre-computed comments are available
  493.                 if (this.objects.comments[uname]) {
  494.                     // We found at least one comment for this user
  495.                     var coms = this.objects.comments[uname];
  496.                     var cn   = coms.length;
  497.                     var cmag = {href: "javascript:void(0)", 'class': 'ShowComments', text: ctxt};
  498.                     var ctxt = (this.objects.shownComments[uname] ? 'Hide ' : 'Show ') + cn;
  499.                     ctxt    += " comment"+(cn == 1 ? '' : 's')+ " on this page";
  500.                     cmag.text = ctxt;
  501.                     items.push(cmag);
  502.                 } else {
  503.                     // No comments for this user
  504.                     items.push("<i>No comments found</i>");
  505.                 }
  506.                 // Are the AJAX requests succesfully completed?
  507.                 var stat = this.apiStatus('getComments');
  508.                 if (stat != "") {
  509.                     // Warn the user that some data was not available.
  510.                     items.push({ tag:'i', style:'color:orange; font-size:xxsmall', text:"&rArr;Data missing: "+stat})
  511.                 }
  512.             }
  513.         }
  514.          if (uname) {
  515.             // John Watson's Scout page - list of the user's interesting photos
  516.             links.push
  517.                 ( [ 'Scout (CSF)', "http://flagrantdisregard.com/flickr/scout.php?username="+uname] );
  518.             // Nathan Siemer's HiveMind
  519.             links.push
  520.             ( [ 'HiveMind (CFS)', "http://flickrhivemind.net/User/"+uname] );
  521.  
  522. // DECEMBRE TWEAK - TEST OK - 2018 - ADD VIEWERS in POPUP (contacts page)
  523.  
  524. // TEST OK - 2018 - HiveMind Interesting -  (use +uname+)
  525. // http://flickrhivemind.net/flickr_hvmnd.cgi?search_type=User&textinput=10946586@N02&search_type=Search+User&photo_number=500&photo_type=100&sort=Interestingness&page=1&tag_mode=
  526.  links.push
  527.             ( [ 'HiveMind Interesting TEST  uname', "http://flickrhivemind.net/flickr_hvmnd.cgi?search_type=User&textinput="+uname+"&search_type=Search+User&photo_number=500&photo_type=100&sort=Interestingness&page=1&tag_mode="] );
  528.  
  529. // TEST OK - 2018 - HiveMind UserFAV -  (use +purl+)
  530. // http://flickrhivemind.net/flickr_hvmnd.cgi?search_type=Favorites&textinput=...%20Tina
  531.  links.push
  532.             ( [ 'HiveMind UserFAV - TEST uname', "http://flickrhivemind.net/flickr_hvmnd.cgi?search_type=Favorites&textinput="+uname] );
  533.  
  534. // OK TEST OK - 2018 - FLUIDR -  (use +uname+)
  535. // http://www.fluidr.com/photos/tinatink/favorites
  536. // http://www.fluidr.com/photos/tinatink
  537.             links.push
  538.             ( [ 'FLUIDR', "http://www.fluidr.com/photos/"+uname] );
  539.  
  540. // TEST OK - 2018 - Archives (use +purl+)
  541. // PM =   iconlink += '<a title="User Photo Archive (Small)" href="https://www.flickr.com/photos/' + userid + '/archives/date-taken/detail/?view=sm">' + iconarch + '</a> ';
  542. // https://www.flickr.com/photos/10946586@N02/archives/date-taken/detail/?view=sm
  543.             links.push
  544.             ( [ 'Archives', "https://www.flickr.com/photos/"+purl+"/archives/date-taken/detail/?view=sm"] );
  545. // END TEST ADD LINKS IN POPUP (contacts pages)
  546.  
  547.         }
  548.         if (links.length > 0) {
  549.             // The number of links to stuff into one line:
  550.             var linksPerLine = 3;
  551.             for (var l=0;l<links.length; l++) {
  552.                 html += "| <a class='simple_butt' href='"+links[l][1]+"'>"+links[l][0]+"</a> ";
  553.                 if (!((l+1) % linksPerLine)) html += "|</br>";
  554.             }
  555.             if (links.length % linksPerLine) html += "|</br>";
  556.         }
  557.         // Make a menu of colors to list:
  558.         items.push({ tag:'b', text: 'Available Flags:' });
  559.  
  560.         html += this.makeMenu( items ) +"\n<div style='font-size:smaller' id='"
  561.         + this.fids.csfAvl + "'>";
  562.         for (var c=0; c < this.user.colList.length; c++) {
  563.             var col   = this.user.colList[c];
  564.             if (colHash[col.toLowerCase()]) continue;
  565.             var linkHtml = this.userColorBlock( col, 'SetColor' );
  566.             if (linkHtml != "") html += linkHtml;
  567.         }
  568.         html += "</div>\n";
  569.  
  570.         // Pop up the window
  571.         var div = this.popUp(el, html, evt);
  572.         // Also associate the PURL with the popup, we'll need it for processing clicks later
  573.         var hb = document.getElementById(this.fids.csfHelp);
  574.         if (hb) hb.addEventListener('click', function (e) {
  575.             return CatFlickrSuite.settingsClick(this, e);}, false);
  576.         this.privateHash(div, 'purl', purl);
  577.         this.privateHash(div, 'dispid', dispid);
  578.         this.privateHash(div, 'onclose', function() {
  579.                 CatFlickrSuite.updateUser( el );
  580.             } );
  581.         GM_log("DEBUG="+el.href);
  582.         return false;
  583.     },
  584.     userColorBlock: function(col, cname) {
  585.         // Returns a single div for a category color
  586.         if (/^none$/i.test(col)) return ""; // compatibility with old versions
  587.         // Get the description for this color:
  588.         var text  = this.user.colDesc[col.toLowerCase()];
  589.         // Use the color name itself if no description available:
  590.         if (!text) text = col;
  591.         return this.makeMenu( [ {
  592.             tag: 'div', 'class':cname, text: "<em>"+text+"</em>", colName: col, style: "background-color:"+col
  593.         } ] );
  594.     },
  595.     escapeXML: function (txt) {
  596.         if (txt == null) return '';
  597.         txt = txt.replace(/&gt;/g,'>');
  598.         txt = txt.replace(/&lt;/g,'<');
  599.         txt = txt.replace(/&amp;/g,'&');
  600.         return txt;
  601.     },
  602.     unescapeXML: function (txt) {
  603.         if (txt == null) return '';
  604.         txt = txt.replace(/\>/g,'&gt;');
  605.         txt = txt.replace(/\</g,'&lt;');
  606.         txt = txt.replace(/\&/g,'&amp;');
  607.         return txt;
  608.     },
  609.     liveUserPhotoList: function () {
  610.         /* Designed to always return a list of user photos, even
  611.            if the page has been modified by another script */
  612.         var arr = new Array();
  613.         var links = document.getElementsByTagName("a");
  614.         for (var l=0; l < links.length; l++) {
  615.             var el = links[l];
  616.             if (this.isUserPhoto(el)) arr.push(el);
  617.         }
  618.         return arr;
  619.     },
  620.     isUserPhoto: function (el) {
  621.         if (!el) return false;
  622.         var dispid  = el.text;
  623.         // Skip special links:
  624.         if (dispid == null || dispid == '' || this.specLinkHash[dispid.toLowerCase()] ||
  625.             /photostream$/.test(dispid)) return false;
  626.         var hit  = el.href.match( this.re.userPhotos );
  627.         if (!hit) return false;
  628.         return hit[1];
  629.     },
  630.     colorUserPhotos: function (purlReq) {
  631.         if (this.user.colorUser != 1) return;
  632.         // This routine colors <a> tags pointing to
  633.         // "/photos/UserName/", so long as you have assigned a color
  634.         // to that particular user. If purlReq is null, then all links
  635.         // are processed, otherwise only the requested purl will be
  636.         // altered.
  637.         var arr = this.liveUserPhotoList();
  638.         this.gmMsg += "Coloring User photos for '"+purlReq+"' out of " +arr.length+" total images\n";
  639.         for (var i=0; i < arr.length; i++) {
  640.             var el     = arr[i];
  641.             // if (this.privateHash(el, 'cupDone')) continue;
  642.             this.privateHash(el, 'cupDone', true);
  643.             var purl   = this.privateHash(el, 'purl');
  644.             // Skip if there is a specific request and this is not it
  645.             if (purlReq && purl != purlReq) continue;
  646.             // this.gmMsg += "Coloring "+purl+"\n";
  647.             var colArr  = this.colors4user( purl, true );
  648.             var colNum  = colArr.length;
  649.             var text    = this.privateHash(el, 'innerText');
  650.             var htmlNow = el.innerHTML;
  651.             if (colNum < 1) {
  652.                // Decolorize the link if it was previously colored:
  653.                 if (text) el.innerHTML = htmlNow.replace(/\<span[^\>]+span\>/,'');
  654.                 continue;
  655.             }
  656.             if (!text) {
  657.                 text = this.unescapeXML(el.text);
  658.                 this.privateHash(el, 'innerText', text);
  659.             }
  660.             // The routine below will color the user's name into one or more colored blocks:
  661.             var tlen   = text.length;
  662.             var step   = tlen / colNum;
  663.             var html   = "";
  664.             for (var c=0; c < colNum; c++) {
  665.                 var start = Math.floor(0.5 + c * step);
  666.                 var end   = (c == colNum - 1) ? tlen : Math.floor(0.5 + (c+1) * step);
  667.                 if (start == end) continue;
  668.                 html += "<span style='background-color:"+colArr[c]+"'>"+
  669.                     this.escapeXML(text.substring(start, end)) + "</span>";
  670.             }
  671.             if (/\<span/.test(el.innerHTML)) {
  672.                 el.innerHTML = htmlNow.replace(/\<span.+span\>/, html);
  673.             } else {
  674.                 el.innerHTML = htmlNow.replace(text, html);
  675.             }
  676.         }
  677.         this.msg();
  678.     },
  679.     tagAssociation: function () {
  680.         var main  = document.getElementById(this.fids.main);
  681.         if (!main) return;
  682.         var type = this.env.pageType;
  683.         if (type == 'Set') {
  684.             // Only associate with sets you own
  685.             var you   = this.whoami();
  686.             var owner = this.env.setOwn;
  687.             if (!owner || !you || owner != you) return;
  688.         } else if (type != 'Group') {
  689.             return;
  690.         }
  691.         var div = document.getElementById(this.fids.csfTag);
  692.         if (!div) {
  693.             // Make the div if we have not already done so
  694.             div = document.createElement('div');
  695.             div.id = this.fids.csfTag;
  696.             main.insertBefore(div, main.firstChild);
  697.             div.style.border = 'solid navy 1px';
  698.         }
  699.         var tags = new Array();
  700.         var hash = this.getTagAssociations(  );
  701.         for (var tag in hash) {
  702.             if (tag && tag != '') tags.push( tag );
  703.         }
  704.         var html = "";
  705.         var form = document.createElement('form');
  706.         form.innerHTML = "<i>Associate tag rule with this "+type+":</i> "+
  707.         "<input name='tagassoc' width='20' value='' />";
  708.         div.innerHTML = html;
  709.         div.appendChild(form);
  710.         form.addEventListener('submit', function (e) {
  711.             e.preventDefault();
  712.             return CatFlickrSuite.addTagAssociation(this);}, false);
  713.         if (tags.length != 0) {
  714.             var tform = document.createElement('form');
  715.             var thtml = "<input type='submit' id='cfs_ta_search' value='Find new members with tag:'>";
  716.             tags = tags.sort();
  717.             for (var t=0; t < tags.length; t++) {
  718.                 var tag = tags[t];
  719.                 thtml += "<span style='border: grey solid 1px; margin: 3px; padding: 3px;'><input type='checkbox' name='cfs_ta' value='"+tag+
  720.                     "' checked='checked'/>"+hash[tags[t]] +" <span class='CancelButt'>[x]</span></span> ";
  721.             }
  722.             var lim = GM_getValue("TagAssocLimit", '');
  723.             thtml += "<br /><span style='color: #006'>";
  724.             thtml += "Report at most <input id='cfs_ta_limit' size='3' value='"+lim+
  725.                 "' /> matches";
  726.             thtml += ", uploaded between <input id='cfs_ta_minage' size='3' />";
  727.            thtml += " to <input id='cfs_ta_maxage' size='3' /> days ago";
  728.             thtml += "</span>\n";
  729.             tform.innerHTML = thtml;
  730.             div.appendChild(tform);
  731.             // Monitor tag interactions:
  732.             tform.addEventListener('click', function (e) {
  733.                 return CatFlickrSuite.tagAssocClickHandler(e);}, false);
  734.         }
  735.         this.taDiv = div;
  736.     },
  737.     intFromField: function( fieldId, desc, errors) {
  738.         var obj = document.getElementById( fieldId);
  739.         if (!obj) return null;
  740.         if (/^\d+$/.test(obj.value)) return obj.value;
  741.         if (desc && errors) errors.push(desc);
  742.         return null;
  743.     },
  744.     UTC: new Date(1970,0,1),
  745.     flickrDateFormat: function( offset ) {
  746.         if (!offset) offset = 0;
  747.         var dt = new Date();
  748.         dt.setDate(dt.getDate() - offset);
  749.         return (dt.getTime() - this.UTC.getTime()) / 1000 ;
  750.         return dt.toUTCString();
  751.  
  752.         var string = dt.getFullYear();
  753.         var bits   = [ dt.getMonth() + 1, dt.getDate(),
  754.                        dt.getHours(), dt.getMinutes(), dt.getSeconds() ];
  755.         for (var b=0; b < bits.length; b++) {
  756.             var val = bits[b];
  757.             if (val < 10) val = '0' + val;
  758.             string += val;
  759.         }
  760.         return string;
  761.     },
  762.     gmObjId: function () {
  763.         var type = this.env.pageType.toLowerCase();
  764.         if (!type || type == '' || !this.env[type] ) return '';
  765.         return type + '_' + this.env[type];
  766.     },
  767.     getTagAssociations: function() {
  768.         var hash = new Object();
  769.         var gid  = this.gmObjId();
  770.         if (gid == '') return hash;
  771.         var txt = GM_getValue("TagAssoc_"+gid, '');
  772.         var words = txt.split(',');
  773.         for (var w=0; w < words.length; w++) {
  774.             var raw = words[w];
  775.             hash[ this.cleanTag(raw) ] = raw;
  776.         }
  777.         return hash;
  778.     },
  779.     setTagAssociations: function(hash) {
  780.         var gid  = this.gmObjId();
  781.         if (!hash || gid == '') return 0;
  782.         var arr = new Array();
  783.         for (var tag in hash) {
  784.             if (tag && tag != '') arr.push(hash[tag]);
  785.         }
  786.         arr = arr.sort();
  787.         GM_setValue("TagAssoc_"+gid, arr.join(','));
  788.         return arr.length;
  789.     },
  790.     addTagAssociation: function (el) {
  791.         var val = this.valuesForNamedInput(el, 'tagassoc');
  792.         if (!val || val.length != 1 || ! val[0]) return;
  793.         var raw  = val[0];
  794.         var tag  = this.cleanTag(raw);
  795.         var hash = this.getTagAssociations();
  796.         hash[ tag ] = raw;
  797.         this.setTagAssociations(hash);
  798.         // Redraw the interface
  799.         this.tagAssociation();
  800.     },
  801.     tagAssocClickHandler: function(e) {
  802.         // Respond to a click event in a tag list
  803.         if (!e || !e.originalTarget) return;
  804.         var targ  = e.originalTarget;
  805.         var cn, id;
  806.         try {
  807.             // For some reason this throws a Permission Denied sometimes
  808.             cn = targ.className;
  809.             id = targ.id;
  810.         } catch (e) {
  811.             this.err("Failed to find node information for "+targ, e);
  812.         }
  813.         if (cn == 'CancelButt') {
  814.             var el    = targ.parentNode.firstChild;
  815.             if (!el || !el.value) return;
  816.             var raw  = el.value;
  817.             var hash = this.getTagAssociations();
  818.             delete hash[ this.cleanTag(raw) ];
  819.             this.setTagAssociations(hash);
  820.             this.tagAssociation(); // Redraw the interface
  821.         } else if ( id == 'cfs_ta_search' ) {
  822.             e.preventDefault();
  823.             this.searchTagAssociations();
  824.         }
  825.     },
  826.     cleanTag: function (raw) {
  827.         // "Hot Dog" !cat rat !"My Mouse"
  828.         // leading exclamation point
  829.         if (raw == null) return '';
  830.         var tag = raw.toLowerCase();
  831.         tag = tag.replace(/\s+/g, ' ');   // Space runs trimmed to single spaces
  832.         tag = tag.replace(/\! /g, '!');   // Remove trailing space after !
  833.         var tagList = new Array();
  834.         // Identify and extract contents of quoted strings
  835.         var quotes  = [ "'", '"' ];
  836.         for (var q = 0; q < quotes.length; q++) {
  837.             var qt = quotes[q];
  838.             // Make sure ! is inside quotes:
  839.             var swRE   = new RegExp('!' + qt, 'g');
  840.             tag        = tag.replace(swRE, qt + '!');
  841.             var nestRe = new RegExp(qt+ '([^' + qt + ']+)' + qt);
  842.             while (1) {
  843.                 var quoted = tag.match( nestRe );
  844.                 if (!quoted || quoted.length < 2) break;
  845.                 var inner = quoted[1];
  846.                 // Check for leading !
  847.                 var isNot = /^\!/.test(inner) ? '!' : '';
  848.                 inner     = inner.replace(/[^a-z0-9]/g, '');
  849.                 tagList.push( isNot + inner );
  850.                 tag = tag.replace(quoted[0],'');
  851.             }
  852.         }
  853.         tag = tag.replace(/^\s+/, '');   // Remove leading space
  854.         tag = tag.replace(/\s+$/, '');   // Remove trailing space
  855.         var words = tag.split(/\s+/);
  856.         for (var w = 0; w < words.length; w++) {
  857.             var word  = words[w];
  858.             var isNot = /^\!/.test(word) ? '!' : '';
  859.             word     = word.replace(/[^a-z0-9]/g, '');
  860.             tagList.push( isNot + word );
  861.         }
  862.         // GM_log("Raw: "+raw+" | Parsed: "+tagList.join(' '));
  863.         return tagList.join(' ');
  864.     },
  865.     searchTagAssociations: function () {
  866.         var cbs  = document.getElementsByName('cfs_ta');
  867.         if (!cbs || cbs.length < 1) return;
  868.         var type = this.env.pageType;
  869.         var ta   = this.tagAssocResults = { shown: {}, shownum: 0 };
  870.         var nsid = this.myNSID();
  871.         if (!nsid) {
  872.             alert("Failed to determine your Flickr NSID for searching");
  873.             return;
  874.         }
  875.         var commonFlickrArgs = {
  876.             method: 'flickr.photos.search', user_id: nsid, per_page: 500, extras: 'icon_server'
  877.         };
  878.  
  879.         var atErr = new Array();
  880.         var minA  = this.intFromField('cfs_ta_minage', "minimum age", atErr);
  881.         var maxA  = this.intFromField('cfs_ta_maxage', "maximum age", atErr);
  882.         if (minA && maxA && minA > maxA) {
  883.             var tmp = minA;
  884.             minA    = maxA;
  885.             maxA    = tmp;
  886.         }
  887.         if (minA) {
  888.             commonFlickrArgs.min_upload_date = this.flickrDateFormat( minA );
  889.         }
  890.         if (maxA) {
  891.             commonFlickrArgs.max_upload_date = this.flickrDateFormat( maxA );
  892.         }
  893.         // GM_log("Date range: "+commonFlickrArgs.min_upload_date + ' to ' + commonFlickrArgs.max_upload_date);
  894.  
  895.         if (type == 'Set') {
  896.         } else if (type == 'Group') {
  897.             commonFlickrArgs.privacy_filter = 1; // Assume we want only public photos for groups
  898.         } else {
  899.             alert("I do not know how to find photos for a '"+type+"' page");
  900.             return;
  901.         }
  902.         ta.what = type;
  903.  
  904.         // Determine which tag criteria the user wants to use to find photos
  905.         var tagCriteria = new Object();
  906.         for (var c=0; c < cbs.length; c++) {
  907.             // Scan through all the user's tag criteria defined for this set / pool
  908.             var cb = cbs[c];
  909.             if (!cb.checked) continue; // Not selected for this search
  910.             // Each criteria should have one or more tags in it
  911.             var tagSet  = cb.value.split(' ');
  912.  
  913.             var crit    = { tags: [], not: [] };
  914.             var goodTag = 0;
  915.             for (var ts = 0; ts < tagSet.length; ts++) {
  916.                 var tag = tagSet[ts];
  917.                 if (!tag) continue;
  918.                 if (/\!/.test(tag)) {
  919.                     // This is a 'not' tag
  920.                     crit.not.push( tag.replace(/\!/g, '') );
  921.                 } else {
  922.                     crit.tags.push( tag );
  923.                 }
  924.                 goodTag++;
  925.             }
  926.             if (goodTag == 0) continue;
  927.             // Use the not requests to aggregate each criteria
  928.             crit.not.sort();
  929.             var nkey = crit.not.join(' ') || '';
  930.             if (!tagCriteria[ nkey ]) {
  931.                 tagCriteria[ nkey ] = {
  932.                     'not': crit.not,
  933.                     'and': new Array(),
  934.                     'or':  new Array(),
  935.                 };
  936.             }
  937.             var posTags = crit.tags;
  938.             if (posTags.length == 1) {
  939.                 // Single positive tag request, put it in an OR stack
  940.                 tagCriteria[ nkey ].or.push( posTags[0] );
  941.             } else if (posTags.length > 1) {
  942.                 tagCriteria[ nkey ].and.push( posTags.join(',') );
  943.             }
  944.         }
  945.  
  946.         var searchArgs = new Array();
  947.         for (var nkey in tagCriteria) {
  948.             var crit      = tagCriteria[ nkey ];
  949.             var orLen     = crit.or.length;
  950.             var andLen    = crit.and.length;
  951.             var notLen    = crit.not.length;
  952.             if (orLen + andLen + notLen == 0) continue; // We need at least one criteria...
  953.             var notHash;
  954.             if (notLen) {
  955.                 // There is a least one tag we should exclude
  956.                 notHash = new Object();
  957.                 for (var n = 0; n < notLen; n++) {
  958.                     notHash[ crit.not[n] ] = 1;
  959.                 }
  960.             }
  961.  
  962.             var flickArgs = new Object();
  963.             for (var cfa in commonFlickrArgs) {
  964.                 // Make a copy of the common arguments hash:
  965.                 flickArgs[ cfa ] = commonFlickrArgs[cfa];
  966.             }
  967.  
  968.             var notQuery  = "";
  969.             if (notLen) {
  970.                 // We will need to know the tags for each photo in order to exclude them
  971.                 flickArgs.extras = flickArgs.extras + ',tags';
  972.                 if (orLen || andLen) {
  973.                     // The NOT query is going to be combined with other positive criteria
  974.                     notQuery = " <span style='font-weight:bold; color:red'>but NOT</span> " +
  975.                         "<u>" + crit.not.join('</u> <b>OR</b> <u>') + "</u>";
  976.                 } else {
  977.                     // This is simply an exclusionary criteria
  978.                     searchArgs.push( [ flickArgs, {
  979.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  980.                                       query: "<span style='font-weight:bold; color:red'>NOT</span> " +
  981.                                       "<u>" + crit.not.join('</u> <b>OR</b> <u>') + "</u>"} ] );
  982.                 }
  983.             }
  984.             if (orLen) {
  985.                 // Request to do an OR tag search
  986.                 // We need to locally copy the hash again
  987.                 var flickArgsCopy = new Object();
  988.                 for (var fa in flickArgs) {
  989.                     flickArgsCopy[fa] = flickArgs[ fa ];
  990.                 }
  991.                 flickArgsCopy.tags     = crit.or.join(',');
  992.                 flickArgsCopy.tag_mode = 'any';
  993.                 searchArgs.push( [ flickArgsCopy, {
  994.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  995.                                       query:  "<u>" + crit.or.join('</u> <b>OR</b> <u>') +"</u>"+ notQuery }] );
  996.             }
  997.             if (andLen) {
  998.                 // Request to do one or more AND tag searches
  999.                 for (var ca = 0; ca < andLen; ca ++) {
  1000.                     // We need to locally copy the hash again
  1001.                     var flickArgsCopy = new Object();
  1002.                     for (var fa in flickArgs) {
  1003.                         flickArgsCopy[fa] = flickArgs[ fa ];
  1004.                     }
  1005.                     flickArgsCopy.tags     = crit.and[ca];
  1006.                     flickArgsCopy.tag_mode = 'all';
  1007.                     searchArgs.push( [ flickArgsCopy, {
  1008.                         ticktype: 'tagAssoc', search: 'tags', not: notHash,
  1009.                                       query: "<u>" + crit.and[ca].split(',').join('</u> <b>AND</b> <u>') +"</u>"+ notQuery } ] );
  1010.                 }
  1011.             }
  1012.         }
  1013.         var numSearch = searchArgs.length;
  1014.         if (numSearch == 0) {
  1015.             alert("You need to select at least one tag to perform a search");
  1016.             return;
  1017.         }
  1018.  
  1019.         // At least one valid set of criteria
  1020.         // Add the search to find pre-existing photos
  1021.         if (type == 'Set') {
  1022.             var sid = this.env.set;
  1023.             if (!sid) { alert("Unable to determine the Set identifier"); return; }
  1024.             searchArgs.push( [
  1025.                 { method: 'flickr.photosets.getPhotos', photoset_id: sid },
  1026.                 { ticktype: 'tagAssoc', search: 'photoset' } ] );
  1027.         } else if (type == 'Group') {
  1028.             var gid = this.groupID();
  1029.             if (!gid) { alert("Failed to find Flickr Group ID"); return }
  1030.             searchArgs.push( [
  1031.                 { method: 'flickr.groups.pools.getPhotos', per_page: 500, user_id: nsid, group_id: gid },
  1032.                 { ticktype: 'tagAssoc', search: 'photos' } ] );
  1033.         }
  1034.  
  1035.         // Set up a DIV for output:
  1036.         var resID = 'cfs_tag_search_results';
  1037.         var targ  = document.getElementById( resID );
  1038.         if (targ) {
  1039.             targ.innerHTML = "";
  1040.         } else {
  1041.             targ = document.createElement('div');
  1042.             targ.id = resID;
  1043.             this.taDiv.appendChild(targ);
  1044.         }
  1045.         ta.resultsDiv = targ;
  1046.  
  1047.         // Parse the limit value
  1048.         ta.limit  = 0;
  1049.         ta.limit  = this.intFromField('cfs_ta_limit', "search limit", atErr);
  1050.         if (ta.limit) GM_setValue("TagAssocLimit", ta.limit);
  1051.  
  1052.  
  1053.         // launch all Flickr API searches:
  1054.         for (var sa = 0; sa < searchArgs.length; sa++) {
  1055.             var div = document.createElement('div');
  1056.             var qry = searchArgs[sa][1].query;
  1057.             if (qry) {
  1058.                 qry = "with tags " + qry;
  1059.             } else {
  1060.                 qry = "already present in the " + type;
  1061.             }
  1062.             div.innerHTML = "<i>Searching for your photos "+qry+"</i>";
  1063.             targ.appendChild(div);
  1064.             searchArgs[sa][1].div = div;
  1065.             this.flickrApi( searchArgs[sa][0], 'tagAssocCB', searchArgs[sa][1] );
  1066.         }
  1067.         // The callback (tagAssocCB, below) will perform the subtraction of [Present - Needed]
  1068.     },
  1069.     tagAssocCB: function(rsp, args, cfsArgs) {
  1070.         // This function captures and combines two Ajax calls
  1071.         var st   = cfsArgs.search;
  1072.         var ta   = this.tagAssocResults;
  1073.         if (ta.complete) return;
  1074.         var targ = ta.resultsDiv;
  1075.         var qDiv = cfsArgs.div;
  1076.         var type = ta.what;
  1077.         if (st == 'tags') {
  1078.             // This query is reporting photos matching the user's tag criteria
  1079.             var notHash = cfsArgs.not;
  1080.             var keeping = new Array();
  1081.  
  1082.             for each (photos in rsp.photos) {
  1083.                 for each (photo in photos.photo) {
  1084.                     if (notHash) {
  1085.                         // We need to verify that the photo does not have an excluded tag
  1086.                         var notCount = 0;
  1087.                         var tags = photo['@tags'].split(' ');
  1088.                         for (var t = 0; t < tags.length; t++) {
  1089.                             if (notHash[ tags[t] ]) { notCount++; break; }
  1090.                         }
  1091.                         // If any of the excluded tags match, then do not use the photo
  1092.                         if (notCount) continue;
  1093.                     }
  1094.                     var pid = photo['@id'];
  1095.                     keeping.push( { id: pid, title: photo['@title'], src: 'http://static.flickr.com/'+
  1096.                                             photo['@server']+'/'+pid+'_'+photo['@secret']+'_s.jpg'} );
  1097.                 }
  1098.             }
  1099.             if (!ta.results) ta.results = new Array();
  1100.             var rdat = { photos: keeping, args: cfsArgs };
  1101.             ta.results.push( rdat );
  1102.             var numMatched = keeping.length;
  1103.             var nstyle     = 'color: blue;';
  1104.             if (numMatched == 0) {
  1105.                 rdat.done = 1;
  1106.                 nstyle = 'color: red;';
  1107.             }
  1108.             qDiv.innerHTML = "<b style='"+nstyle+"'>" + numMatched + "</b> photo"+
  1109.                 (numMatched == 1 ? ' matches ' : 's match ') + cfsArgs.query;
  1110.         } else {
  1111.             // This query is reporting photos already in the set / pool
  1112.             var numExisting = 0;
  1113.             ta.exists = new Object();
  1114.             for each (refs in rsp[st]) {
  1115.                 for each (photo in refs.photo) {
  1116.                     ta.exists[ photo['@id'] ] = 1;
  1117.                     numExisting++;
  1118.                 }
  1119.             }
  1120.             var msg = "<a target='_blank' href='http://www.flickr.com/groups/"+this.groupID()+"/pool/"+this.myNSID()+"/'><b>" + numExisting + "</b> photo" +
  1121.             (numExisting == 1 ? '' : 's') + "</a> found already in " + type;
  1122.             if (numExisting == 500) {
  1123.                 msg += ". <i style='font-size:0.7em; color:brown'>This is the maximum number of matches that Flickr will return. Some of the images suggested below (as being absent from the "+type+") may in fact already be present.</i>";
  1124.             }
  1125.             qDiv.innerHTML = msg;
  1126.         }
  1127.         // We need information from both the tag query and the pre-existing members to continue:
  1128.         if (!ta.exists || !ta.results) return;
  1129.  
  1130.         var toShow = new Array();
  1131.         var available = 0;
  1132.         for (var r = 0; r < ta.results.length; r++) {
  1133.             var rdat = ta.results[r];
  1134.             if (rdat.done) continue; // do not process result set if already processed
  1135.             var kept = rdat.photos;
  1136.             // Find results that are not already in pool / set
  1137.             var ok = 0;
  1138.             for (var k = 0; k < kept.length; k++) {
  1139.                 if (!ta.exists[ kept[k].id ]) {
  1140.                     // This photo is not in the pool
  1141.                     toShow.push( kept[k] );
  1142.                     ok++;
  1143.                 }
  1144.             }
  1145.             var msg = rdat.args.div.innerHTML;
  1146.             if (ok == 0) {
  1147.                 msg += ", all of which are already in the " + type;
  1148.             } else {
  1149.                 msg += ", <span style='font-weight:bold; color:green'>"+ok+ "</span> of which " +
  1150.                     (ok == 1 ? 'is' : 'are')+ " not yet in the " +type;
  1151.                 if (ok > available) available = ok;
  1152.             }
  1153.             rdat.args.div.innerHTML = msg;
  1154.             rdat.done = 1;
  1155.         }
  1156.         GM_setValue(this.groupID() + this.fids.grpAvl, available);
  1157.         if (toShow.length == 0) return;
  1158.  
  1159.         var you  = this.whoami();
  1160.         var form = ta.form;
  1161.         if (!form) {
  1162.             var clr  = document.createElement('button'); clr.innerHTML = "Clear All";
  1163.             var chk  = document.createElement('button'); chk.innerHTML = "Check All";
  1164.             var form = ta.form = document.createElement('form');
  1165.             form.innerHTML = "<input style='font-weight:bold; background-color: #6f6' type='submit' value='Submit to "+type+"' /> | ";
  1166.             form.appendChild(clr);
  1167.             form.appendChild(chk);
  1168.             targ.appendChild(form);
  1169.             // Arm the various buttons
  1170.             form.addEventListener('submit', function (e) {
  1171.                     // GM_log("E: " +e);
  1172.                 e.preventDefault();
  1173.                 return CatFlickrSuite.tagAssocSubmit(form);}, false);
  1174.             clr.addEventListener('click', function (e) {
  1175.                 e.preventDefault();
  1176.                 return CatFlickrSuite.setCheckboxes('orgIds', false);}, false);
  1177.             chk.addEventListener('click', function (e) {
  1178.                 e.preventDefault();
  1179.                 return CatFlickrSuite.setCheckboxes('orgIds', true);}, false);
  1180.         }
  1181.         var lim   = ta.limit;
  1182.         var defc  = (type == 'Set') ? " checked='checked'" : '';
  1183.         var togF  = this.toggleChildVisibility;
  1184.  
  1185.         for (var ts = 0; ts < toShow.length; ts++) {
  1186.             if (lim && ta.shownum >= lim) {
  1187.                 // Limit reached
  1188.                 ta.complete = 1;
  1189.                 var comp = document.createElement('div');
  1190.                 comp.innerHTML = "Requested limit of "+lim+" reached.";
  1191.                 comp.style.fontSize  = '0.7em';
  1192.                 comp.style.fontStyle = 'italic';
  1193.                 comp.style.color     = 'brown';
  1194.                 targ.appendChild(comp);
  1195.                 break;
  1196.             }
  1197.             var photo = toShow[ts];
  1198.             var pid   = photo.id;
  1199.             if (ta.shown[ pid ]) continue;
  1200.             var div   = document.createElement('div');
  1201.             div.className = 'photodiv';
  1202.             div.innerHTML = "<input type='checkbox' name='orgIds' value='"+pid+"' "+defc+"><a target='_blank' style='color: blue ! important' href='http://www.flickr.com/photos/"+you+"/"+pid+"/'>"+ photo.title+"</a><div style='display:none; position:relative;'><img src='"+photo.src+"' style='position:absolute; top: 5px; left:2em;' /></div>";
  1203.             div.addEventListener('mouseout',  togF, false);
  1204.             div.addEventListener('mouseover', togF, false);
  1205.             form.appendChild( div );
  1206.             ta.shown[ pid ] = 1;
  1207.             ta.shownum++;
  1208.         }
  1209.       // http://www.flickr.com/photos/organize/?ids=189644777,189670488
  1210.     },
  1211.     toggleChildVisibility: function( e ) {
  1212.         var obj  = e.target;
  1213.         while (obj && obj.className != 'photodiv') {
  1214.            obj = obj.parentNode;
  1215.         }
  1216.         if (!obj) return;
  1217.         var kids = obj.childNodes;
  1218.         if (!kids) return;
  1219.         if (e.type == 'mouseout') {
  1220.             kids[2].style.display = 'none';
  1221.             kids[1].style.backgroundColor = null;
  1222.        } else {
  1223.             kids[2].style.display = 'block';
  1224.             kids[1].style.backgroundColor = '#ff9';
  1225.          }
  1226.     },
  1227.     setCheckboxes: function(name, bool) {
  1228.         var ids = document.getElementsByName(name);
  1229.         if (!ids) return;
  1230.         for (var i=0; i<ids.length; i++) { ids[i].checked = bool }
  1231.     },
  1232.     tagAssocSubmit: function (frm) {
  1233.         var ids = document.getElementsByName('orgIds');
  1234.         if (!ids) return;
  1235.         var apiArgs = {  };
  1236.         var type    = this.env.pageType;
  1237.         if (type == 'Group') {
  1238.             apiArgs.method   = 'flickr.groups.pools.add';
  1239.             apiArgs.group_id = this.groupID();
  1240.         } else if (type == 'Set' && this.env.set) {
  1241.             apiArgs.method   = 'flickr.photosets.addPhoto';
  1242.             apiArgs.photoset_id = this.env.set;
  1243.         }
  1244.         if (!apiArgs.method) { alert("Failed to find ID for "+type); return; }
  1245.         var tot = 0;
  1246.         // We are going to be stripping elements out - this mucks up the ids[] array, so we will first map the checkboxes into a static array
  1247.         var elements = new Array();
  1248.         for (var i=0; i < ids.length; i++) {
  1249.             elements.push(ids[i]);
  1250.         }
  1251.         // Now we can cycle over elements:
  1252.         for (var i=0; i < elements.length; i++) {
  1253.             var el = elements[i];
  1254.             if (!el || !el.checked) continue;
  1255.             var par  = el.parentNode;
  1256.             var span = document.createElement('span');
  1257.             par.insertBefore(span,el);
  1258.             span.style.color = 'orange';
  1259.             span.style.fontSize = 'smaller';
  1260.             span.innerHTML = "Loading...";
  1261.             apiArgs.photo_id = el.value;
  1262.             par.removeChild( el );
  1263.             this.getAuthToken();
  1264.             this.flickrApi( apiArgs, 'tasubCB', {ticktype: 'groupLoad', el: span, failok: 1} );
  1265.             tot++;
  1266.         }
  1267.         if (tot < 1) { alert("Please select at least one photo"); return }
  1268.     },
  1269.     tasubCB: function (rsp, args, cfsArgs) {
  1270.         // This function just reports on the success or failure of an
  1271.         // attempt to add photos to a group or set
  1272.         var el  = cfsArgs.el;
  1273.         if (!el) return;
  1274.         var txt = rsp.toString();
  1275.         if (!txt || /^\s*$/.test(txt)) {
  1276.             // A response of nothing means success:
  1277.             el.style.color = 'green';
  1278.             el.innerHTML = 'Success! ';
  1279.         } else {
  1280.             el.style.color = 'red';
  1281.             var err = cfsArgs.error;
  1282.             if (!err) { err = "|Unknown Error|"; GM_log(txt) }
  1283.             el.innerHTML = err + ' ';
  1284.        }
  1285.     },
  1286.     cleanComments: function () {
  1287.         // Only relevant for "Comments You've Made":
  1288.         if (this.env.pageView != 'YourComments' ) return;
  1289.         var tabs = document.getElementsByTagName('table');
  1290.         var re  = new RegExp("Here's the latest \\d+\\)", "g");
  1291.         for (var t=0; t < tabs.length; t++) {
  1292.             var tab = tabs[t];
  1293.             if (tab.className != 'NewComments') continue;
  1294.             var par = tab.parentNode;
  1295.             var partabs = par.getElementsByTagName('table');
  1296.             var prior = partabs[0];
  1297.             var html = prior.innerHTML;
  1298.             var hit  = html.match(re);
  1299.             if (!hit || hit.length < 1) continue;
  1300.             tab.style.display = 'none';
  1301.  
  1302.             var span = document.createElement('span');
  1303.             span.style.color = 'blue';
  1304.             span.style.backgroundColor = 'yellow';
  1305.             span.innerHTML = "click to view comments";
  1306.             par.insertBefore(span, tab);
  1307.             tab.style.display = 'none';
  1308.             span.addEventListener('click', function (e) {
  1309.                 this.innerHTML = 'clicked';
  1310.                 var targ = this.nextSibling.style;
  1311.                 if (targ.display == 'none') {
  1312.                     this.innerHTML = 'click to hide comments';
  1313.                     targ.display   = 'block';
  1314.                 } else {
  1315.                     this.innerHTML = 'click to view comments';
  1316.                     targ.display   = 'none';
  1317.                 }
  1318.             }, false);
  1319.         }
  1320.     },
  1321.     annotateGroupList: function () {
  1322.         // alert(this.env.pageView);
  1323.         if (this.env.pageView != 'YourGroups' ) return;
  1324.         this.groupsWithTagMatches();
  1325.     },
  1326.     sortGroups: function() {
  1327.         var avail = this.groupsWithTagMatches();
  1328.         if (!avail.length) return;
  1329.         if (1) {
  1330.             sorted = avail.sort( function (a,b) { return b[1] - a[1]; } );
  1331.         } else {
  1332.             sorted = avail.sort( function (a,b) { return a[1] - b[1]; } );
  1333.         }
  1334.  
  1335.         for (var l = 0; l < sorted.length; l++) {
  1336.             var li = sorted[l][0];
  1337.             var ul = li.parentNode;
  1338.             if (!ul) continue;
  1339.             // GM_log("#"+l+" = "+li+" Group: "+li.cfsGroup+" Num: "+sorted[l][1]);
  1340.             ul.removeChild(li);
  1341.             ul.appendChild(li);
  1342.         }
  1343.     },
  1344.     groupsWithTagMatches: function () {
  1345.         if (this.groupsAvailable) return this.groupsAvailable;
  1346.         var lis    = document.getElementsByTagName('li');
  1347.         var idTest = /group_(\S+)/;
  1348.         var tot    = 0;
  1349.         var par;
  1350.         var found = new Array();
  1351.         for (var l = 0; l < lis.length; l++) {
  1352.             var li = lis[l];
  1353.             var id = li.id;
  1354.             if (!id) continue;
  1355.             var hits = id.match(idTest);
  1356.             if (!hits) continue;
  1357.             var available = GM_getValue(hits[1] + this.fids.grpAvl);
  1358.             if (available == null) {
  1359.                 available = -1;
  1360.             } else {
  1361.                 var ht = document.createElement('i');
  1362.                 ht.style.color = available == 0 ? 'gray' : 'orange';
  1363.                 ht.innerHTML = ' '+ available;
  1364.                 li.appendChild(ht);
  1365.                 tot += available;
  1366.                 par = li;
  1367.             }
  1368.             found.push([li, available]);
  1369.             li.cfsGroup = found.length;
  1370.         }
  1371.         if (par) {
  1372.             var msg = "<i style='color:orange'>"+tot+
  1373.             "</i> = photos matching your tag criteria available ";
  1374.             var mli = document.createElement('li');
  1375.             mli.innerHTML = msg;
  1376.             var srt = document.createElement('button'); srt.innerHTML = "Sort";
  1377.             mli.appendChild(srt);
  1378.             par  = par.parentNode;
  1379.             par.insertBefore(mli, par.firstChild);
  1380.             srt.addEventListener('click', function (e) {
  1381.                     e.preventDefault();
  1382.                     return CatFlickrSuite.sortGroups();}, false);
  1383.         }
  1384.         return this.groupsAvailable = found;
  1385.     },
  1386.     colorStats: function () {
  1387.         if (this.env.pageView != 'Stats' ) return;
  1388.         var nodes = document.getElementsByTagName('a');
  1389.         var isSearch = new RegExp('Searched for:');
  1390.         var isGroup  = new RegExp('\/groups\/');
  1391.         var isSet    = new RegExp('\/sets\/');
  1392.     var isTag    = new RegExp('\/([^\/]+)\/tags\/[^\/]+')
  1393.         for (var n=0; n<nodes.length; n++) {
  1394.         var node = nodes[n];
  1395.             if (!node || !node.href) continue;
  1396.         var styles = 0;
  1397.             var iH = node.innerHTML;
  1398.              if (isSearch.test(iH)) {
  1399.          styles = { color: 'green', fontWeight: 'bold', border:'solid green 1px' };
  1400.          } else if (isTag.test(iH)) {
  1401.          mat  = iH.match(isTag);
  1402.          styles = { fontWeight : 'bold', color: mat[1] == 'photos' ? 'purple' : 'blue' };
  1403.          } else if (isGroup.test(iH)) {
  1404.          styles = { fontWeight : 'bold', color: 'orange' };
  1405.          } else if (isSet.test(iH)) {
  1406.          styles = { fontWeight : 'bold', color: '#f0f' };
  1407.          }
  1408.         if (!styles) continue;
  1409.         for (var s in styles) {
  1410.             node.style[ s ] = styles[s];
  1411.         }
  1412.         }
  1413.     },
  1414.     findMultiPost: function () {
  1415.         // Only relevant for group photo pools:
  1416.         if (this.env.pageView != 'Pool' ) return;
  1417.         // Find users that have posted more than one photo on the current page
  1418.         var struct = new Object();
  1419.         // Scan all 'user photo links' - as found by registerUserPhoto()
  1420.         var arr  = this.liveUserPhotoList();
  1421.         var pool = this.objects.poolImages = new Object();
  1422.         for (var i=0; i < arr.length; i++) {
  1423.             var el  = arr[i];
  1424.             var par = el.parentNode;
  1425.             // Only take note of links inside a PoolList classed object
  1426.             if (par.className != 'PoolList') continue;
  1427.             var pid = this.imageIdFromNode(par);
  1428.             if (pid) pool[pid] = par;
  1429.             var purl   = this.privateHash(el, 'purl');
  1430.             if (!struct[purl]) {
  1431.                 // Initiate data stucture for this user
  1432.                 struct[purl] = {
  1433.                     pars: new Array(),
  1434.                     name: this.privateHash(el, 'dispid'),
  1435.                 };
  1436.             }
  1437.             struct[purl].pars.push( par );
  1438.         }
  1439.         var pcount = 0; // Total thumbnails on the page
  1440.         var ucount = 0; // Total unique users on the page
  1441.         var multi = new Array();
  1442.         // Now look at each unique user
  1443.         for (var purl in struct) {
  1444.             ucount++;
  1445.             var pars  = struct[purl].pars;
  1446.             var count = pars.length;
  1447.             pcount   += count;
  1448.             if (count > 1) {
  1449.                 // This user has more than one photo on the page
  1450.                 // Get the user's automatically generated color...
  1451.                 var col  = "rgb("+this.color4string( purl )+")";
  1452.                 // ... and set the background of each thumbnail to that color
  1453.                 if (this.user.colorMult == 1) {
  1454.                     for (var p=0; p < pars.length; p++) {
  1455.                         pars[p].style.backgroundColor = col;
  1456.                     }
  1457.                 }
  1458.                 var name = struct[purl].name;
  1459.                 // Now make a summary token to put at the top of the
  1460.                 // page - we will have a link that will be activated
  1461.                 // as a pop up:
  1462.                 var link = document.createElement('a');
  1463.                 link.href = "/photos/" + purl +"/";
  1464.                 link.innerHTML = name;
  1465.                 this.registerUserPhoto(link);
  1466.                 // ... which will be held in a span that will have the
  1467.                 // user's auto-color:
  1468.                 var span = document.createElement('span');
  1469.                 span.innerHTML = "<b>"+count+":</b>&nbsp;";
  1470.                 span.appendChild(link);
  1471.                 span.style.backgroundColor = col;
  1472.                 // Store in array for later sorting:
  1473.                 multi.push( [count, span ] );
  1474.             }
  1475.         }
  1476.         // If all images are singletons, return with no action:
  1477.         if (multi.length < 1) return;
  1478.         // Also exit if the user does not want a summary
  1479.         if (this.user.sumMult != 1) return;
  1480.         // Sort the users high-to-low:
  1481.         multi = multi.sort( function (a,b) { return b[0] - a[0]; } );
  1482.         // Slap in the little spans under the Main div:
  1483.         var target  = document.getElementById(this.fids.main);
  1484.         for (var m=0; m < multi.length; m++) {
  1485.             target.parentNode.insertBefore(multi[m][1],target);
  1486.         }
  1487.         // Generate a summary of how many users are unique:
  1488.         var divId = 'CatFlickrSuiteMultiDiv';
  1489.         var div = document.getElementById(divId);
  1490.         if (!div) {
  1491.             div = document.createElement('div');
  1492.             div.id = divId;
  1493.         }
  1494.         var uperc = Math.floor(100 * ucount / pcount);
  1495.         div.innerHTML = "<b>"+ucount + "</b> users = <b>"+uperc+"%</b> of maximum";
  1496.         target.parentNode.insertBefore(div,target);
  1497.     },
  1498.     getAllComments: function () {
  1499.         // Only relevant for group photo pools:
  1500.         if (this.env.pageView != 'Pool' ) return;
  1501.         // Do nothing if the user has requested so:
  1502.         if (this.user.getCom != 1) return;
  1503.         var pool = this.objects.poolImages;
  1504.         this.objects.comments = new Object();
  1505.         this.objects.shownComments = new Object();
  1506.         for (var pid in pool) {
  1507.             var ticket = this.requestImageComments( pid );
  1508.         }
  1509.     },
  1510.     imageIdFromNode: function(el) {
  1511.         var focus = el;
  1512.         while (!focus.href || !/\/photos\/[^\/]+\/\d+/.test(focus.href)) {
  1513.             if (focus.hasChildNodes()) {
  1514.                 focus = focus.firstChild;
  1515.             } else if (focus.nextSibling) {
  1516.                 focus = focus.nextSibling;
  1517.             } else {
  1518.                 // Failed to find image link
  1519.                 focus = null; break;
  1520.             }
  1521.         }
  1522.         var id;
  1523.         if (focus && focus.href) {
  1524.             var hits = focus.href.match( this.re.photoID );
  1525.             if (hits) id = hits[2];
  1526.         }
  1527.         return id;
  1528.     },
  1529.     requestImageComments: function( id ) {
  1530.         if (!id) return;
  1531.         // If we have already recovered comments for this id, do not do so again:
  1532.         if (!this.doneTask.getComments) this.doneTask.getComments = new Object();
  1533.         if (this.doneTask.getComments[ id ]++) return true;
  1534.         var tkey = 'getComments';
  1535.         // Set up ticket status queue if needed
  1536.         if (!this.ticketStatus[tkey]) this.ticketStatus[tkey] = new Object();
  1537.         return this.flickrApi
  1538.         ( { method: 'flickr.photos.comments.getList', photo_id: id },
  1539.           'ricCB', {ticktype: tkey} );
  1540.     },
  1541.     ricCB: function(rsp) {
  1542.         var hash = this.objects.comments;
  1543.         for each (comments in rsp.comments) {
  1544.             // for (var cs = 0; cs < rsp.comments.length; cs++) {
  1545.             // var comments = rsp.comments[cs];
  1546.             var pid  = comments['@photo_id'];
  1547.             for each (com in comments.comment) {
  1548.                 var uname  = com['@authorname'];
  1549.                 var nsid   = com['@author'];
  1550.                 this.setTranslation( { uname: uname, nsid: nsid } );
  1551.                 // var create = new Date( com.@datecreate );
  1552.                 var ctxt  = com + '';
  1553.                 // Strip out HTML tags:
  1554.                 ctxt = ctxt.replace(/(\<|\&lt\;).+?(\>|\&gt\;)/g,'');
  1555.                 // Collapse all whitespace runs to single spaces:
  1556.                 ctxt = ctxt.replace(/[\s\n\r\t]+/g, ' ');
  1557.                 if (/^\s*$/.test(ctxt)) ctxt = "HTML only" ;
  1558.                 // Store data under both authorname and photo ID (hash
  1559.                 // will collide only if someone is using a pure
  1560.                 // integer as a name AND a photo has same integer).
  1561.                 var info = { txt: ctxt, uname: uname, photo: pid };
  1562.                 if (!hash[uname]) hash[uname] = new Array();
  1563.                 if (!hash[pid])   hash[pid]   = new Array();
  1564.                 hash[uname].push(info);
  1565.                 hash[pid].push(info);
  1566.             }
  1567.         }
  1568.         this.msg();
  1569.     },
  1570.     checkClickEvent: function(evt) {
  1571.         if (!evt) {
  1572.             GM_log("Click event fails to pass the event object!");
  1573.             return false;
  1574.         }
  1575.         if (evt.which != 1) return false; // Only consider for left button
  1576.         var el = evt.target;
  1577.         while (1) {
  1578.             if (el.getAttribute && el.getAttribute('userPhoto')) {
  1579.                 // This is a link to a user photo stream
  1580.                 return this.userPhotoClick(el, evt);
  1581.             }
  1582.             if (!el.parentNode) break;
  1583.             el = el.parentNode;
  1584.         }
  1585.         // GM_log("Click on "+el+" deemed not a user photo link");
  1586.         return false;
  1587.     },
  1588.     registerUserPhoto: function(el) {
  1589.         // Take a link with target '/photos/USERID/' and add pop-up
  1590.         // functionality to it. This method also stores the link in an
  1591.         // internal structure
  1592.         var purl = this.isUserPhoto(el);
  1593.         if (!purl) return 0;
  1594.         var dispid  = el.text;
  1595.         if (this.privateHash(el, 'parsed')) return dispid;
  1596.         // Ok, this looks like the sort of link we want to modify
  1597.         // (and have not already done so)
  1598.         this.privateHash(el, 'purl', purl);
  1599.         this.privateHash(el, 'dispid', dispid);
  1600.         this.privateHash(el, 'parsed', true);
  1601.         this.setTranslation( { dispid: dispid, purl: purl } );
  1602.         el.setAttribute('userPhoto', dispid);
  1603.         return dispid;
  1604.     },
  1605.     insertSettings: function() {
  1606.         // Add a settings menu
  1607.         var targ = document.getElementById(this.fids.navOrg);
  1608.         if (!targ) {
  1609.             GM_log("Failed to find 'Organize' menu item for settings");
  1610.             return;
  1611.         }
  1612.         var liL  = document.createElement('li');
  1613.         var setL = document.createElement('a');
  1614.         setL.href = "javascript:void(0)";
  1615.         setL.innerHTML = "Flickr Suite Settings";
  1616.         setL.addEventListener('click', function (e) {
  1617.             return CatFlickrSuite.settingsClick(this, e);}, false);
  1618.         liL.appendChild(setL);
  1619.         targ.appendChild(liL);
  1620.     },
  1621.     settingsClick: function (el, evt) {
  1622.         var items = new Array();
  1623.  
  1624.        items.push("<span class='CancelButt'>[x]</span>&nbsp;"+
  1625.                    "<span style='font-weight:bold;color:blue'>"+
  1626.                    "Flickr Suite GreaseMonkey Settings</span>");
  1627.         for (var type in this.userSet) {
  1628.             // Cycle through each data type
  1629.             var info = this.userSet[type];
  1630.             if (type == 'checkbox') items.push( "<b>Active Suite Functions:</b>" );
  1631.             for (var tag in info) {
  1632.                 var val  = this.user[tag];
  1633.                 var desc = info[tag][0];
  1634.                 var inpt = { tag: 'input', type: type, id: 'CFS'+tag };
  1635.                 if (type == 'checkbox') {
  1636.                     inpt.text = desc;
  1637.                     if (val == 1) inpt.checked = 'checked';
  1638.                 } else if (type == 'text') {
  1639.                     inpt.text  = desc;
  1640.                     inpt.value = val;
  1641.                     inpt.size  = 5;
  1642.                 } else if (type == 'textarea') {
  1643.                     delete inpt.type;
  1644.                     inpt.tag  = type;
  1645.                     inpt.cols = 30;
  1646.                     inpt.rows = 10;
  1647.                     inpt.pre  = "<b>"+desc+":</b><br />";
  1648.                     inpt.text = val;
  1649.                 }
  1650.                 items.push(inpt);
  1651.             }
  1652.         }
  1653.         items.push( "<i>Close menu, then <b>reload page</b> to see changes</i>" );
  1654.         items.push({ pre: "Check ", post: " for updates to this suite", text: 'userscripts.org', target:'userscripts', href: 'http://userscripts.org/scripts/show/5016', });
  1655.         var html;
  1656.         try {
  1657.             // Some weirdness during development, so be safe in a try/catch
  1658.             html = this.makeMenu( items );
  1659.         } catch(e) {
  1660.             this.err("Failed to make settings menu for ", e);
  1661.             return false;
  1662.         }
  1663.         // Pop up the window
  1664.         var div = this.popUp(el, html, evt);
  1665.         this.privateHash(div, 'onclose', function() {
  1666.                 CatFlickrSuite.updateSettings();
  1667.             } );
  1668.         return false;
  1669.     },
  1670.     updateSettings: function (el) {
  1671.         // Note that we have succesfully gotten to the callback
  1672.         this.privateHash(el, 'onclose', false );
  1673.         // Scan all user configurable settings, put values in GreaseMonkey persistant store
  1674.         var uarr = this.userSetArr;
  1675.         for (var u=0; u < uarr.length; u++) {
  1676.             var type = uarr[u][0];
  1677.             var tag  = uarr[u][1];
  1678.             var inpt = document.getElementById('CFS' + tag);
  1679.             if (!inpt) continue;
  1680.             var val;
  1681.             if (type == 'checkbox') {
  1682.                 // Data in checkboxes
  1683.                 val = (inpt.checked) ? 1 : 0;
  1684.             } else {
  1685.                 val = inpt.value;
  1686.             }
  1687.             GM_setValue(tag , val);
  1688.         }
  1689.         // Reparse all user settings
  1690.         this.setSettings();
  1691.     },
  1692.     updateUser: function (el) {
  1693.         // Note that we have succesfully gotten to the callback
  1694.         this.privateHash(el, 'onclose', false );
  1695.         var purl    = this.privateHash(el, 'purl');
  1696.         var setCol = document.getElementById(this.fids.csfCols);
  1697.         if (setCol) {
  1698.             // There is a list of colors attributed to this user
  1699.             var kids = setCol.childNodes;
  1700.             var setCols = new Array();
  1701.             for (var k=0; k < kids.length; k++) {
  1702.                 var col = kids[k].getAttribute('colName');
  1703.                 if (col) setCols.push(col);
  1704.             }
  1705.             GM_setValue("UserColor"+purl, setCols.join(" "));
  1706.         }
  1707.         // Re-color any user links
  1708.         this.colorUserPhotos( purl );
  1709.     },
  1710.     color4string: function( txt ) {
  1711.         // This method takes a string (for example a user ID) and
  1712.         // converts it to a reproducible RGB color. There are probably
  1713.         // more elegant ways to do this (I'd like to know of them) -
  1714.         // the basic goal is to get good spread of the color spectrum,
  1715.         // without being too dark or too light, and avoiding gray
  1716.         // scales.
  1717.         // Make a string that's just the concatenation of all the decimal ascii codes:
  1718.         var hash = "";
  1719.         for (var j = 0; j < txt.length; j++) {
  1720.             var code = txt.charCodeAt(j);
  1721.             hash    += code.toString();
  1722.         }
  1723.         var col     = new Array();
  1724.         var colMv   = 0;
  1725.         // Break the long integer into three equal sized pieces:
  1726.         var block   = Math.floor(hash.length/3);
  1727.         var colSpan = this.colMax - this.colMin + 1;
  1728.         var colBuf  = this.colBuf;
  1729.         if (colBuf > colSpan / 4) colBuf = Math.floor(colSpan / 4);
  1730.         for (var b = 0; b < 3; b++) {
  1731.             var si   = b * block;
  1732.             var subh = hash.substring( si, si + block - 1 );
  1733.             // Turn the sub-hash into colMin-colMax (modulus colSpan)
  1734.             var val = this.colMin + ((parseInt(subh) * 7353) % colSpan);
  1735.             for (var c = 0; c < b; c++) {
  1736.                 // make sure this color value is far enough from the prior ones
  1737.                 var pval = col[c];
  1738.                 if (val > pval - this.colBuf && val < pval + this.colBuf) {
  1739.                     // This color index is too close to another
  1740.                     if (colMv == 0) colMv = (val < pval) ? -1 : 1;
  1741.                     if (colMv > 0) {
  1742.                         val = pval + this.colBuf;
  1743.                         if (val > this.colMax) val -= colSpan;
  1744.                     } else {
  1745.                         val = pval - this.colBuf;
  1746.                         if (val < this.colMin) val += colSpan;
  1747.                     }
  1748.                 }
  1749.             }
  1750.             col.push(val);
  1751.         }
  1752.         // Now finally rotate the three colors
  1753.         var rot = parseInt(hash) %3;
  1754.         for (var r = 0; r < rot; r++) {
  1755.             col.push( col.shift() );
  1756.         }
  1757.         return col;
  1758.     },
  1759.     popUp: function (el, html, evt) {
  1760.         // Popup a mini menu on a mouse click
  1761.         var div = document.getElementById(this.fids.csfPop);
  1762.         if (!div) {
  1763.             // Create the object once, then keep it
  1764.             div = document.createElement('div');
  1765.             div.id = this.fids.csfPop;
  1766.             div.className = 'ToolTip';
  1767.             div.style.zIndex = '9999';
  1768.             document.body.appendChild(div);
  1769.             // Using an event listener to monitor activity on our popup
  1770.             div.addEventListener('click', function (e) {
  1771.                     return CatFlickrSuite.popClick(e);
  1772.                 }, false);
  1773.         } else {
  1774.             // We are recycling the same object as the popup (so only
  1775.             // one popup allowed at a time). Registration of user
  1776.             // changes in the popup occurs when the user closes the
  1777.             // window - make sure that if the window was not
  1778.             // explicitly closed (that is, it is open in another
  1779.             // location) that we still save the user settings:
  1780.             var cb = this.privateHash(div, 'onclose');
  1781.             if (cb) cb( div );
  1782.         }
  1783.         // Position div under click (-15 offset attempts to get close box under mouse)
  1784.         div.style.top     = (evt.pageY - 15) + 'px';
  1785.         div.style.left    = (evt.pageX - 15) + 'px';
  1786.         // Update content:
  1787.         div.innerHTML     = html;
  1788.         // Make sure it is visible:
  1789.         div.style.display = 'block';
  1790.         // clear any private variables associated with the popup
  1791.         this.clearPrivate(div);
  1792.         return div;
  1793.     },
  1794.     popClick: function (e) {
  1795.         // Respond to a click event in our popup
  1796.         if (!e || !e.originalTarget) return;
  1797.         var targ  = e.originalTarget;
  1798.         var par   = targ.parentNode;
  1799.         var cname = targ.className;
  1800.         while (!cname && par) {
  1801.             // Back out of DOM tree until we find a classed target
  1802.             targ  = par;
  1803.             par   = targ.parentNode;
  1804.             cname = targ.className;
  1805.         }
  1806.         if (!par || !cname) return;
  1807.         if (cname == 'CancelButt') {
  1808.             // A click within a close button [x] - hide the popup
  1809.             this.popClose(par);
  1810.         } else if (cname == 'CloseComment') {
  1811.             this.toggleComments(par);
  1812.         } else if (cname == 'SetColor') {
  1813.             // A click within a 'set user color' selection
  1814.             var addTo = document.getElementById
  1815.             (par.id == this.fids.csfCols ? this.fids.csfAvl : this.fids.csfCols);
  1816.             if (!addTo) return;
  1817.             addTo.appendChild(targ);
  1818.         } else if (cname == 'ShowComments') {
  1819.             this.toggleComments(par);
  1820.         }
  1821.     },
  1822.     toggleComments: function (el) {
  1823.         var dispid = this.registerUserPhoto(el);
  1824.         var uname  = this.getTranslation(dispid, 'uname');
  1825.         if (!uname) return;
  1826.         var coms   = this.objects.comments[uname];
  1827.         if (!coms) return;
  1828.         var list  = this.objects.shownComments[uname];
  1829.         if (list) {
  1830.             // Already showing comments - hide them
  1831.             for (var l=0; l < list.length; l++) {
  1832.                 var el = list[l];
  1833.                 el.parentNode.removeChild(el);
  1834.             }
  1835.             this.objects.shownComments[uname] = null;
  1836.             return;
  1837.         }
  1838.         list = this.objects.shownComments[uname] = new Array();
  1839.         var struct = new Object();
  1840.         for (var i=0; i < coms.length; i++) {
  1841.             var info = coms[i];
  1842.             var pid  = info.photo;
  1843.             if (!struct[pid]) struct[pid] = new Array();
  1844.             struct[pid].push( info.txt );
  1845.         }
  1846.         var pool = this.objects.poolImages;
  1847.         var purl  = this.privateHash(el, 'purl');
  1848.         var col  = "rgb("+this.color4string( purl )+")";
  1849.         var elips = "<span style='color:red;font-weight:bold'>&hellip;</span>";
  1850.         for (var pid in struct) {
  1851.             var targ = pool[pid];
  1852.             if (!targ) {
  1853.                 this.err("Could not find pool image ID="+pid);
  1854.                 continue;
  1855.             }
  1856.             var html = "<span style='color:red;background-color:yellow' class='CloseComment'>["+dispid+"]</span>";
  1857.             var maxlen = this.user.comWidth;
  1858.             for (var c=0; c < struct[pid].length; c++) {
  1859.                 // If there are multiple comments, separate them by
  1860.                 // slightly differnt background colors
  1861.                 var com = struct[pid][c];
  1862.                 if (maxlen > 0 && com.length > maxlen) com = com.substr(0,maxlen) + elips;
  1863.                 html += "<span style='background-color:"+( c%2 ? '#cfc' : '#9f9')+"'>"+com+"</span>";
  1864.             }
  1865.             var el = document.createElement('div');
  1866.             el.innerHTML = html;
  1867.             targ.appendChild(el);
  1868.             el.style.fontSize  = this.user.comSize;
  1869.             el.style.border    = col+" solid 1px";
  1870.             el.style.textAlign = 'left';
  1871.             el.style.zIndex   = 100;
  1872.             el.style.position = 'relative';
  1873.             el.style.left     = '-4px';
  1874.             el.style.width    = '118px';
  1875.             el.className      = "CommentBox";
  1876.             this.privateHash(el, 'dispid', dispid);
  1877.             list.push(el);
  1878.             el.addEventListener('click', function (e) {
  1879.                     return CatFlickrSuite.popClick(e);
  1880.                 }, false);
  1881.             //targ.style.height = "100%";
  1882.         }
  1883.     },
  1884.     popClose: function (el) {
  1885.         // Does the window have a callback associated with it?
  1886.         var cb = this.privateHash(el, 'onclose');
  1887.         if (cb) cb( el );
  1888.         // Set display to none to hide menu
  1889.         el.style.display = 'none';
  1890.     },
  1891.     makeMenu: function( arr ) {
  1892.         // Build a little menu given an array of 'lines'
  1893.         if (!arr || arr.length < 1) return "";
  1894.         var lines = new Array();
  1895.         try {
  1896.             for (var i=0; i < arr.length; i++) {
  1897.                 var info = arr[i];
  1898.                 if (typeof(info) == 'string') {
  1899.                     // If this entry is a simple string, use it as is
  1900.                     lines.push(info);
  1901.                     continue;
  1902.                 }
  1903.                 // Otherwise, assume it is an object that will be turned
  1904.                 // into a tag, with keys being attribute names. The
  1905.                 // 'text' attribute is taken as the link text:
  1906.                 var tag = info.tag;
  1907.                 if (!tag || tag == '') tag = 'a';
  1908.                 var txt = ">"+info.text+"</"+tag+">";
  1909.                 // Free text to put after the link
  1910.                 if (info.post) txt += info.post;
  1911.                 // Remove special attrs so they do not become an part of the tag
  1912.                 delete info.tag; delete info.post; delete info.text;
  1913.                 var attrs = new Array();
  1914.                 for (var attr in info) {
  1915.                     var val = info[attr];
  1916.                     if (!val) val = "";
  1917.                     // Escape single quotes
  1918.                     if (typeof(val) == 'string') val = val.replace("'", "\\'");
  1919.                     attrs.push(attr+"='"+val+"'");
  1920.                 }
  1921.                 txt = "<"+tag+" "+attrs.join(' ')+txt;
  1922.                 if (info.pre) txt = info.pre + txt;
  1923.                 // Join all attributes into an anchor tag
  1924.                 lines.push(txt);
  1925.             }
  1926.         } catch (e) {
  1927.             this.err("Failed to make menu for "+arr.length+" items", e);
  1928.             return "";
  1929.         }
  1930.         // Join all lines into a single block of text
  1931.         return lines.join("<br />\n");
  1932.     },
  1933.     hashToLog: function (obj, title) {
  1934.         var msg = "Hash report for "+obj+":\n";
  1935.         if (title) msg += title + "\n";
  1936.         if (obj) {
  1937.             var num = 0;
  1938.             for (var key in obj) {
  1939.                 msg += key + ": "+obj[key]+"\n";
  1940.                 num++;
  1941.             }
  1942.             msg += num + " key"+(num == 1 ? '' : 's')+"\n";
  1943.         } else {
  1944.             msg += "/null/\n";
  1945.         }
  1946.         GM_log(msg);
  1947.     },
  1948.     valuesForNamedInput: function(form, name) {
  1949.         /* Huh. It used to work that if I had an <input> named 'foo' in a form
  1950.            represented by object bar, I could get it with bar.foo, but
  1951.            not anymore... */
  1952.         var rv = new Array();
  1953.         if (!form || !form.elements || !name) return null;
  1954.         name = name.toLowerCase();
  1955.         for (var e = 0; e < form.elements.length; e++) {
  1956.             var inp = form.elements[e];
  1957.             if (inp.name.toLowerCase() != name) continue;
  1958.             rv.push(inp.value);
  1959.         }
  1960.         return rv;
  1961.     },
  1962.     privateHash: function(el, tag, val) {
  1963.         // Private hash holding tag / value pairs on HTML elements
  1964.         // The function is both a setter and a getter
  1965.         var key = this.setElementId(el);
  1966.         if (!key || !tag)  return null;
  1967.         // Initialize the hash if this is the first access on the element:
  1968.         if (!this.privateData[key]) {
  1969.             // this.gmMsg += "Establish new private data for " + key+"\n";
  1970.             this.privateData[key] = new Object();
  1971.         }
  1972.         tag = tag.toLowerCase();
  1973.         if (val != null) {
  1974.             // Request to set the value
  1975.             this.privateData[key][tag] = val;
  1976.             // this.gmMsg += "Set "+tag+"="+val+" for " + key+"\n";
  1977.         }
  1978.         // Return the current value
  1979.         return this.privateData[key][tag];
  1980.     },
  1981.     logPrivateData: function( hash ) {
  1982.         if (!hash) hash = this.privateData;
  1983.         var txt = "Hash dump for " + hash + "\n";
  1984.         for (var key in hash) {
  1985.             txt += "["+key+"]\n";
  1986.             var kh = hash[key];
  1987.             if (typeof(kh) == 'object') {
  1988.                 for (var tag in kh) {
  1989.                     txt += "  ["+tag+"] = '"+kh[tag]+"'\n";
  1990.                 }
  1991.             } else {
  1992.                 txt += "  !! Hash expected, found '"+kh+"'\n";
  1993.             }
  1994.         }
  1995.         GM_log(txt);
  1996.     },
  1997.     setTranslation: function (data, debugMsg) {
  1998.         // Are any other data associated with these?
  1999.         for (var type in data) {
  2000.             var existing = this.translate[ data[type] ];
  2001.             if (existing) {
  2002.                 // One of these values is already recorded
  2003.                 var novel = this.mergeHash( existing, data );
  2004.                 if (novel == 0) {
  2005.                     // No new additions to the tranlsation hash:
  2006.                     return;
  2007.                 }
  2008.                 data = existing;
  2009.                 break;
  2010.             }
  2011.         }
  2012.         // If uname is not set it is the same as the display ID, if it is not elipsed
  2013.         if (!data.uname && data.dispid &&
  2014.             !this.re.elipsed.test(data.dispid)) data.uname = data.dispid;
  2015.         // We can generally get the username from the displayed ID
  2016.         if (!data.dispid && data.uname) {
  2017.             // I *THINK* 20 is the upper limit... ?
  2018.             if (data.uname < 20) {
  2019.                 data.dispid = uname;
  2020.             } else {
  2021.                 // Hmm...
  2022.             }
  2023.         }
  2024.         // Cycle through the hash again, update all keys in translation to point to same hash:
  2025.         for (var type in data) {
  2026.             if (debugMsg) this.gmMsg += type + " = " + data[type] + "\n";
  2027.             this.translate[data[type]] = data;
  2028.         }
  2029.     },
  2030.     getTranslation: function( term, type ) {
  2031.         var thash = this.translate;
  2032.         var data  = (term in thash) ? thash[term] : null;
  2033.         if (!data) return null; // Nothing at all found
  2034.         if (!type) return data; // The user wants the full hash
  2035.         // Specific term type requested for return
  2036.         if (type in data) return data[type]; // That type is present, return it
  2037.         // We found data, but no match for this type
  2038.         if ('dispid' in data && !('uname' in data) &&  this.re.elipsed.test(term)) {
  2039.             // The query term is an elipsed display id, which does not
  2040.             // yet have a true uname associated with it - see if we
  2041.             // can find a match to a username
  2042.             var elipre  = this.re.elipsed;
  2043.             // Thanks to John Carney for pointing out that I need to
  2044.             // escape RE tokens in the username when building this
  2045.             // regexp. I miss \Q..\E in perl!
  2046.             var matcher = new RegExp(term.replace(elipre,'').
  2047.                                      replace(/([(){}.^$*?+\[\]\\])/g, '\\$1')+'.+$');
  2048.             for (var tag in thash) {
  2049.                 // Ignore if this tag does not match, or is itself
  2050.                 // elipsed, or the matched hash does not have a
  2051.                 // username defined.
  2052.                 if (!matcher.test(tag) || elipre.test(tag) ||
  2053.                     !('uname' in thash[tag])) continue;
  2054.                 // We have a match - combine the two hashes
  2055.                 this.mergeHash(data, thash[tag]);
  2056.                 this.setTranslation(data);
  2057.                 if (type in data) return data[type];
  2058.             }
  2059.         }
  2060.         return null;
  2061.     },
  2062.     mergeHash: function(hashA, hashB) {
  2063.         // Adds the key/val pairs of hashB to hashA
  2064.         var newVals = 0;
  2065.         for (var tag in hashB) {
  2066.             if (!(tag in hashA)) { hashA[tag] = hashB[tag]; newVals++; }
  2067.         }
  2068.         return newVals;
  2069.     },
  2070.     setElementId: function(el) {
  2071.         if (!el) return null;
  2072.         if (!el.id) {
  2073.             // this.gmMsg += "New ID added to " + el + "\n";
  2074.             el.id = "CFS" + "_" + this.ms + '_' + ++this.counter;
  2075.         }
  2076.         return el.id;
  2077.     },
  2078.     clearPrivate: function(el) {
  2079.         // Clear out private variables associated with an element
  2080.         if (!el) return;
  2081.         var key = this.setElementId(el);
  2082.         var rv  = this.privateData[key];
  2083.         // Totally wipe the settings:
  2084.         // this.gmMsg += "Clearing private data for " +key+"\n";
  2085.         this.privateData[key] = new Object();
  2086.         return rv; // Return the old settings
  2087.     },
  2088.     buildGetString: function (args, noToken) {
  2089.         delete args[ "api_sig" ];
  2090.         if (unsafeWindow.global_auth_hash) {
  2091.             // I believe this is the old authentication?
  2092.             args[ "auth_hash" ] = unsafeWindow.global_auth_hash;
  2093.         } else {
  2094.             delete args[ "auth_hash" ];
  2095.         }
  2096.         // Always add the api_key:
  2097.         args[ "api_key" ] = this.apikey;
  2098.         // Add the auth token if it is available
  2099.         if (this.authTok) args[ "auth_token" ] = this.authTok;
  2100.         // if (!noToken && ! args['frob']) args[ "auth_token" ] = this.getAuthToken();
  2101.  
  2102.         // Sort all the parameter names:
  2103.         var argList  = new Array();
  2104.         for (var arg in args) { argList.push( arg ); }
  2105.         argList = argList.sort();
  2106.         // Build the basic parameter list
  2107.         var get = "";
  2108.         for (var al = 0; al < argList.length; al++) {
  2109.             var arg = argList[al];
  2110.             var val = args[arg];
  2111.             if (val == null) continue;
  2112.             if (get) get += "&";
  2113.             get += arg + "=" + val;
  2114.             sig += arg + val;
  2115.         }
  2116.         var signIt = args['auth_token'] || args['frob'] ? 1 : 0;
  2117.         if (signIt) {
  2118.             // We also need to sign the GET parameters
  2119.             var sig = this.getSecKey();
  2120.             for (var al = 0; al < argList.length; al++) {
  2121.                 var arg = argList[al];
  2122.                 var val = args[arg];
  2123.                 if (val == null) continue;
  2124.                 sig += arg + val;
  2125.             }
  2126.             // MD5 the signature string and append as a new parameter:
  2127.             var md5 = hex_md5(sig);
  2128.             get += "&api_sig="+md5;
  2129.         }
  2130.         return get;
  2131.     },
  2132.     getSecKey : function () {
  2133.         return this.seckey;
  2134.     },
  2135.     getAuthToken : function () {
  2136.         if (this.authTok) return this.authTok;
  2137.         // Try to get token from local store:
  2138.         this.authTok = GM_getValue("FlickrAuthTok");
  2139.         if (this.authTok) {
  2140.             GM_log("Authorization token recovered from local storage - " + this.authTok);
  2141.             return this.authTok;
  2142.         }
  2143.         // Need to generate new token:
  2144.         return this.frobToAuth();
  2145.     },
  2146.     frobToAuth: function () {
  2147.         var frob = this.getFrob();
  2148.         this.flickrApi( { method: "flickr.auth.getToken", frob: frob }, 'parseAuth' );
  2149.         return this.authTok;
  2150.     },
  2151.     parseAuth: function (rsp) {
  2152.         var toks = new Array();
  2153.         for each (auth in rsp.auth) {
  2154.            for each (tok in auth.token) {
  2155.                var token = tok + "";
  2156.                if (token) toks.push(token);
  2157.            }
  2158.         }
  2159.         if (toks.length == 1) {
  2160.             this.authTok = toks[0];
  2161.             GM_setValue("FlickrAuthTok", toks[0]);
  2162.             GM_log("Authorization token returned by Flickr API");
  2163.         } else {
  2164.             this.err("Failed to recover auth_token");
  2165.         }
  2166.         return this.authTok;
  2167.     },
  2168.     getFrob: function () {
  2169.         if (this.frob) return this.frob;
  2170.         // Try to get frob from local store:
  2171.         this.frob = GM_getValue("FlickrFrob");
  2172.         if (this.frob) {
  2173.             GM_log("Frob recovered from local storage");
  2174.             return this.frob;
  2175.         }
  2176.         // Need to go to authentication page
  2177.         var get = this.buildGetString( { perms: 'write' }, 'NO AUTH' );
  2178.         var url = "http://www.flickr.com/services/auth/?" + get;
  2179.         // Need to open a new page
  2180.         window.open(url, "_blank");
  2181.         var msg = "";
  2182.         if (this.frobTry) msg += "Hm. You have tried "+this.frobTry+
  2183.                               " time(s) but have not authenticated...\n";
  2184.         msg +=
  2185.         "Flicker Functional Suite has opened a new window.\n"+
  2186.         "It will request 'write' permission for your photo stream.\n"+
  2187.         "If you are comfortable with that, please grant permissions\n"+
  2188.         "and close this alert AFTER you grant them.\n"+
  2189.         "If you are not, you may ignore the request, but FFS will not function properly"
  2190.         alert(msg);
  2191.         this.frobTry++;
  2192.         return grabFrob();
  2193.     },
  2194.     grabFrob: function () {
  2195.         var loc = document.location.href;
  2196.         var mat = loc.match(this.re.frob);
  2197.         if (!mat) return;
  2198.         GM_setValue("FlickrFrob", this.frob = mat[1]);
  2199.         GM_log("Frob recognized from Flickr authentication page");
  2200.     },
  2201.     flickrApi: function( args, cbname, cfsArgs ) {
  2202.         /* Generic method for an AJAX call to the Flickr API
  2203.          * cfsArgs
  2204.          *   failok: if true, then still execute the callback when error code encountered
  2205.          */
  2206.         var callback = this[cbname];
  2207.         var get      = this.buildGetString( args );
  2208.         if (!get) {
  2209.             // Failed to build get string. This usually means that authentication is under way
  2210.             // Store the arguments for recovery after
  2211.             return this.delayApi( args, cbname, cfsArgs );
  2212.         }
  2213.  
  2214.         var url = "http://api.flickr.com/services/rest/?" + get;
  2215.  
  2216.         var ticket = ++this.ticket;
  2217.         if (!cfsArgs) cfsArgs = new Object();
  2218.         cfsArgs.ticket = ticket;
  2219.         cfsArgs.url = url;
  2220.         if (cfsArgs.ticktype) {
  2221.             var tkey = cfsArgs.ticktype;
  2222.             if (!this.ticketStatus[tkey]) this.ticketStatus[tkey] = new Object();
  2223.             this.ticketStatus[tkey][ticket] = 'pending';
  2224.         }
  2225.         GM_xmlhttpRequest
  2226.         ({ method: "GET", url: url, headers: {
  2227.             "User-agent": "Mozilla/4.0 (compatible) Greasemonkey (Flickr Functional Suite)",
  2228.                 "Accept": "application/atom+xml,application/xml,text/xml",
  2229.             }, onload: function(rsp) { CatFlickrSuite.parseXML(rsp,cbname,args,cfsArgs, url) } } );
  2230.         return ticket;
  2231.     },
  2232.     delayApi: function ( args, cbname, cfsArgs ) {
  2233.         if (!this.apiDelayStack) this.apiDelayStack = new Array;
  2234.         this.apiDelayStack.push( [ args, cbname, cfsArgs ] );
  2235.         return this.apiDelayStack.length;
  2236.     },
  2237.     resumeApi : function () {
  2238.         var stack = this.apiDelayStack;
  2239.         // Transfer full contents of delayed stack to local array
  2240.         var lStck = new Array();
  2241.         while (stack.length) {
  2242.             lStck.push( stack.shift() );
  2243.         }
  2244.         while (lStck.length) {
  2245.             var dat = lStck.shift();
  2246.             var ticket = this.flickrApi( dat[0], dat[1], dat[2] );
  2247.             GM_log("Resuming API call: "+dat[1]);
  2248.         }
  2249.     },
  2250.     parseXML: function(response, cbname, args,cfsArgs, url) {
  2251.         // Takes an XML response from Flickr services and turns it into a E4X object
  2252.         // http://developer.mozilla.org/presentations/xtech2005/e4x/
  2253.         var txt  = response.responseText;
  2254.         txt      = txt.replace(/\s*\<\?[^\>]+\?\>\s*/g,'');
  2255.         var rsp  = new XML(txt);
  2256.         var stat = rsp['@stat'];
  2257.         var tick = cfsArgs.ticket;
  2258.         var tt   = cfsArgs.ticktype;
  2259.         var rv   = null;
  2260.         if (stat != 'ok') {
  2261.             var msg = "Failed to retrieve Flickr data via API:\n";
  2262.             cfsArgs.error = '|';
  2263.             var seenErrs = new Object();
  2264.             for each (err in rsp.err) {
  2265.                 var ec = err['@code'];
  2266.                 seenErrs[ec] = 1;
  2267.                 msg += "  Error: " +ec+ " = "+err['@msg']+"\n";
  2268.                 // cfsArgs.error += 'id='+args.photo_id+' ';
  2269.                 cfsArgs.error += err['@msg'] + '|';
  2270.             }
  2271.             for (var arg in args) {
  2272.                 msg += "  "+arg+'='+args[arg]+"\n";
  2273.             }
  2274.             msg += "URL: "+ url;
  2275.             if (seenErrs['99']) {
  2276.                 // Insufficient priveleges. We need to start the authentication chain
  2277.                 if (cfsArgs.pendingAuth) {
  2278.                     msg += "\nFAILED PRIOR AUTHENTICATION";
  2279.                 } else {
  2280.                     this.delayApi( args, cbname, cfsArgs );
  2281.                     cfsArgs.error = '[Authenticating...]';
  2282.                     cfsArgs.pendingAuth = 1;
  2283.                     this.getAuthToken();
  2284.                     this.resumeApi();
  2285.                     return '[Authenticating...]';
  2286.                     msg = "Authentication required, attempting to authenticate";
  2287.                 }
  2288.             }
  2289.             this.err(msg);
  2290.             if (tt) this.ticketStatus[tt][tick] = 'failed';
  2291.             if (!cfsArgs.failok) return rv;
  2292.         }
  2293.         try {
  2294.             rv = this[cbname](rsp, args, cfsArgs);
  2295.         } catch (e) {
  2296.             this.err("Failed to execute API callback "+cbname, e);
  2297.             if (tt) this.ticketStatus[tt][tick] = 'failed';
  2298.         }
  2299.         // Remove the ticket from the queue as being completed
  2300.         if (tt) delete this.ticketStatus[tt][tick];
  2301.         return rv;
  2302.     },
  2303.     apiStatus: function(tt) {
  2304.         // Report the status of an API queue
  2305.         if (!(tt in this.ticketStatus)) return "";
  2306.         var struct = new Object();
  2307.         for (var ticket in this.ticketStatus[tt]) {
  2308.             var stat = this.ticketStatus[tt][ticket];
  2309.             if (!struct[ stat ]) struct[ stat ] = 0;
  2310.             struct[ stat ]++;
  2311.         }
  2312.         var list = new Array();
  2313.         for (var stat in struct) {
  2314.             list.push( struct[ stat ] + ' ' + stat);
  2315.         }
  2316.         return list.join(",");
  2317.     },
  2318. };
  2319.  
  2320. // This is the call that starts the ball rolling - it launches the
  2321. // init() method when the page finishes loading:
  2322. window.addEventListener('load', function (e) {CatFlickrSuite.init();}, false);
  2323.  
  2324.  
  2325. /*
  2326.  * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  2327.  * Digest Algorithm, as defined in RFC 1321.
  2328.  * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  2329.  * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  2330.  * Distributed under the BSD License
  2331.  * See http://pajhome.org.uk/crypt/md5 for more info.
  2332.  */
  2333.  
  2334. /*
  2335.  * Configurable variables. You may need to tweak these to be compatible with
  2336.  * the server-side, but the defaults work in most cases.
  2337.  */
  2338. var hexcase = 0;   /* hex output format. 0 - lowercase; 1 - uppercase        */
  2339. var b64pad  = "";  /* base-64 pad character. "=" for strict RFC compliance   */
  2340.  
  2341. /*
  2342.  * These are the functions you'll usually want to call
  2343.  * They take string arguments and return either hex or base-64 encoded strings
  2344.  */
  2345. function hex_md5(s)    { return rstr2hex(rstr_md5(str2rstr_utf8(s))); }
  2346. function b64_md5(s)    { return rstr2b64(rstr_md5(str2rstr_utf8(s))); }
  2347. function any_md5(s, e) { return rstr2any(rstr_md5(str2rstr_utf8(s)), e); }
  2348. function hex_hmac_md5(k, d)
  2349.   { return rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
  2350. function b64_hmac_md5(k, d)
  2351.   { return rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); }
  2352. function any_hmac_md5(k, d, e)
  2353.   { return rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
  2354.  
  2355. /*
  2356.  * Perform a simple self-test to see if the VM is working
  2357.  */
  2358. function md5_vm_test()
  2359. {
  2360.   return hex_md5("abc").toLowerCase() == "900150983cd24fb0d6963f7d28e17f72";
  2361. }
  2362.  
  2363. /*
  2364.  * Calculate the MD5 of a raw string
  2365.  */
  2366. function rstr_md5(s)
  2367. {
  2368.   return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
  2369. }
  2370.  
  2371. /*
  2372.  * Calculate the HMAC-MD5, of a key and some data (raw strings)
  2373.  */
  2374. function rstr_hmac_md5(key, data)
  2375. {
  2376.   var bkey = rstr2binl(key);
  2377.   if(bkey.length > 16) bkey = binl_md5(bkey, key.length * 8);
  2378.  
  2379.   var ipad = Array(16), opad = Array(16);
  2380.   for(var i = 0; i < 16; i++)
  2381.   {
  2382.     ipad[i] = bkey[i] ^ 0x36363636;
  2383.     opad[i] = bkey[i] ^ 0x5C5C5C5C;
  2384.   }
  2385.  
  2386.   var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
  2387.   return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
  2388. }
  2389.  
  2390. /*
  2391.  * Convert a raw string to a hex string
  2392.  */
  2393. function rstr2hex(input)
  2394. {
  2395.   try { hexcase } catch(e) { hexcase=0; }
  2396.   var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  2397.   var output = "";
  2398.   var x;
  2399.   for(var i = 0; i < input.length; i++)
  2400.   {
  2401.     x = input.charCodeAt(i);
  2402.     output += hex_tab.charAt((x >>> 4) & 0x0F)
  2403.            +  hex_tab.charAt( x        & 0x0F);
  2404.   }
  2405.   return output;
  2406. }
  2407.  
  2408. /*
  2409.  * Convert a raw string to a base-64 string
  2410.  */
  2411. function rstr2b64(input)
  2412. {
  2413.   try { b64pad } catch(e) { b64pad=''; }
  2414.   var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2415.   var output = "";
  2416.   var len = input.length;
  2417.   for(var i = 0; i < len; i += 3)
  2418.   {
  2419.     var triplet = (input.charCodeAt(i) << 16)
  2420.                 | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
  2421.                 | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
  2422.     for(var j = 0; j < 4; j++)
  2423.     {
  2424.       if(i * 8 + j * 6 > input.length * 8) output += b64pad;
  2425.       else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
  2426.     }
  2427.   }
  2428.   return output;
  2429. }
  2430.  
  2431. /*
  2432.  * Convert a raw string to an arbitrary string encoding
  2433.  */
  2434. function rstr2any(input, encoding)
  2435. {
  2436.   var divisor = encoding.length;
  2437.   var i, j, q, x, quotient;
  2438.  
  2439.   /* Convert to an array of 16-bit big-endian values, forming the dividend */
  2440.   var dividend = Array(Math.ceil(input.length / 2));
  2441.   for(i = 0; i < dividend.length; i++)
  2442.   {
  2443.     dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  2444.   }
  2445.  
  2446.   /*
  2447.    * Repeatedly perform a long division. The binary array forms the dividend,
  2448.    * the length of the encoding is the divisor. Once computed, the quotient
  2449.    * forms the dividend for the next step. All remainders are stored for later
  2450.    * use.
  2451.    */
  2452.   var full_length = Math.ceil(input.length * 8 /
  2453.                                     (Math.log(encoding.length) / Math.log(2)));
  2454.   var remainders = Array(full_length);
  2455.   for(j = 0; j < full_length; j++)
  2456.   {
  2457.     quotient = Array();
  2458.     x = 0;
  2459.     for(i = 0; i < dividend.length; i++)
  2460.     {
  2461.       x = (x << 16) + dividend[i];
  2462.       q = Math.floor(x / divisor);
  2463.       x -= q * divisor;
  2464.       if(quotient.length > 0 || q > 0)
  2465.         quotient[quotient.length] = q;
  2466.     }
  2467.     remainders[j] = x;
  2468.     dividend = quotient;
  2469.   }
  2470.  
  2471.   /* Convert the remainders to the output string */
  2472.   var output = "";
  2473.   for(i = remainders.length - 1; i >= 0; i--)
  2474.     output += encoding.charAt(remainders[i]);
  2475.  
  2476.   return output;
  2477. }
  2478.  
  2479. /*
  2480.  * Encode a string as utf-8.
  2481.  * For efficiency, this assumes the input is valid utf-16.
  2482.  */
  2483. function str2rstr_utf8(input)
  2484. {
  2485.   var output = "";
  2486.   var i = -1;
  2487.   var x, y;
  2488.  
  2489.   while(++i < input.length)
  2490.   {
  2491.     /* Decode utf-16 surrogate pairs */
  2492.     x = input.charCodeAt(i);
  2493.     y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
  2494.     if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
  2495.     {
  2496.       x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
  2497.       i++;
  2498.     }
  2499.  
  2500.     /* Encode output as utf-8 */
  2501.     if(x <= 0x7F)
  2502.       output += String.fromCharCode(x);
  2503.     else if(x <= 0x7FF)
  2504.       output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
  2505.                                     0x80 | ( x         & 0x3F));
  2506.     else if(x <= 0xFFFF)
  2507.       output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
  2508.                                     0x80 | ((x >>> 6 ) & 0x3F),
  2509.                                     0x80 | ( x         & 0x3F));
  2510.     else if(x <= 0x1FFFFF)
  2511.       output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
  2512.                                     0x80 | ((x >>> 12) & 0x3F),
  2513.                                     0x80 | ((x >>> 6 ) & 0x3F),
  2514.                                     0x80 | ( x         & 0x3F));
  2515.   }
  2516.   return output;
  2517. }
  2518.  
  2519. /*
  2520.  * Encode a string as utf-16
  2521.  */
  2522. function str2rstr_utf16le(input)
  2523. {
  2524.   var output = "";
  2525.   for(var i = 0; i < input.length; i++)
  2526.     output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
  2527.                                   (input.charCodeAt(i) >>> 8) & 0xFF);
  2528.   return output;
  2529. }
  2530.  
  2531. function str2rstr_utf16be(input)
  2532. {
  2533.   var output = "";
  2534.   for(var i = 0; i < input.length; i++)
  2535.     output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
  2536.                                    input.charCodeAt(i)        & 0xFF);
  2537.   return output;
  2538. }
  2539.  
  2540. /*
  2541.  * Convert a raw string to an array of little-endian words
  2542.  * Characters >255 have their high-byte silently ignored.
  2543.  */
  2544. function rstr2binl(input)
  2545. {
  2546.   var output = Array(input.length >> 2);
  2547.   for(var i = 0; i < output.length; i++)
  2548.     output[i] = 0;
  2549.   for(var i = 0; i < input.length * 8; i += 8)
  2550.     output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (i%32);
  2551.   return output;
  2552. }
  2553.  
  2554. /*
  2555.  * Convert an array of little-endian words to a string
  2556.  */
  2557. function binl2rstr(input)
  2558. {
  2559.   var output = "";
  2560.   for(var i = 0; i < input.length * 32; i += 8)
  2561.     output += String.fromCharCode((input[i>>5] >>> (i % 32)) & 0xFF);
  2562.   return output;
  2563. }
  2564.  
  2565. /*
  2566.  * Calculate the MD5 of an array of little-endian words, and a bit length.
  2567.  */
  2568. function binl_md5(x, len)
  2569. {
  2570.   /* append padding */
  2571.   x[len >> 5] |= 0x80 << ((len) % 32);
  2572.   x[(((len + 64) >>> 9) << 4) + 14] = len;
  2573.  
  2574.   var a =  1732584193;
  2575.   var b = -271733879;
  2576.   var c = -1732584194;
  2577.   var d =  271733878;
  2578.  
  2579.   for(var i = 0; i < x.length; i += 16)
  2580.   {
  2581.     var olda = a;
  2582.     var oldb = b;
  2583.     var oldc = c;
  2584.     var oldd = d;
  2585.  
  2586.     a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
  2587.     d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
  2588.     c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
  2589.     b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
  2590.     a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
  2591.     d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
  2592.     c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
  2593.     b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
  2594.     a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
  2595.     d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
  2596.     c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
  2597.     b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
  2598.     a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
  2599.     d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
  2600.     c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
  2601.     b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
  2602.  
  2603.     a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
  2604.     d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
  2605.     c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
  2606.     b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
  2607.     a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
  2608.     d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
  2609.     c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
  2610.     b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
  2611.     a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
  2612.     d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
  2613.     c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
  2614.     b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
  2615.     a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
  2616.     d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
  2617.     c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
  2618.     b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
  2619.  
  2620.     a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
  2621.     d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
  2622.     c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
  2623.     b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
  2624.     a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
  2625.     d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
  2626.     c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
  2627.     b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
  2628.     a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
  2629.     d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
  2630.     c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
  2631.     b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
  2632.     a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
  2633.     d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
  2634.     c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
  2635.     b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
  2636.  
  2637.     a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
  2638.     d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
  2639.     c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
  2640.     b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
  2641.     a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
  2642.     d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
  2643.     c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
  2644.     b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
  2645.     a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
  2646.     d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
  2647.     c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
  2648.     b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
  2649.     a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
  2650.     d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
  2651.     c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
  2652.     b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
  2653.  
  2654.     a = safe_add(a, olda);
  2655.     b = safe_add(b, oldb);
  2656.     c = safe_add(c, oldc);
  2657.     d = safe_add(d, oldd);
  2658.   }
  2659.   return Array(a, b, c, d);
  2660. }
  2661.  
  2662. /*
  2663.  * These functions implement the four basic operations the algorithm uses.
  2664.  */
  2665. function md5_cmn(q, a, b, x, s, t)
  2666. {
  2667.   return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
  2668. }
  2669. function md5_ff(a, b, c, d, x, s, t)
  2670. {
  2671.   return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
  2672. }
  2673. function md5_gg(a, b, c, d, x, s, t)
  2674. {
  2675.   return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
  2676. }
  2677. function md5_hh(a, b, c, d, x, s, t)
  2678. {
  2679.   return md5_cmn(b ^ c ^ d, a, b, x, s, t);
  2680. }
  2681. function md5_ii(a, b, c, d, x, s, t)
  2682. {
  2683.   return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
  2684. }
  2685.  
  2686. /*
  2687.  * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  2688.  * to work around bugs in some JS interpreters.
  2689.  */
  2690. function safe_add(x, y)
  2691. {
  2692.   var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  2693.   var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  2694.   return (msw << 16) | (lsw & 0xFFFF);
  2695. }
  2696.  
  2697. /*
  2698.  * Bitwise rotate a 32-bit number to the left.
  2699.  */
  2700. function bit_rol(num, cnt)
  2701. {
  2702.   return (num << cnt) | (num >>> (32 - cnt));
  2703. }
  2704.  
Add Comment
Please, Sign In to add comment