Remy's back! A script for those who don't want to read the source


  • FoxDev

    Continuing the discussion from The Fizz Buzz from Outer Space:

    @aliceif said:

    The cornify was really easy to find.
    But I find myself incapable of understanding WTF the "source code" is supposed to mean.

    if one is impatient with Remy's posts and wants to find all those html comments and the cornify script without looking through the HTML source code (and going WTF more than once on the way) I present to you my "auto Remify" greasemonkey script.

    Enjoy

    // ==UserScript==
    // @name       Auto Remify
    // @namespace  http://use.i.E.your.homepage/
    // @version    0.2
    // @description  enter something useful
    // @match      http://thedailywtf.com/*
    // @copyright  2012+, You
    // ==/UserScript==
    
    function remify(){
        function inner() {
    		document.querySelector('.ArticleBody').innerHTML=document.querySelector('.ArticleBody').innerHTML.replace(/<!--​/g,"<span style='color: red'> (").replace(/-->/g,") </span>");
            var clicker = document.querySelector('.ArticleBody span[onclick]');
            if (clicker) {
        		clicker.style.color = 'magenta';
            }
        }
        if (document.body){
            inner();
        } else {
            setTimeout(remify, 5);
        }
    }
    
    remify();
    

    Edit: clarified what i meant by 'source code' due to some certain pendants that i shall not name



  • a bookmarklet version:

    javascript:void(function(){document.querySelector('.ArticleBody').innerHTML=document.querySelector('.ArticleBody').innerHTML.replace(/<!--​/g,"<span style='color: red'> (").replace(/-->/g,") </span>");document.querySelector('.ArticleBody span[onclick]').style.color = 'magenta';}())
    ```


  • Mine's bigger.

    • Thumbnail images in article until mouseover
    • Destroys deeply-nested [quote] tags to save space
    • Makes HTML comments visible; auto-detects if they contain plain text or HTML
    • Broken images: displays the correct image if .png should be .jpg or vice versa
    • Turns text URLs into hyperlinks
    • Detects spammy comments using lzw-compression; one-lines them to save space
    • Detects duplicate comments; hides the duplicates
    • Makes contents of display:none or visibility:hidden elements visible
    • Adds [host.com] after hyperlinks to third-party websites (except wikimedia, etc.)
    • Adds an old-school comments link to articles that use Discourse
    • Does nothing to the cornify link. I have cornify adblocked anyway.

    Disclosure: I did not personally write the lzw_encode function.

    // ==UserScript==
    // @name        TDWTF
    // @namespace   custom
    // @description This script makes "hidden" content visible on TDWTF without needing to view-source, along with a handful of other tweaks and fixes.
    // @include     http://thedailywtf.com/*
    // @include     http://*.thedailywtf.com/*
    // @grant       none
    // run-at       document-start
    // ==/UserScript==
    
    function lzw_encode(s) {
        if (String(s) == "") return "";
        
        var dict = {};
        var data = (s + "").split("");
        var out = [];
        var currChar;
        var phrase = data[0];
        var code = 256;
        for (var i=1; i<data.length; i++) {
            currChar=data[i];
            if (dict[phrase + currChar] != null) {
                phrase += currChar;
            }
            else {
                out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
                dict[phrase + currChar] = code;
                code++;
                phrase=currChar;
            }
        }
        out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
        for (var i=0; i<out.length; i++) {
            out[i] = String.fromCharCode(out[i]);
        }
        return out.join("");
    }
    
    try {
        // script to execute before document starts loading
        document.body.appendChild(document.createElement("style")).innerHTML =
            ".ArticleBody img,.CommentContainer blockquote img{max-width:128px;max-height:128px}" +
            ".ArticleBody img:hover,.CommentContainer blockquote img:hover{max-width:none;max-height:none}" +
            ".ArticleBody blockquote img,.CommentContainer img,.ForumPostBodyArea img{max-width:100%;height:auto}" +
            ".ArticleBody blockquote img:hover,.CommentContainer img:hover,.ForumPostBodyArea img:hover{max-width:none!important}" +
            "blockquote+blockquote+blockquote br,blockquote+blockquote+blockquote blockquote," +
            ".spam,.spam *{display:inline;white-space:nowrap;overflow:auto;border:none!important;margin:0!important;" +
            "padding:0!important;background:none}.spam br{display:none}" + 
            ".spam img{max-height:1em!important;max-width:1em!important;vertical-align:text-bottom}" +
            "blockquote blockquote blockquote,blockquote blockquote blockquote div{padding:2px!important;margin:0}" +
            "blockquote blockquote{margin-right:8px!important}" +
            "blockquote blockquote blockquote blockquote blockquote blockquote blockquote " +
            "blockquote blockquote blockquote{display:none}";
    
        // script to execute when DOMContentLoaded event occurs
        window.addEventListener("DOMContentLoaded", function () {
            try {
                var pgbase = window.location.hostname.match(/[^\.]+\.[^\.]+$/).pop(), id, comments = [];
                id = (window.location.hostname == "forums.thedailywtf.com" ? "CommonBody" : "Primary");
                for (e = [document.getElementById(id)]; e.length > 0 && e[0] != null; e.shift()) {
                    if (e[0].nodeType == e[0].COMMENT_NODE) {
                        // Make comments visible by inserting the contents of the comment node inside a new <span> element
                        with (e[0].parentElement.insertBefore(document.createElement("span"), e[0])) {
                            e[0].parentNode.removeChild(e[0]);
                            
                            with (style) {
                                fontStyle = "italic";
                                color = "#008000";
                            }
                            
                            var text = e[0].data;
                            if (text.match(/^\s*([^\s])/)[1] == "<" && text.match(/([^\s])\s*$/)[1] == ">" && text.split("<").length == text.split(">").length) {
                                // this looks like HTML, so try setting it as the innerHTML
                                innerHTML = text;
                                title = text;
                            } else {
                                // assume it's plain text
                                style.whiteSpace = "pre-line";
                                appendChild(document.createTextNode(" " + text + " "));
                            }
                            
                            // Add new child nodes to the list so they will be processed (for instance, images or text URLs)
                            if (hasChildNodes()) for (i = 0; i < childNodes.length; ++ i) e.push(childNodes[i]);
                        }
                        
                    } else if (e[0].nodeType == e[0].ELEMENT_NODE && e[0].tagName == "IMG") {
                        // Set onerror event to check image when it finishes loading
                        e[0].onerror = function () {
                            if (this.naturalWidth == 0 && this.src.indexOf("//img.thedailywtf.com/") >= 0) {
                                // Image appears to be broken - try changing the extension
                                var f = this.src.split("."), ext = f.pop();
                                var img = this.parentElement.insertBefore(document.createElement("img"), this.nextSibling);
                                img.style.display = "none";
                                img.onload = function () {
                                    if (this.naturalWidth != 0) {
                                        this.style.display = "";
                                        console.log("Broken image (" + this.oldSrc + ") was replaced with " + this.src);
                                    }
                                };
                                img.oldSrc = f.join(".") + ext;
                                f.push(ext == "jpg" ? "png" : "jpg");
                                img.src = f.join(".");
                            } else {
                                this.onclick = function () {
                                    if (this.style.maxWidth) {
                                        this.style.maxWidth = "";
                                        this.style.maxHeight = "";
                                    } else {
                                        this.style.maxWidth = "100%";
                                        this.style.maxHeight = "none";
                                    }
                                };
                            }
                        };
                        // If image has already finished loading, onerror won't fire - call it manually
                        if (e[0].complete) e[0].onerror();
                        
                    } else if (e[0].nodeType == e[0].TEXT_NODE) {
                        // Turn URLs into hyperlinks
                        var parent = e[0].parentElement;
                        while (parent && parent.tagName != "A" && !parent.classList.contains("CommentSubHeading")) parent = parent.parentElement;
                        if (!parent || parent.tagName != "A" && !parent.classList.contains("CommentSubHeading")) {
                            var text = e[0].data, url;
                            
                            if (text.indexOf("http colon slash slash ") >= 0) e[0].data = text = text.replace("http colon slash slash ", "http://");
                            if (text.indexOf("https colon slash slash ") >= 0) e[0].data = text = text.replace("https colon slash slash ", "https://");
                            
                            // Attempt to separate the URL from the surrounding text
                            if (url = text.match(/([^\s]?)[\s]*(((https?|ftp):?\/\/|www\.|[a-zA-Z0-9]+\.com\/)[^\s:\/<>\[\]"\.][^\s:\/<>\[\]"]+(:[0-9]+\/)?[^\s:<>\[\]"]*)/)) {
                                var braces = ["()", "{}", "[]", "<>", "''", '""'];
                                while (braces.length) {
                                    if (url[1] == braces[0].charAt(0) && (i = url[2].indexOf(braces[0].charAt(1))) >= 0) {
                                        var count = url[2].split(braces[0].charAt(1)).length - url[2].split(braces[0].charAt(0)).length;
                                        while (count > 0 && url[2].indexOf(braces[0].charAt(1), i + 1) >= 0) {
                                            i = url[2].indexOf(braces[0].charAt(1), i + 1);
                                            -- count;
                                        }
                                        url[2] = url[2].substring(0, i);
                                    }
                                    braces.shift();
                                }
                                
                                while (url[2].length > 0 && ";.!?'".indexOf(url[2].charAt(url[2].length - 1)) >= 0)
                                    url[2] = url[2].substring(0, url[2].length - 1);
                                
                                var i = text.indexOf(url[2]), a, h;
                                e[0].data = text.substring(0, i);
                                h = url[2].replace(/^(https?|ftp)\/\//, "$1://").replace(/^www\./, "http://www.");
                                if (h.indexOf("://") < 0) h = "http://" + h;
                                with (a = document.createElement("a")) {
                                    setAttribute("target", "_blank");
                                    setAttribute("href", h);
                                    appendChild(document.createTextNode(url[2]));
                                }
                                e[0].parentNode.insertBefore(a, e[0].nextSibling);
                                e.push(a);
                                e[0].parentNode.insertBefore(i = document.createTextNode(text.substring(text.indexOf(url[2]) + url[2].length)), a.nextSibling);
                                e.push(i);
                            }
                        }
                        
                        if (e[0].data.length > 200 && !e[0].data.match(/\s/)) e[0].parentElement.style.wordBreak = "break-all";
                        if (e[0].data.length > 2048) {
                            var percent = lzw_encode(e[0].data).length / e[0].data.length;
                            if (percent < 0.3) {
                                // post compression filter - if text compresses by more than 70%, oneline it
                                with (e[0].parentElement.style) {
                                    whiteSpace = "nowrap";
                                    overflow = "auto";
                                }
                                e[0].parentElement.title = "Post compression filter triggered ("
                                   + (100 * (1 - percent)).toFixed(2) + "% reduction)";
                            } else if (percent < 0.5) {
                                e[0].parentElement.title = "Post compression filter almost triggered ("
                                   + (100 * (1 - percent)).toFixed(2) + "% reduction)";
                            }
                        }
                        
                    } else {
                        if (e[0].nodeType == e[0].ELEMENT_NODE) {
                            // Make elements with display="none" or visibility="hidden" visible if they have no id and no class
                            if (e[0].id == "" && e[0].className == "") {
                                with (e[0].style) {
                                    if (display == "none" || visibility && visibility != "visible") {
                                        display = "";
                                        visibility = "visible";
                                        fontStyle = "italic";
                                        color = "#008000";
                                    }
                                }
                            }
                            
                            // Add [host.com] after links to third-party websites (except for a few "safe" host names)
                            if (e[0].tagName == "A" && e[0].hostname > "") {
                                var host, base = e[0].hostname.indexOf(".") > 0 ? e[0].hostname.match(/[^\.]+\.[^\.]+$|[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/).pop() : e[0].hostname;
                                var safe = ["creativecommons.org","wikimedia.org","wikipedia.org"];
                                safe = "|" + safe.join("|") + "|";
                                if (base == "ac.uk" || base == "co.uk" || base == "gov.uk" || base == "ltd.uk" || base == "net.uk" || base == "org.uk") {
                                    if (host = e[0].hostname.match(/[^\.]+\.[^\.]+\.[^\.]+$/)) base = host.pop();
                                }
                                if (e[0].host.indexOf(":") >= 0) base += ":" + e[0].host.split(":").pop();
                                if (pgbase != base) {
                                    if (safe.indexOf("|" + base + "|") >= 0 || (e[0].href == e[0].innerHTML && window.getComputedStyle(e[0]).whiteSpace == "pre")) {
                                        if (e[0].title > "") {
                                            e[0].title = e[0].title + " [" + base + "]";
                                        } else {
                                            e[0].title = base;
                                        }
                                    } else {
                                        e[0].parentNode.insertBefore(document.createTextNode(" [" + base + "]"), e[0].nextSibling);
                                    }
                                }
                                
                                if (e[0].host == "what.thedailywtf.com" && e[0].textContent.toLowerCase().indexOf("comment") >= 0) {
                                    var a = document.getElementById("MainContent_Discourse");
                                    if (!a) {
                                        a = document.getElementById("MainContent_lnkComments");
                                        var node = a.parentNode.insertBefore(document.createTextNode(" • "), a);
                                        var a = node.parentNode.insertBefore(document.createElement("A"), node);
                                        a.appendChild(document.createTextNode("Discourse"));
                                        a.id = "MainContent_Discourse";
                                        a.href = e[0].href;
                                    }
                                    
                                    e[0].href = window.location.href.split("?")[0].split("#")[0].replace("/Articles/", "/Comments/");
                                    if (e[0].textContent.toLowerCase().indexOf("add") == 0) {
                                        e[0].onclick = function () {
                                            wtf("http://thedailywtf.com/Comments/AddComment.aspx?ArticleId=");
                                            return false;
                                        };
                                    } else {
                                        // If the label contains a number first (e.g. "13 Comments"), remove that as it pertains
                                        // to the number of comments in the Discourse thread and not the old-style forum thread.
                                        var s = e[0].textContent.split(" "), n = s.shift();
                                        if (isFinite(Number(n))) e[0].textContent = s.join(" ");
                                    }
                                }
                            }
                            
                            if (e[0].classList.contains("CommentBodyText")) {
                                var html = e[0].innerHTML;
                                if (html > "" && typeof comments[html] == "undefined") {
                                    comments[html] = true;
                                    html = html.replace(/<img [^>]*src="?([^">]*)"?[^>]*>/g, " $1 ");
                                    var t = html.replace(/(\s*<[^>]*>\s*)+|\s{2,}/g, " ").replace(/^\s+|\s+$/g, "");
                                    var percent = lzw_encode(t).length / t.length;
                                    if (t.length > 1024 && percent < 0.35 || percent < 0.05) {
                                        // post compression filter - if text compresses by more than 70%, oneline it
                                        e[0].classList.add("spam");
                                        e[0].title = "Post compression filter triggered ("
                                        + (100 * (1 - percent)).toFixed(2) + "% reduction)";
                                    } else if (percent < 0.5) {
                                        e[0].title = "Post compression filter almost triggered ("
                                        + (100 * (1 - percent)).toFixed(2) + "% reduction)";
                                    }
                                } else {
                                    e[0].classList.add("spam");
                                    e[0].title = "Dupe";
                                    var el = e[0];
                                    while (el != null && !el.classList.contains("CommentContainer")) {
                                        el = el.parentElement;
                                    }
                                    if (el != null) {
                                        console.log(el);
                                        el.style.display = "none";
                                    } else {
                                        console.error("Unable to find CommentContainer for corresponding CommentBodyText");
                                    }
                                }
                            }
                        }
                        
                        // Add child nodes to the list to recursively check all the nodes in the document
                        if (e[0].hasChildNodes()) {
                            for (i = 0; i < e[0].childNodes.length; ++ i) {
                                if (e[0].childNodes[i].nodeType != e[0].ELEMENT_NODE || (t = e[0].childNodes[i].tagName) != "INPUT" && t != "TEXTAREA") {
                                    if (!e[0].childNodes[i].classList || !e[0].childNodes[i].classList.contains("ForumReplyToPostArea")) e.push(e[0].childNodes[i]);
                                }
                            }
                        }
                    }
                }
                
                var e = document.querySelectorAll("blockquote>div:only-child>blockquote:only-child");
                for (var i = 0; i < e.length; ++ i) with (e[i].parentNode.parentNode) {
                    style.margin = "0";
                    style.padding = "0";
                    style.border = "none";
                }
                
            } catch (e) {
                alert(e.name + ": " + e.message);
            }
        });
    } catch (e) {
        alert(e.name + ": " + e.message);
    }
    


  • @accalia said:

    if one is impatient with Remy's posts and wants to find all those html comments and the cornify script without looking through the source code (and going WTF more than once on the way)

    ...except the "source code" being referenced was, you know, [i]the fizzbuzz "source code" featured in the article itself[/i], not the HTML source...


  • FoxDev

    i'll grant you that you could take it that way. but i did literally mean the HTML source.

    @Morpheus said:

    Use the Source Luke. Use the Source



  • Is there a way to use these UserScript things in Firefox?





  • Wow, this is much worse than the SEXY-fy XSS from a week or two ago.



  • @accalia said:

    i'll grant you that you could take it that way. but i did literally mean the HTML source.

    Maybe you did, but I'm pretty sure @aliceif didn't mean the HTML source:
    @aliceif said:
    But I find myself incapable of understanding WTF the "source code" is supposed to mean.


  • FoxDev

    I have updated my OP to clarify what i meant by 'source code' due to some certain pendants that i shall not name


  • ♿ (Parody)

    @accalia said:

    pendants

    ...must....resist....


  • FoxDev

    why resist?

    bottling it up just hurts everyone when the bottle explodes.



  • That's a great reason to bottle it up!



  • I don't wear a small bottle as a pendant around my neck though. I do wear a small silver dragon.


  • FoxDev

    nice. I don't wear anything on my neck, but i do have a silver dragon that i wear in my hair when i want to be fancy.

    of course getting it back out at the end of the day is a B**** so usually it rests on top of my monitors staring accusingly at me.



  • I find my pendant gets caught up in my hair if I'm in a bad mood (since long-haired, yo) but that hasn't happened for a while.

    Dragons in hair... never seen that before.


  • FoxDev

    It's a custom piece. It's a chinese dragon that you can wind into your hair like a cross between a hairstick and a curler (bad description, it looks way cooler than that)

    if i remember i'll take a picture of it when i get home and post it somewhere.



  • That sounds pretty awesome actually.


  • FoxDev

    It does!

    i get the strangest looks when i wear it. Seeing people's reactions to it is quite fascinating.

    Filed under: With my love of social experimentation you would think i was a shrink or something


  • ♿ (Parody)

    @accalia said:

    It's a custom piece. It's a chinese dragon that you can wind into your hair like a cross between a hairstick and a curler (bad description, it looks way cooler than that)

    My wife has some hair thingies that sound similar in function. They're relatively plain, decoration-wise. Hair screws, apparently:


  • FoxDev

    that looks a lot like it actually. It's a single helix, and flattened, but yeah, same basic idea.

    of course it's become a lot harder to wear since i started keeping my hair short.


  • Discourse touched me in a no-no place

    Hmm, it's been a long time since I was that bored…



  • updated bookmarklet for the new look:

    javascript: void (function () { document.querySelector('.articleWrapper').innerHTML = document.querySelector('.articleWrapper').innerHTML.replace(/<!--​/g, "<span style='color: red'> (").replace(/-->/g, ") </span>"); document.querySelector('.articleWrapper span[onclick]').style.color = 'magenta'; }())

Log in to reply