Monday, October 17, 2011

Token Replacement inside DocX

Before I get into this.  YES you can do this same thing with some standard microsoft tools like excel and access.  There is even a PHP class already built for this.

Anyway...

So have you ever needed to work with "less than computer savvy" clients?  And maybe they need to have document templates for whatever reason.  Well normally when you generate a word document or PDF you have to get a PHP class to generate that, and code in the document. That way you can dynamically generate the document on the fly when you need to.

Well that would take you a long time to type up say.. 20 documents.  Wouldn't it be cool if you (or the client) could just create their own templates in word, and your system would understand that? AND be able to generate a document based on that template?

Well I wouldn't be writing this blog if the answer was "sorry we can't do that".

Opening the Docx


So whats the technique?  It turns out that docX files are just zip files.  You literally can rename docx to zip and unzip it.

You get the following files when you unzip


Well inside the word folder is a file called document.xml. That file is the actual content of your word doc. Which means you can replace the text right there.

Re-Creating the DocX
So now that you have edited these files, you need to make them into a docx again. Just zip it back up, and rename it docx. Done and done.

PHP can do this for us
So all of the things we just did, php can do for us. So that means we can build this into our systems.

Step 1) Create a temp folder to store the extracted contents of the docx file

All this code does is create the temp directory if it does not exist. If it already exists, clean it out. Refer to the youtube video for the full code, and to see what recursive_remove_directory does (if you haven't figured it out)

Step 2) make sure the directory path is safe for shell use
So were going to be executing linux commands using shell_exec, and you can't have spaces and other random things in the path. So we just need to escape that first.
Step 3) Unzip to the temp folder
This is just a shell command
Step 4) Replace tokens.
So now we get the contents of the document.xml file, use str_replace to replace our tokens, then save it back.
Step 5) Re-zip ONLY the files we need.
we are going to specify the files here, because mac os x likes to create random folders when it unzips from the command line...
And thats it!
Now we have programmatically token replaced a docx file.

Here is the full tutorial

Thursday, August 18, 2011

When you know you should give up

I needed to know how to play vimeo videos inside and iPhone App.  So I googled for "vimeo videos inside iPhone app"

I found the first stack overflowlink to
http://stackoverflow.com/questions/2503235/vimeo-videos-in-iphone-app

Which had the accepted answer of using some "tips and tricks" which was a link to
http://www.stacyconaway.com/bucket/JS-Vimeo-embed-code-with-notes.pdf

I read that PDF and the code looked really familiar.  So I went to the blog post that the PDF came from.
http://www.stacyconaway.com/blog/2010/vimeo-html5-embed/

And on it was:
Thanks to YouTube user “optikalefxx” for posting his solution for everyone.


So turns out... I wrote the solution a year ago. Haha.  Too bad it doesn't work anymore.


Thursday, August 4, 2011

Which E-Commerce Solution Works for Me?

One of the higher paying jobs that I come across is E-Commerce jobs.  That's because clients know that they need to spend more money to ensure they can collect theirs.

There are quite a few popular choices when it comes to online payments, here are the most common in my eyes.

1) Donate button
2) Selling 1 or 2 things
3) Selling a bunch of products
4) You're serious about selling a lot of products
5) Payments integrated into your website
6) Recurring payments

1) Donate Button
This payment option should cost you next to nothing. You just create a paypal account, go create a button, say its for donate, and bam paste some HTML code onto your page.  If someone charges you for this, tell them they should be ashamed.  Just take them out to dinner or something, this payment option is really simple to do.

2) Selling 1 or 2 things
When you just have less than 5 things to sell, you have basically 2 ways of going about this.  You can go the easy way and just create buttons like we did for the donate button.  Thats really easy, and you can just paste those into your site.  But lets say you want a shopping cart now that you have multiple items.  Well paypal gives you this really easy to use FREE api called "3rd party shopping cart" that lets the developer have a bit more customization.  To sell a product you just put this HTML on the page

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="seller@designerfotos.com">
<input type="hidden" name="item_name_1" value="Item Name 1">
<input type="hidden" name="amount_1" value="1.00">
<input type="hidden" name="item_name_2" value="Item Name 2">
<input type="hidden" name="amount_2" value="2.00">
<input type="submit" value="PayPal">
</form>

So you can sell any number of products in a shopping cart type way using this HTML.  You can even incorporate discounts by using discount_amount_cart and discount_rate_cart.  You can even discount individual items with discount_amount_x and discount_rate_x.  Where rate is a percentage and amount is a dollar amount off.

3) Selling a bunch of products
If your selling lots of products, more than 10 I would say, then you need a store.  An online store is a solution that allows you add products, edit them, save user information, view order details etc.  Its quite a full featured solution for managing an online store.  This option should not cost that much either, because as the developer you can install something FREE like OpenCart and then let your client add all the products.  Then you just charge for design work making it look better.  OpenCart is really a great store and it allows you have users checkout with paypal (free) or by taking credit cards ($30 a month)

4) Serious Online Store
While OpenCart is great, its not advanced. It doesn't do fraud store checkout, it doesn't integrate with UPS world ship, or USPS Dazzle (these are both shipping programs).  It also has a very primitive inventory control.  A paid / hosted online store like Volusion or Magento is a better solution.  They will give you support agents, and have a very fully functional store, that even integrates right with quickbooks.  Customers can pay by credit card, paypal, check, money order or smoke signal.  If you are buying one of these stores, it can cost 6 to 800 a month, and  you will need someone full time to manage CRM (customer reports), Products and orders.  This is the real deal.

5) Integrated Payments
Lets say you already have a bunch of products on your site, and you already love the way it looks.  Or say you need some super custom shopping cart, or even a affiliate payment program.  All of these tasks can be accomplished with an integrated solution.  This is where you start paying a lot.  These solutions require a programmer that really knows the paypal APIs well, and knows how to integrate Paypal payments pro and payments standard as well as express checkout.  This is the most fun type for me because its by far the most challenging.

6) Recurring Payments
This is also a fun one.  Sometimes you need to handle monthly payments or any kind of recurring payment really.  There are again 2 ways to go about this. You can do the "free" way and use the "3rd party shopping cart" to integrate this. Or use Paypal payments Pro ($30 a month) if you wanna take credit cards and have recurring fees. Here are the needed variables for the free way.

$_POST['business'] = "seller@yoursite.com";
$_POST['cmd'] = "_xclick-subscriptions";
$_POST['a3'] = 30.00;
$_POST['p3'] = "1";
$_POST['t3'] = "Y";
$_POST['src'] = "1";
$_POST['item_name'] = "Single User Yearly Subscription";
$_POST['item_number'] = 2;
$_POST['sra'] = "1";
$_POST['no_shipping'] = "1";
$_POST['no_note'] = "1";
$_POST['return'] = "http://come/back/after/complete;
$_POST['currency_code'] = "USD";
$_POST['lc'] = "US";
$_POST['bn'] = "PP-SubscriptionsBF";

This sets up a 1 year recurring payment of $30 a year.


So you can see there are many ways to accept payments on your site, and this is only a few of them.  There are many more ways included Mass pay, parallel payments, working directly with your bank and more!  If you want to make good money as a web developer, learn the paypal apis.

Thursday, July 14, 2011

I Love Regex

regex is awesome. Its powerful, its fun, and it can make you extremely efficient. There are 2 places where regex is most needed.

1) fixing code.
You've seen maybe 3 videos on my youtube channel about using regex with text wrangler.  I don't know about you, but I have to fix code sometimes.  And sometimes, it requires replacing some text a thousand times.  Or say you have a long list of stuff, and you wanna make it into a comma list.  That regex is simply

Find:
\r
Replace with:
,

So, it's quite often that I need to replace a bunch of stuff in some HTML or PHP, or even CSS and knowing regex makes this task very simple.  If you didn't know regex, you would either have to pay some kid to do the same task 1000 times, or you would have to waste your time doing it.  Or, if you didn't know how to use regex in your text editor, you'd have to write a script to do the replacement for you.  So get to know your text editor. This function is also called "grep".

2) Pattern Matching
This is pretty generic.  This can mean anything from page scraping, to dom crawling, to email syntax checking, to curse word validation.  It's all pattern matching.
There are 2 extremely useful regex you should know about.

1) match until character.  This is great for DOM crawling.  But it's also great for email addresses.  The regex is [^c]+  Where "c" is the character your are matching until.  So to match every div on the page, you would do div[^>]+  That would match <div however many times it was on your page. If you wanted the closing > you would just add it on.  div[^>]+>  ta da.

2) match until string.  This is extremely useful, and a lot of people never know about it. Lets say you have a div of class "hello" and inside maybe 20 divs down, is a class "world"  You can't use the "match until character" to find "world".  You would use this awesome regex.

hello(?:(?!world).)+

Complicated right?  yea, well just copy and paste it when you need to use it.  Lets explain.

  1. We start with hello. Pretty simple.

  2. Then we first use a negated lookahead.  (?!world).  Which basically says "match one time the string "world" NOT followed by anything. (which is the .)  So again, were matching 1 time, the word "world" that is NOT followed by anything.

  3. Then, we need to not just match 1 time. That would just give us 1 character. We need to match everything until we get there. Just like the "match until character" had the +, we need a + here as well.

  4. But you can't just add a +.  And you can't wrap the whole thing in square brackets like a normal regex.  So we need to wrap in parentheses so we can use the +  ((?!word).)+

  5. BUT, we have a problem that we just used parentheses, which are going to capture the result.  So we now need to NON CAPTURE those parentheses so they stay out of the way.
    (?:(?!world).)+

And that is the "match until string".

You could also use another regex instad of a string.  say we wanted to find hello world or hello planet.
(?:(?!world|planet).)+

Heres a video explaining this if I didn't do a good job writing it.

Tuesday, July 5, 2011

Source Code Release - Load After Scroll / ForeverScroll

The video



Also to note:
You could pass in a number into the load function and load different content, you don't always have to load the same thing over and over, that was just for the example.

<html>
<head>
 <style type="text/css">
  #flickr {
   height:600px;
   overflow-x:hidden;
   width:800px;
  }
  .flickr_results, .loading {
   padding:10px;
   border-radius:5px;
   background:#eee;
   color:#555;
   margin:10px;
   font-family:helvetica;
   font-size:11px;
   font-weight:bold;
  }
  .loading {
   background:#000;
   color:white;
  }
 </style>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script type="text/javascript">
  
  var loading = true;
  
  function loadFlickr() {
   var url = "http://api.flickr.com/services/rest/?&method=flickr.photosets.getPhotos&api_key=4ef2fe2affcdd6e13218f5ddd0e2500d&photoset_id=72157619415192530&format=json&jsoncallback=?";
   $.getJSON(url, function(data) {
    var photos = data.photoset.photo;
    $.each(photos, function(i,photo) {
     var title = photo.title;
     $("#flickr").append("<div class='flickr_results'>"+title+"</div>");
    });
    
    // once we've loaded
    // kill the loading stuff
    loading = false;
    $(".loading").remove();
    
   });
  }
  
  $(function() {
   
   // load initial photos
   loadFlickr();
   
   // scroll event of the main div
   $("#flickr").scroll(function() {
   
    // get the max and current scroll
    var curScroll = $(this)[0].scrollTop;
    var maxScroll = $(this)[0].scrollHeight - $(this).height();
    
    // are we at the bottom?
    if( (curScroll == maxScroll) && loading == false) {
    
     // when you start, set loading
     loading = true;
    
     // add the loading box
     $("#flickr").append("<div class='loading'>Loading...</div>");
     
     // scroll to the bottom of the div
      $(this)[0].scrollTop = $(this)[0].scrollHeight - $(this).height();
     
     // load more photos
     loadFlickr();
    } 
   });  
   
  });
 </script>
</head>
<body>
 <div id="flickr">
 
 </div>
</body>
</html>

Source Code Release - CSS3 Animation Menu

Here is the video



<html>
<head>
 <style type="text/css">
  body {
   background:#9cb4b3;
  }
  div.moving_arrow {
   width:640px;
   height:25px;
   margin:50px auto;
  }
  .moving_arrow ul {
   margin:0;
   padding:10px;
   border-radius:8px;
   height:inherit;
   width:inherit;
   background:-webkit-gradient(
    linear, 
    left top, 
    left bottom, 
    color-stop(0, #fff),
    color-stop(1, #e5e5e5)
   ) #e5e5e5;
   -webkit-box-shadow:0px 0px 6px #555;
  }
  .moving_arrow ul li {
   list-style:none;
   float:left;
   margin-right:11px;
  }
  .moving_arrow ul li a {
   display:block;
   float:left;
   padding:4px 8px 8px 8px;
   font-family:helvetica;
   text-shadow:0px 1px 1px white;
   color:#666;
   font-weight:700;
   text-decoration:none;
  }
  .moving_arrow li img {
   float:left;
   padding:4px 3px 8px 8px;
  }
  #arrow {
   width:12px;
   -webkit-transition:margin-left 400ms ease-out;
   margin-left:50px;
  }
  #arrow svg, #arrow polygon {
   width:12px;
  }
  #arrow.home {margin-left:54px;}
  #arrow.apps {margin-left:150px;}
  #arrow.blog {margin-left:233px;}
  #arrow.about {margin-left:339px;}
  #arrow.support {margin-left:457px;}
  #arrow.contact {margin-left:569px;}
  #arrow polygon {
   text-shadow:0px 1px 1px black;
   -webkit-box-shadow:0px 0px 6px black;
  }
  
 </style>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
 <script type="text/javascript">
  $(function() {
   $(".moving_arrow ul li a").mouseover(function() {
    $("#arrow").removeAttr("class").addClass($(this).attr("class"));
    return false;
   });
  });
 </script>
</head>
<body>
 <div class="moving_arrow">
  <ul>
   <li>
    <img src="icon.png"/>
    <a class="home" href="">Home</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="apps" href="">Apps</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="blog" href="">Blog</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="about" href="">About Us</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="support" href="">Support</a>
   </li>
   <li>
    <img src="icon.png"/>
    <a class="contact" href="">Contact</a>
   </li> 
  </ul>
  <div id="arrow">
   <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="12px" height="7px">
    <polygon id="arrow_thumb_shadow" points="0,0 6,7 12,0" fill="#333"/>
    <polygon id="arrow_thumb" points="0,0 6,6 12,0" fill="#e5e5e5"/>
   </svg>
  </div>
 </div>
</body>
</html>

Monday, June 20, 2011

How to Learn Web Programming

There are a lot of different ways to learn anything.  Reading,  listening, watching, doing.  In programming, I find the best combination of learning is watching then doing.  Some people really like to read, but I think when it comes to programming, reading is the wrong way to go.

Why video?
The cool thing about video is that you get to see and hear at the same time. And its in the tone at which the trainer wanted you to hear it.  So you also get their inflection and emphasis on certain parts.  This is why I chose to produce a bunch of videos and why you won't really see tutorials on this blog.  I think programming, even straight code, needs to be seen, visualized and explained. Sometimes just watching someone type something out is way more helpful then reading a final code block.

Errors will also occur on video.  And thats not a bad thing.  One thing I've had to work on in doing these videos is being able correct errors really quickly and explain what went wrong. Honestly some of the best learning you can get is from watching someone else make errors.  I used to stop the video and correct it, or re make the video because of the errors. But now I think it's even more valuable to let people watch me debug on the fly and figure out how to fix whatever the problem may be.

Why not programming books?
"Books suck. Watch videos."  That was going to be my tagline for square bracket. Catchy no?  While I don't think books suck, I do think they aren't ideal for learning to program.  For a short period of time they are good as references, but the internet is fast enough now where that is even becoming irrelevant.  See, printed books lose their relevance very quickly.  Programming languages get updated all the time.  I mean just 3 years ago it was all about web 2.0, 2 years ago was all about html5, and this year is all about CSS3 transformations.  Not only that, the syntax for this stuff is changing all the time.  Of course if you buy books on languages that are frozen then you will be safer.  But still, you can't see a piece of code, then see it work, and interact with it at the same time.  You have to read the code example, type it in, then try it.  It's too many steps and leaves you too disconnected from the learning.

So what about online books or written tutorials?
So written tutorials online are good when coupled with other media.  That is if your able to provide an interactive example along with the tutorial you are halfway there.  So the person learning can get that hands on access to play with the code.  I think the perfect example of this is w3schools.com  I went to this site probably 10,000 times while learning CSS. I could never remember everything when I was 15.  But they provide examples of every single CSS class and selector.  That really helped.  That kind of "try it now" is a perfect way to learn.

What is most important?
Just do it™.  If you are trying to learn something, go with video first to get a good idea of what is going on, then dive right into code. That is THE best way to learn.


My learning process generally goes:
1) look for a "how to" on youtube.
2) look for some sample code online.
3) Launch the example and see if it works
4) try to change something about that example and not break it
5) try to apply new modifications specific for a project

And by then you should pretty much understand how it works, how it breaks, and how you can use it in your application.