Wednesday, October 31, 2012

I felt inspired to go back to my animation roots for an evening.

When I heard that Disney is reacquiring the Star Wars Franchise I felt inspired to edit the Imperial March to Steamboat Wilie.  Enjoy.
http://www.youtube.com/watch?v=xdqH85LSuGE

Wednesday, October 24, 2012

Web Page Update

Updated the Fractured Nations page.  I now have a timeline till go live.
www.fracturednations.com

Tuesday, October 16, 2012

E-mail attachments with php

      So the boss wanted to get a bunch of stats out of the database on a daily basis.  Our server guy has been doing it for her, and he complains that it takes time, which it does.  And he does not pull all the data she wants because some of it needs to be cleaned before it will display nicely.  So I figured it would be better done with a php script set to execute in a daily CRON.  I got put to this because she really wanted  the data that was dirty.  I could see my way threw the project but I had to figure out one or two things.  The main being how do you sent an email with an attachment with code.  So the next few posts will be addressing e-mailing with code, and data cleaning.


Monday, September 17, 2012

Weird Dream Last Night

So my wife and I have been looking at house plans with the intent of building one day.  And I have been scripting a lot.  I don't know exactly what triggered it but I had a dream we were building the house and I was laying out the floor with CSS and Javascript.  I made it self cleaning.  To bad it can't really be done this way.

<div id="kitchenFloor" class="Pergo Mahogany WideStrips" onwalk="selfClean()"></div>

function selfClean()
{
     var floor = house.getElementById("kitchenFloor");
     if(floor.mud == true)
     {
          //remove Mud
          floor.mud = false;
     }
}

Tuesday, September 11, 2012

HTML form element class object in PHP

Form Elements as easy as

$elem = new FormElement("yourElement", "Hello World Element");
echo $elem->HTML();

This Will print
--------------------------
<div class=''>Hello World Element</div>
<input id="yourElement" name="yourElement" type="text" form="form" onblur="Validate('yourElement')"/>
<div name='err' class='error'></div>
--------------------------
The last div named 'err' can be used to display errors from the validation.


<?php

/**
 * Description of FormElement
 * Form Element HTML Object
 * @author Joseph Tveter
 *
 * $name        is the name and id of the form element.
 * $cmd         is the HTML tag
 * $label       is the Label the User will see for the field the default is that it will not be there.
 * $pos         is the position of the label.  The default is "top", but it will also accept "right", "left", and "bottom"
 * $formName    is the name of the form the element is attached to. The default is "form"
 * $type        is the type of input tag it is. The default is "text"
 * $onblur      is the javascript function called onblur. default will call the function called "Validate" with the name of the field.  false will not include this field.
 * $val         is the value the tag has or will return.  The default is ""
 * $req         is weather to make the field required or not. The default is false
 * $disabled    is weather to make the field disabled or not. The default is false
 * $size        is the size of the input field. The default is ""
 * $maxLength   is the Maximum Length of the input field. The default is ""
 * $fullclass   is the class assigned to the div wrapper around the label and form element. The default is ""
 * $titleClass  is the class assigned to the label. The default is ""
 * $elementClass is the class of the form element.  The default is ""
 */
class FormElement extends HTML
{
    public function __construct($name, $label = "", $cmd = "input", $pos = "top", $formName = "form", $type = "text", $onblur = "default", $val = "", $req = false, $disabled = false, $size = "", $maxLength = "", $elementClass = "", $fullclass = "", $titleClass = "")
    {
        parent::__construct("div");
        if($fullclass != "")
        {
            parent::addValue("class", $fullclass);
        }
     
        $input = new HTML($cmd);
        $input->addValue("id", $name);
        $input->addValue("name", $name);
        $input->addValue("type", $type);
        $input->addValue("form", $formName);
     
        if($onblur != "default")
        {
            if($onblur != false)
            {
                $input->addValue("onblur", $onblur);
            }
        }
        else
        {
            $input->addValue("onblur", "Validate('$name')");
        }
     
        if($val != "")
        {
            $input->addValue('value', $val);
        }
     
        if($disabled == true)
        {
            $input->addValue('disabled', "disabled");
        }
     
        if($req == true)
        {
            $input->addValue("required", "required");
        }
     
        if($size != "")
        {
            $input->addValue("size", $size);
        }
     
        if($maxLength != "")
        {
            $input->addValue("maxlength", $maxLength);
        }
     
        if($elementClass != "")
        {
            $input->addValue("class", $elementClass);
        }
     
     
        if($label != "")
        {
            switch($pos)
            {
                case "":
                    parent::addChild("<div class='$titleClass'>$label</div>");
                    parent::addChild($input->HTML());
                    parent::addChild("<div name='err' class='error'></div>");
                break;
         
                case "top":      
                    parent::addChild("<div class='$titleClass'>$label</div>");
                    parent::addChild($input->HTML());
                    parent::addChild("<div name='err' class='error'></div>");
                break;
         
                case "bottom":
                    parent::addChild($input->HTML());
                    parent::addChild("<div class='$titleClass'>$label</div>");
                    parent::addChild("<div name='err' class='error'></div>");
                break;
         
                case "right":
                    $input->addChild("<span class='$titleClass'>$label</span>");
                    parent::addChild($input->HTML());
                    parent::addChild("<div name='err' class='error'></div>");
                break;
         
                case "left":
                    parent::addChild("<label for='$name' class='$titleClass'>$label</label>");
                    parent::addChild($input->HTML());
                    parent::addChild("<div name='err' class='error'></div>");
                break;
            }
        }
        else
        {
            parent::addChild($input->HTML());
        }
    }
}

?>

HTML Form Class Object


I got your form right here.

$form = new form("myform");
echo $form->HTML();

This will print
----------------------
<form id="myform" name="myform" action="index.php" method="post">
</form>
---------------------


<?php
/**
 * Description of form
 * HTML form Object
 * @author Joseph Tveter
 */
class form extends HTML
{
    public function __construct($name = "form", $action = "index.php", $method = "post")
    {
        parent::__construct("form");
        parent::addValue("id", $name);
        parent::addValue("name", $name);
        parent::addValue("action", $action);
        parent::addValue("method", $method);
    }
}

?>

Update to my Object Oriented HTML class


I removed most of the Actionscript like functions because it can not be changed after the server has sent it to the client.  I am testing some HTML class extensions and will post them soon.


<?php

/**
 * Description of HTML
 *  -- OO-HTML 1.1 --
 * - Removed some methods that it didnt make sense to have.
 * - Removed array key name requirement on addChild
 *
 * @author Joseph Tveter
 *
 * Class to allow HTML to be eaisly written in native php
 * It will also work for building xml
 *
 * The $cmd string is the tag command such as a,div,html
 *
 * The $vals array holds a list of value commands for the html tag
 *
 * The $children array holds a list of children of the tag.  They will be placed in decending order, so a tag at [1] will come before a tag at [2]
 *
 * To print the string call HTML();
 * example:
 *
 * $mydiv = new HTML('div');
 * $mydiv->addValue('name', 'mydiv');
 * $mydiv->addChild('Hello World');
 * echo $mydiv->HTML();
 *
 * This will print.
 * --------------------
 * <div name='mydiv'>
 * Hello World
 * </div>
 * ----------------------
 *
 */
class HTML
{  
    public $cmd = "";
    public $vals = array();
    public $children = array();
   
    public function __construct($cmd)
    {
        $this->cmd = $cmd;
    }
   
    public function HTML()
    {
        $r = "";
        $s = false;
        $singleArr = array('input', 'hr', 'meta', 'link');
       
        foreach($singleArr as $i)
        {
            if($this->cmd == $i)
            {
                $s = true;
            }
        }
       
        //values
        $val = "";
        foreach($this->vals as $k => $v)
        {
            $val = $val." ".$k."=\"$v\"";
        }
       
        //Children
        $child = "";
        foreach($this->children as $v)
        {
            $child = $child.$v."\n";
        }
       
        //Build and return the HTML string
        if($s == false)
        {
            $r = "<".$this->cmd.$val.">\n$child</".$this->cmd.">";
        }
        else
        {
            $r = "<".$this->cmd.$val."/>\n".$child;
        }
        return $r;
    }
   
    public function addChild($child)
    {
        $this->children[count($this->children) + 1] = $child;
    }
   
    public function addValue($cmd, $val)
    {
        $this->vals[$cmd] = $val;
    }
}

?>

Wednesday, August 29, 2012

Client side data storage

Lots of ways to do it, but I am favoring HTML 5's sessionStorage. Its clean and does not stick around on peoples machines. I hate it when stuff sticks to my machine so I try not to let it stick on others. sessionStorage will expire when the browser closes. Here are a few ways to set it in javascript.

sessionStorage.someKey = 'someValue';

 or if you prefer...

 sessionStorage.setItem('someKey', 'someValue');

 And to retrieve it.

sessionStorage.getItem('someKey')
 or
sessionStorage.someKey

You can display the info with the Document Object Model like so...

document.getElementById("myvalue").innerHTML = sessionStorage.someKey;

You should get this in your HTML

<div id="myvalue">someValue</div>

Monday, August 27, 2012

Linux

I have decided that I am favoring CentOS over Ubuntu. I used Ubuntu for a long while as a desktop, and it was great for that. I use CentOS at work on our servers. When I installed the server addition of Ubuntu I found that in order to be able to SSH to the server to update files I had to jump threw a lot of hoops, like moving the web directory to a home folder and then pointing Apache to the folder to let it write to it. Yes its more secure that way. But what I really want right now is ease of use. Perhaps I will use Ubuntu if I decide to store Credit Cards, when I finally get my game up and running, but beyond that I think its a bit overkill and cumbersome for my personal sites.

Wednesday, August 22, 2012

PHP Email crazyness

Today I built a simple email class to send out emails.


/**
 * Description of Email Class
 *
 * @author Joseph Tveter
 */
class Email
{
    public function __construct()
    {}
   
    public function Email($to, $subject, $message, $from = 'admin@yoursite.com', $cc = '', $bcc = '', $MIME = 'MIME-Version: 1.0', $Content = 'Content-type: text/html; charset=iso-8859-1', $Reply = "")
    {
            $headers  = $MIME . "\r\n";
            $headers .= $Content . "\r\n";
            $headers .= 'From: '. $from . "\r\n";
            if($cc != "")
            {
                $headers .= 'Cc: '. $cc . "\r\n";
            }
            if($bcc != "")
            {
                $headers .= 'Bcc: '. $bcc . "\r\n";
            }
            if($Reply != "")
            {
                $headers .= 'Reply-To: '. $Reply . "\r\n";
            }
           
        if (mail($to, $subject, $message, $headers) == false)
        {
            //send email on fail
            $s = "Email Failed to ".$to;
            $m = $s.":"."\r\n".$message;
            $h  = $MIME . "\r\n";
            $h .= $Content . "\r\n";
            $h .= 'From:'. '$from' . "\r\n";
            mail('you@yoursite.com', $s, $m, $h);
        }
    }
}

Tuesday, August 21, 2012

Multiple CSS Classes in HTML Tag

This was a major help for me.  If your a  control freak like me you want to keep your CSS from getting out of control. I found its good to keep the layout and text formatting CSS seperate.  Lots of ways to do it. Here is a few.

You can separate out the layout and formatting by putting some info in the id, and some in the Class.

#mytag
{
    position:absolute;
    width:15px;
    top:0px;
    left:30px;
    padding-top: 6px;
    padding-left:3px;
}

.MyDiv
{


    color: #000000;
    text-decoration: underline;
    font-weight: bold;


}

<div id="mytag" class="MyDiv">Bla Bla Bla</div>


But whats really cool is that you can put multiple classes in one tag to keep your CSS more reusable.

<div id="mytag" class=" Bold Underline BlackText">Bla Bla Bla</div>

.Bold
{
    font-weight: bold;
}

.Underline
{
    text-decoration: underline;
}

.BlackText
{
     color: #000000;
}

Monday, August 20, 2012

PHP Quotes and HTML

For those who don't know, I was one of you till about a month ago, you can have PHP write double quotes into your html.  You just need a slash in front of each " to keep it part of the string.

$mydiv = "<div class=\"myclass\"></div>";
echo $mydiv;
//<div class="myclass"></div>

This is really handy if you need to pass stuff to a javascript function.

$PassThis = "Passed";
$btn = "<button class='btn' onclick=\"MyFun('$PassThis')\">My Button</button>";

Friday, August 17, 2012

To all database developers

To all database developers:

Please when your building your database please make sure that your structures makes some sort of sense.  Please assign primary keys.  And make sure that they mean something.  Remember that one to many relationships are the goal.  And Please Please Please do not make stupid tables that you have to query 3 fields to get any meaningful data out of it. If for no other reason to preserve the sanity of the developers that come after you.

Thursday, August 16, 2012

Cleaning phone number data from database

I have been working with a database where the phone number data is very dirty.  People have been imputing numbers any old way so I wrote this to clean the data as it comes into the form. It strips out anything that is not a number and removes the '1' at the beginning of the number.
<?php

    private function CleanPhone($ph)
    {
        //break the string into an array
        $phSplit = str_split($ph);
        //Initialize the return value
        $nph = "";
        //Check each item in the array
        foreach($phSplit as $k => $n)
        {
            //if its numeric add it to the return value
            if(is_numeric ($n))
            {
                //if the first number is not a 1 add it to the retun value
                if($k == '0')
                {
                    if($n != '1')
                    {
                        $nph = $nph.$n;
                    }
                }
                else
                {
                    $nph = $nph.$n;
                }
            }
        }
        return $nph;
    }


$nph = CleanPhone($phoneFromDatabase)


$ph1code = substr($nph,0,3);
$ph1pre = substr($nph,3,3);
$ph1suf = substr($nph,6,4);
                   
$ph = "
<div>
          <div>Phone Number</div>
          (<input id='ph1code' name='ph1code' size='3' maxlength='3' type='text' value='$ph1code' form=' Form' />)
           <input id='ph1pre' name='ph1pre' size='3' maxlength='3' type='text' value='$ph1pre' form=' Form' /> -
            <input id='ph1suf' name='ph1suf' size='4' maxlength='4' type='text' value='$ph1suf' form='Form' />
             </div>
                    ";
?>

And here's how it fits on the site.

<html>
<body>

<?php echo $ph; ?>
<form name='Form' action='index.php' method='post'></form>
</body>
</html>

Thursday, August 9, 2012

Website

I configured apache and the web server last night. So I now have a functional dedicated web server for Fractured Nations.  Fractured Nations will be the company name I will publish any games I build under.  The first I am working on will be called Star Fighter.  Which will be a simple multiplayer space game where you control a ship and shoot your friends.  The site is under construction, I have done little more then lay out the basic css. The buttons do nothing, but the foundation is in place and we will see how fast it goes on an hour every evening.

http://www.fracturednations.com

Tuesday, August 7, 2012

Javascript Ajax POST to a html id function


I found and modified this a few months back so I could POST information into a page's div id's.
////////////////////////////////////
///////////AJAX/////////////
/////////////////////////////////////
//url is the target page
//tar is the div target the post is going to
//val is the array being sent. It must be in this format val = "key='value'&key2='value2'";
function PostToDiv(url, tar, val)
{
    var xmlhttp;
    var c = 0;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
   
    xmlhttp.open("POST", url, true);
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
           
            document.getElementById(tar).innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(val);
}

Return value of Javascript cookies

If you want to read the cookie you wrote.


//returns the value of a cookie by cookie name

function ReadCookie(name)
{
    var c = {};
    var val = "";
    var cookies = document.cookie.split(";");

    //unpack the cookies
    for(var key in cookies)
    {
        //split to array parts
        var s = cookies[key].split("=");
       
        var k = s[0];
        var v = s[1];
       
        c[k] = v;
    }
   
    if(c[name] != 'undefined')
    {
        val = c[name];
    }
    return val;
}

Javascript Cookies

I ran across this a while back.  If you want to hold info in cookies here is a good javascript function to do so.

function setCookie(c_name,value)
{
    var ex=new Date();
    ex.setHours(ex.getHours()+14);
    var c_value=escape(value) + ((ex==null) ? "" : "; expires="+ex.toUTCString());
    document.cookie=c_name + "=" + c_value;
}


Sunday, August 5, 2012

Send POST or GET data to a page from javascript

I found and modified this. It is a javascript function that dynamically creates a form and sends the data via POST or GET to the page.  Enjoy.

The params variable needs you to send data in a key value array object. 

pass = { postThis: 'Posted', andThis: 'as well' };
post_to_url('index.php', pass, 'post');


function post_to_url(path, params, method)
            {
                method = method || "post";

                var form = document.createElement("form");

                form.setAttribute("method", method);
                form.setAttribute("action", path);

                for(var key in params) {
                    var hiddenField = document.createElement("input");
                    hiddenField.setAttribute("type", "hidden");
                    hiddenField.setAttribute("id", key);
                    hiddenField.setAttribute("name", key);
                    hiddenField.setAttribute("value", params[key]);

                    form.appendChild(hiddenField);
                }
                document.body.appendChild(form);
                form.submit();
            }


<?php
echo $_POST['postThis'];  //Posted
echo $_POST['andThis'];  //as well
?>

Saturday, August 4, 2012

Its Saturday so I get to work on my game a bit.  Its crazy how many programs I have open.  It took me forever to figure out all the software needed to build and run a game so I will provide a list of software needed to do so, to save another poor soul from searching forever.

Server Software to run a game
- Web Server ( I run Apache since its free httpd.apache.org/)
- Database Software (I run MYSQL because it is also free www.mysql.com/)
- PHP or ASP for client server communication on the web page(I have been favoring PHP lately)
- Game Server Daemon (I have been trying out Electroserver 5 for its Actionscript interface and the Unity Support in case I go that way.)


Development Software (you don't need all this but I have gotten comfortable with these tools)
- Flash (for Image Object development)
- Flex Builder (for client scripting, layout and publication)
- Netbeans (for server scripting for PHP and Java)
 
- Unity or another game engine can take the place of Flash and Flex and I have thought of using it if I ever go 3d.  
 


 



Friday, August 3, 2012

I thought its about time I started a blog.  The main reason is I need somewhere to keep track of my code notes, and typing it out helps me remember better.  If you do happen by,  feel free to use any code you find.

I have been scripting a lot of PHP and HTML lately and have been wanting the Object Oriented Functions within PHP to be available for the HTML I have been writing so I came up with this.


<?php

/**
 * Description of HTML
 *  -- OO-HTML --
 * @author Joseph Tveter
 *
 * Class to allow HTML to be eaisly written in native php
 * It will also work for building xml
 *
 * The $cmd string is the tag command such as a,div,html
 *
 * The $vals array holds a list of value commands for the html tag
 *
 * The $children array holds a list of children of the tag.  They will be placed in decending order, so a tag at [1] will come before a tag at [2]
 *
 * To print the string call HTML();
 * example:
 *
 * $mydiv = new HTML('div');
 * $mydiv->addValue('name', 'mydiv');
 * $mydiv->addChild('Hello World', '1');
 * echo $mydiv->HTML();
 *
 * <div name='mydiv'>
 * Hello World
 * </div>
 *
 *
 * I added some functions to make it a bit more like actionscript but you can also manipulate the tag arrays directly.
 *
 */
class HTML
{  
    public $cmd = "";
    public $vals = array();
    public $children = array();
   
    public function __construct($cmd)
    {
        $this->cmd = $cmd;
    }
   
    public function HTML()
    {
        $r = "";
       
        //values
        $val = "";
        foreach($this->vals as $k => $v)
        {
            $val = $val." ".$k."=\"$v\"";
        }
       
        //Children
        $child = "";
        foreach($this->children as $v)
        {
            $child = $child.$v."\n";
        }
       
        //Build and return the HTML string
        $r = "<".$this->cmd.$val.">\n$child</".$this->cmd.">";
        return $r;
    }
   
    public function addChild($child, $num)
    {
        $this->children[$num] = $child;
    }
   
    public function removeChild($num)
    {
        unset($this->children[$num]);
    }
   
    public function addValue($cmd, $val)
    {
        $this->vals[$cmd] = $val;
    }
   
    public function removeValue($cmd)
    {
        unset($this->vals[$cmd]);
    }
}

?>