Click or scroll down Circle me on Google+ Fork me on GitHub Follow me on Twitter Ask me on Stack Overflow Gild me on Reddit Code Ninja, Entrepreneur, Idiot ChalkHQ — consulting, prototyping, mentoring HighF.in — resolve innefficiencies in your startup's workflow DearDrum.org — online open-mic / creative space The Dirac Equation (click to WikiPedia) A maxim Sun Tzu references in his magnum opus The Art of War

If you know the enemy and know yourself, you need not fear the result of a hundred battles.
If you know yourself but not the enemy, for every victory gained you will also suffer a defeat.
If you know neither the enemy nor yourself, you will succumb in every battle.
Fork me on GitHub

Tags

actionscript ad-hoc networks Adobe AIR anonymous Apple array Browsing convert Debugger Error Facebook file permissions Flash Flex fonts function future Google Google Plus grid hackers html javascript logs loop network p2p php privacy regexp Security Server social ssl technology terminal time Twitter upgrade Web 2.0 Web 3.0 Web 4.0 Web 5.0 wordpress

Featured Posts

  • Javascript: Undefined parameters
  • The Web, A Look Forward
  • Let Postfix send mail through your Gmail Account – Snow Leopard
  • Archives

  • April 2013
  • December 2011
  • July 2011
  • June 2011
  • March 2011
  • February 2011
  • January 2011
  • November 2010
  • October 2010
  • September 2010
  • July 2010
  • May 2010
  • Categories

  • Code
  • Design
  • Opinion
  • Security
  • Tools
  • Uncategorized
  • Category: Uncategorized

    Flex/Actionscript 3.0 Strip HTML Tags Function

    I needed a function to strip out html tags from a text input, but still let me specify allowable tags.

    Instead of spending time figuring out the regular expressions needed to pull it off and becoming a better programmer, I figured why repeat work someone else has probably already done.. I mean I could be a busy man. Anyway I found this great function on Flexer.info [link]. But after trying it out I noticed that the one tag I really really wanted to be parsed out iframe wasn't. It seems because I had specified i as an allowable tag it was also accepting iframe.

    So with all due respect to Andrei, below is the revised function with the security hole patched.

    All I changed was near the bottom where it determines if it's an allowable tag or not the reg exp was

    <\/?" + tagsToKeep[j] + "[^<>]*?>

    which allowed any character to follow the allowed tag as long as it wasn't a nested tag, which included frame following i. This will also support self closing tags.

     
    // strips htmltags
    // @param html - string to parse
    // @param tags - tags to ignore
    public static function stripHtmlTags(html:String, tags:String = ""):String
    {
        var tagsToBeKept:Array = new Array();
        if (tags.length > 0)
            tagsToBeKept = tags.split(new RegExp("\\s*,\\s*"));
    
        var tagsToKeep:Array = new Array();
        for (var i:int = 0; i < tagsToBeKept.length; i++)
        {
            if (tagsToBeKept[i] != null && tagsToBeKept[i] != "")
                tagsToKeep.push(tagsToBeKept[i]);
        }
    
        var toBeRemoved:Array = new Array();
        var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g");
    
        var foundedStrings:Array = html.match(tagRegExp);
        for (i = 0; i < foundedStrings.length; i++)
        {
            var tagFlag:Boolean = false;
            if (tagsToKeep != null)
            {
                for (var j:int = 0; j < tagsToKeep.length; j++)
                {
                    var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + " ?/?>", "i");
                    var tmpStr:String = foundedStrings[i] as String;
                    if (tmpStr.search(tmpRegExp) != -1)
                        tagFlag = true;
                }
            }
            if (!tagFlag)
                toBeRemoved.push(foundedStrings[i]);
        }
        for (i = 0; i < toBeRemoved.length; i++)
        {
            var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g");
            var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g");
            html = html.replace(tmpRemRE, "");
        }
        return html;
    }

     

    I’m Feeling Lucky Custom Search

    In Firefox, when you type stuff into the main url bar (the "Awesome Bar") it tries to do a GoogleI'm Feeling Lucky search. So if you typed in wiki it would figure out you wanted Wikipedia and take you to Wikipedia.org, it would even take you to the localized version, and when it's in doubt it shows you a standard Google result.

    To get this in Chrome add a custom search engine. Use the following as the url.

    http://www.google.com/search?q=%s&btnI=Im+Feeling+Lucky

    If you make it the default, then any keywords you type into the url bar (the "Omni Bar") will run an I'm Feeling Lucky search. Or you can set the keyword to l. So to use the custom search you would type in l wiki.

     

    HTTPS/SSL/TLS Security Exploit Found – Affects Everyone

    A flaw was discovered in the tls renegotiation process where a 'man in the middle' could take over the connection in a number of ways and perform a number of exploits. Transferring login, credit card, and other important info using https:// is no longer considered secure. The 'man in the middle' could be bumming off your local wireless network, anywhere in between you and your ISP, your ISP and the destination, or on the destinations network. Secure Certificates from the likes of VeriSign can no longer be fully trusted until they find a fix, at which point you'll need to update all your software - browsers, email clients, twitter apps, smart phone firmware, as all the software manufacturers implement and roll out the new(not yet figured out or released) protocol.

    Luckily the vast majority of internet users are stupid and this won't affect activity on the internet a bit, even people that are reading or writing this post will still log into their email accounts and go about their online life relying on sheer improbability of them being exploited by this massive(read: catastrophic) security hole. Once again it's stupidity and recklessness that will keep the world turning cause as we all know if you stop and think about anything too long you'll just give up and go live in the forest like we were originally supposed to.

    If you're interested in a more technical description go here.

    If you're a programmer and you contribute to or write software which implements tls please disable renegotiation a.s.a.p. and push the update to all your users until a new version of the protocol is released.

    via Ars Technica

     

    Flex: Variables, Anonymous Functions, and For Loops

    I just ran into some weird behaviour involving a for loop, some variables, and a bunch ofanonymous functions. This is in Actionscript 3.0 using Flex SDK 3.4 and current Google Maps API(as of the date of this post&mdash I read somewhere they're rolling out a new version although it's not really relevant for this post)

    So below I have a function that loops through the xml result of an http service, for each item in the result it creates a marker on a map and gives that marker a click event. When you click on a given marker I want a window to pop up with the name and description of that location, so the following is the code you'd expect to write. For simplicity sake you can keep an eye on the i:int variable which will help clarify the issue.

     
    //trace(i) will always output total items in the xml result
    private function processResult(event:ResultEvent):void {
    
      var total:int = event.result.data.item.length;
    
      for (var i:int = 0; i<total; i++) {
        var item:Object = event.result.data.item[i];
        //this will create the marker object
        var marker = new Marker(new LatLng(item.lat, item.lng), new MarkerOptions({fillStyle: {color: 0xEE9C21}, radius: 7, tooltip: item.name}));
    
        marker.addEventListener(MapMouseEvent.CLICK, function():void {
          //this will open an info window when the marker is clicked
          map.openInfoWindow(map.getCenter(), new InfoWindowOptions({hasTail: true, tailHeight: 5, hasShadow: true, title:item.name, contentHTML:item.description}));
          trace(i);
        	});
      map.addOverlay(marker);
      }
    }

    Now what you'll find with the above code is that no matter which placemark you click on, they will all show the same name and description. Say that there are 5 items in the xml result, tracing i will output the number 5.

    If you're new to programming, yes i will be 0 during the for loop's first run. Yes having 5 items and starting at 0 means it should be 4 for the last run, but the value of i increments one last time to make the i<totalcondition false before it exits the loop, so essentially it uses the final value of i for all the placemarks which is 5.

    I can't see any reason why this should be happening other than language or framework immaturity.

    The solution; or I should say the easiest, quickest solution, is to create an external function for marker creation that is called by the for loop, which for clarity's sake will only contain the part that's required to explain the concept and make it work ie: adding an event listener to the marker, but in the real world should have all the code necessary for creating a marker - that way you'd have an independent marker creation function you could call from anywhere in the application. Below is the working code:

     
    //trace(i) will output the correct index depending on the placemark clicked
    private function processResult(event:ResultEvent):void {
    
      var total:int = event.result.data.item.length;
    
      for (var i:int = 0; i<total; i++) {
    
        var item:Object = event.result.data.item[i];
        var marker = new Marker(new LatLng(item.lat, item.lng), new MarkerOptions({fillStyle: {color: 0xEE9C21}, radius: 7, tooltip: item.name}));
    
        //call external function and pass variables to it
        placeMarkerAddClickEventListener(marker, item.name, item.description);
        map.addOverlay(marker);
      }
    }
    
    //external function
    private function placeMarkerAddClickEventListener(marker:Marker, name:String, description:String):void {
    
      marker.addEventListener(MapMouseEvent.CLICK, function():void {
    
        map.openInfoWindow(map.getCenter(), new InfoWindowOptions({hasTail: true, tailHeight: 5, hasShadow: true, title:name, contentHTML:description}));
        });
    }

     

    Disable Flash Debugger Error Messages

    If you have Adobe CS, Flex Builder, Flash Builder or otherwise use the Debuggerversion of Flash Player you quickly realize that a lot of sites out there don't bother with error handling in their apps and widgets.  This sucks because everywhere you go you get these error messages and all you can do is click them away and contact the developers, who if they cared would have dealt with the errors in the first place.

    You can easily disable these error messages and then just re-enable them when you're debugging something. So here's how to do that:

    1. Find or create a file called mm.cfg in the following folder:
      OS X: /Library/Application Support/Macromedia
      Win XP: C:\Documents and Settings\username
      Win Vista: C:\Users\username
      Linux: /home/username
    2. Add the following line to the file and save it:
      SuppressDebuggerExceptionDialogs=1
    3. That's it, to turn debugging back on change that value to 0

     

    WordPress Automatic Upgrade

    For a few versions now WordPress has let you automatically upgrade it and your plugins. Every time an update would come around I'd try figure out how to activate it and fail. As a last resort you can specify ftp/ftps details and have it upgrade that way, but who wants to setup an ftp server right?

    Anyway, it turns out that aside from setting file permissions like everyone tells you to do to setup the automatic upgrade feature, the actual missing piece of the pie was to give ownership of the entire wordpress directory to the owner of the apache process.

    So, step 1: open up terminal and ssh to your server(use your ip address instead of all those 9s)

    # ssh root@99.99.999.999

    # [password]

    step 2: Now you're running a remote session to your server, open top

    # top

    step 3: Expand the window and look for processes name httpd or apache2, chances are they're owned by the user www-data. Say you have wordpress installed in /var/www/, enter in:

    # chown -R www-data /var/www

    The above command changes the ownership of /var/www, which is a folder, recursively so it goes through and changes ownership of all the files and folders below it, and it's changing ownership to the user www-data.

    Now log into wordpress and try auto upgrade.

     

    Flex 3-RegExp: Find Urls In Text And Html

    There are a number of situations where you'd want to grab the urls from a block of text. For example you may be loading in some external or dynamic data and want to make the links clickable, or change their colour. Regular expressions are used in a multitude of languages; they define patterns that can be matched against a string, thus certain key characters used in defining a RegExp have to be escaped so they are interpreted as special characters like \d matches any digit. In Actionscript, you can define a RegExp by either wrapping it in double quotes "", or forward slashes//. In each case you would have to escape any characters that match the wrapping in addition to the characters that need to be escaped in the actual pattern. Further more Actionscript requires you to separate out the last part of the regular expression, called flags, and insert it as the second argument when defining a new RegExp object.

    Here's how you find a url in text or html:

    var str:String = new String('This is a url www.fightskillz.com, and this is another one: <a href="http://chalk-it-out.com">Chalk It Out</a>');
    var reg:RegExp = new RegExp("\\b(((https?)://)|(www.))([a-z0-9-_.&amp;=#/]+)", 'i');
    var result:Object = reg.exec(str);
    trace(result[0]);

    First off if you're new to Flex/Actionscript you have to copy and paste this into a function and the variables created will only be accessable within that function while it's running as they are created and destroyed as it runs. If you wanted more permanence you'd just define the variables outside the function.

    Now Let's break it down. The first \ is used as a character escape for Actionscript. In actionscript when defining a string within double quotes you'd escape a double that's part of the string like this "Look at this double quote \""\b searches for a word boundary ie: a whitespace, or the beginning or end of a string.The next part ((https?)://)|(www.))defines the first part of a 'word' that passes for a url. It's made up of two substrings, the first looks for http, the question mark deems the preceding character optional, so it'll match to https as well. It then looks to see if the protocol is followed by ://. The |character means OR, so if there is no protocol specified, it checks for (www.). Next we have [a-z0-9-_.&=#/] which is a list of characters a to z, 0 to 9, and various others commonly found in urls. This is followed by a + which instructs the pattern to match the preceding list of characters until it can't anymore. It can't anymore when it reaches whitespace, a single or double quote, brackets, or any other non-url character. Finally the RegExp flag i informs the pattern to be case insensitive.

    reg.exec(str); executes the pattern on the specified string and returns the results as an array. Since the example is only designed to match the first url it encounters and then stop, the array will only have one result. The method reg.exec(str) is interchangable withstr.match(reg)