Timezones: The client, The server and The database

To Start out, I want to say why I’m writing this post. I have just recently been struggling with server to database interactions with date time and I had no idea why. Thought was “maybe I’m using the wrong time stamp”, “maybe I’m not setting the time to Midnight morning” then i realized “maybe my server is at a different timezone than my database”. And this was very very true.

SQL at base makes their timezones based on the servers timezone. That means if you’re in New York, running a server, it will be based off New York. If London, it will be London. This is ok, so long as your server is on the same timezone, and unfortunately for me, it doesn’t seem like it.  Wordpress has a few functions to work with such as current_time() and the seemingly undocumented option time_zone. Except its useless when it is empty, basically telling me UTC (the universal time for computers generally). PHP also returned my UTC which also doesn’t help me. In all who I hang with the most (My clean cut but simple friend wordpress and my old disorganized but extremely intelligent friend PHP) just don’t see at the same level as mySQL. So what do I do? Well, change mySQLs timezone and change my servers timezone to ensure everyone sees the same.

$wpdb->query("SET time_zone = '+0:00'");
date_default_timezone_set('UTC');

Based off this post and the php manual,  I’ve found this is the ultimate solution to my problem. I was having such problems with timezones being in different places and wordpress not helping too much that I’ve just given up and decided the proper solution is just to set everything in UTC.

This isn’t what I necessarilly want to do though. The reason for this is I’m forcing the user to experience my application in UTC. Why is this a problem? Well, user experience. However, if I’m going to change the website dependent on the users time zone, I would need to find the persons position in the world to find out what time zone they are in. And generally users don’t just give away their time zones. So how am I suppose to do this?

I make the theme have all datetime oriented aspects in my theme return in UTC and when I want to shift the date, either through xslt or jquery, I change the date based on what I recieve from javascript. It isn’t pretty. But I can make it pretty. And functionality is more important than in this case

 

Whens the Right Time?: The Transfer from Local to Production

I’ve been working on my clockin plugin for some time, and have nearly completed most of the graphs and the basic functionality, but theres a couple of things that I still need to do. So It leaves to question, when is the right time?

graphs

Well, I think it I believe, at this point in time, its project based. What are absolute necessities? For example, Even though I have the graph bases, I still need to grab the github trees and append those to the graph. I need to add each post type, when its updated to “recent posts” so they are easily accessible. There are time difference bugs where a month will show the same times for a different day then a weekday. As well as Timezone problems, allowing for projects to have appended Bug fixes and Enhancements. Showing on author page, loading all previous data from all my various locations (I’ve been working a ton, and I want to show it off)

In essence, Top Shelfing User Experience.

Then theres the error checking which will allow me to post this to the plugins like; When github Authorization for a user is taken away. Caching the pictures to promote speed. When a wordpress user is deleted, what do I do? Making sure that the dates are SEO compatible as well as graphs. When a readme is blank, not displaying one.

In essence very important things that I am not worried about right now since they don’t necessarilly all apply to me

But as I look at my fixes and enhancements, I start realizing how intertwined the plugin and theme enhancements are. So Can I truelly submit this as a plugin? Or is this just neat idea for my own personal setup? As I continue, only more enhancements arise, so when does it end? Or do I see it as a continuous project? Is wordpress the best place for this? Could I be doing it better? These are important questions I think everyone may have, and I believe working hard from working smart.

MVC as applied to wordpess and a moment of silence for XSL

So, finishing up the backbones of the Clockin Plugin, I’ve found the next steps are to see it as I had it on my old site. With a multitude of charts and such. However, the display for the clockin plugin isn’t static. In fact its quite dynamic. The entire idea of a “clock in” is its date as such it will be changing almost daily. This is ok and unfortunate for me in that it was what bogged down my load times before. I gotta do what I got to do.

Now there are a few things I’m going to be doing

  1. Add a specific ui thats just for clock_in_project
  2. Add a specific ui thats just for users, and allow them to be searchable
  3. Start Moving away from the 2014 base (while attempting to keep a lot of the great parts)
  4. Create my old charts
  5. Cache days that are not current days for easy access

But my to do this isn’t why I’m writing this blog post, the reason I’m writing this is to explain what a model view controller is and what wordpress offers.

The best way I can explain the model view controller is this:

  • Model is an object in your database
  • View is how you’ll be viewing the Model
  • Controller is directing what Model to choose and what view to choose for it
    -This can be based off: User Request, Admin Request, App Request and Default

With wordpress, our MVC is simple: we have post types, we have a theme, we have a url.
Whenever a user makes a request at the top thereurl, what we’re actually doing is making a request.
Now from my experience there are two main forms of requests, archive, singles. Archives will show you a list of items based off a query. Singles may also be based off a query, the difference is that you get full frontal information instead of a bunch of items.

Why does this matter?

Well for the clock in post type, we’re going to have to do some very special things. And Unfortunately as is the default it renders as if its just a regular post. We’re going to change that.

Its something very simple, where we can base it off of file structure. But I’d prefer not

switch (get_post_type( get_the_ID() )){
case "type_a": break;
case "type_b": break;
default: echo "ah, the good old default";
}

As simple as this we can go through and pick our view. we can also mix and match and a bunch of funky things.

One thing I want to point out is a sad sad truth about MVC, XSLT. XSLT was designed to make HTML the view component of choice. Where we would take in our model, see what we had and apply the appropriate templates. Important to note, it was all (well kinda) XML. It gave people the conceptual graduation platform to move up to. So why didn’t it work out?

XSLT has a major flaw, most Databases don’t return XML. If your database isn’t returning XML, your going to have to Transform it into XML. If you’re transforming, your wasting time. Especially when you can just use the raw data retrieved to fill in the dots. Another Major flow is that despite how awesome Xpath is, there isn’t a direct correlation from url concepts o XPath concepts.

What people need to understand is the url is the command, just as XPath is a command. And most people go from HTML, CSS, File system into PHP and Javascript where either they sink or swim. XSL and Xpath had the opportunity to make that bridge easier. But they died as other CMS’s popped up and took over. Will we see them again? One day maybe, I certainly try to use it when i can. But I highly highly doubt it

ClockIn: Preparing the Shortcode

Last time I basically shutdown all possibilities of using google calander, but thats fine, SQL is an efficient alternative and it should be no issue.

CREATE TABLE Clock_ins (
 time datetime DEFAULT NOW() NOT NULL,
 duration int DEFAULT 0 NOT NULL,
 user tinytext NOT NULL,
 project tinytext NOT NULL
 );

Now, theres 3 main UIs I need to focus on

  1. Clock In, Clock out-This will be in the sidebar, or really where ever someone wants to put it
  2. Project Chooser-When we begin to clock in, we need to be able to choose from our existing repositories
  3. Clock In Viewer (User and Project mode)-Whats a database if we can’t view it? Here we give sexy charts for people to look at to make them feel comfortable (We’ll worry about this later

So For Clock In, Clock out…. We’re going to want to add in a some WordPress Shortcode tags so that we can place it anywhere we want Our shortcode is going to be called [clock_in] and theres three major things we’ll be needing from the user -Their user id -their github id -The project they’re going to clockin to

function clock_in_setup( $atts, $content=null) {
 $current_user = wp_get_current_user();
 $message;
 $href;
 $type = "ajax";

 if ( !($current_user instanceof WP_User) ){
 $message = "Please Login First";
 $href = wp_login_url( get_permalink() );
 $type="self";
 }else if(($meta = get_user_meta($current_user->ID, "clockin")) == array()){
 $json = json_decode(file_get_contents(plugin_dir_path( __FILE__ )."/secret.json"));
 $cid = $json->cid;
 $redirect_uri = plugins_url("auth.php", __FILE__);
 $state = "clock-in_plugin".$current_user->ID;

 $href = "https://github.com/login/oauth/authorize";
 $href .= "?client_id=".$cid;
 $href .= "&redirect_uri=".$redirect_uri;
 $href .= "&state=".$state;

 $message = "Authorize our plugin";
 $type="blank";
 }else if(isset($atts["cur_project"])){
 $nonce = wp_create_nonce("clock_in");
 $href = admin_url('admin-ajax.php?action=clock_in&proj='.$atts["curproject"].'&nonce='.$nonce);
 $message = "Clock in!";
 }else if($meta["clocked"] == true){
 $nonce = wp_create_nonce("clock_in");
 $href = admin_url('admin-ajax.php?action=clock_out&nonce='.$nonce);
 $message = "Clock out!";
 }else{
 $href = plugins_url("clocked.php", __FILE__)."?action=in";
 $nonce = wp_create_nonce("clock_in");
ob_start();
?>
 Choose a project to Clock Into
 <div class="clockin-wrap">
 <a style="display:inline-block;height:144px;width:64px;background-color:#000;"></a>
 <div class="clockin_projects" style="display:inline-block;height:144px;width:144px;">
 </div>
 <a style="display:inline-block;height:144px;width:64px;background-color:#000;">
 </a>
 </div>
<?php
 wp_enqueue_script ('clock_in_proj');
 wp_localize_script('clock_in_proj', 'clock_in_vars', array("github_user"=>$meta["github"], "clockin_uri"=>admin_url('admin-ajax.php?action=clock_in&&nonce='.$nonce)));
 return ob_get_clean();
 }
 ob_start();
 ?>
 <div class="clockin-wrap">
 <a class="clockin_anchor" href=<?php echo $href; echo ($type != "ajax")?" target=".$type.'"':''; ?> ><?php echo $message ?></a>
 </div>
 <?php 
 if($type == "ajax"){
 wp_enqueue_script ('clock_in');
 }
 return ob_get_clean();
}

What I’m doing here essentially is creating a link where ever the shortcode is. The Link will either;  direct to login, direct to github authorization, if its a project page, allow person to clock in, display logged persons projects to clock in or show clockout link. Next we need to make sure we authenticate with github, then display our projects properly

Google API + WordPress: A Problem, an Inconvienience and a Killer

I started off planning on using Google Calanders to store my clockin information. I was doing this for one main reason: Its important that how I store the information is standardized in case I attempt to export my plugin to node.js or another platform. But there is a problem I ran into that I realized may turn very annoying or worse.

Refresh Tokens are not unlimited

this will create an awkward situation once the refresh tokens run out and the website owner is forced to login and authorize again

And as a minor inconvienience

Google Authorization Doesn’t allow Get parameters in the url

Perhaps this is a problem on WordPress side more than googles in the way they setup their admin. Essentially I’m forced to create a plugin url that is independent from the direct flow. Making either the user Leave the admin interface conpletely or doing it through a popup. Then Instead of storing it in WordPress Options, we’d be storing it in a seperated SQL table to avoid loading wp-load.php. These are definitely managable, though not entirely preferable. If I’m using a content management system, I’d rather feel as though I can do everything in a very sexy and clean manner. Rather than go through hoops.

nonetheless I will continue to make the plugin as is simply for experience sake. Though I recognize this is definitely not final version

Update: What Killed using Google API as a web service was the fact that I am forced to use give my webserver an key file. This will not make future installations happy for random people. As a Result, I’m going to drop google calander from the design spec and move onto something else. This isn’t necessarilly Google Calanders Fault, but rather a design philosophy Flaw. I wanted to Use Google Calanders as My database, but I didn’t want to have to make installation a hassle. as a result, I gotta move on.

I’ll go with what is important

  1. Start DateTime
  2. Duration in seconds
  3. Github User
  4. Github Project

Clockin WordPress Integration: Million ways to get it, choose one. pt1

So at this point we can….
1) Retrieve a Github info
2) Retrieve google calender info

But one thing we have yet to do is provide a place where we can actually clock in and clock out. Now we can do this in a variety of ways….

  • Custom Post Types to define Projects and Users
    -they would literally just be place holders to avoid storing tons of duplicant data
    -Would be based off any user that enters our website and allows our app to access their github profile

    • Pros
      -We don’t need javascript to display data
      -Pretty URLs will be enforced
      -Good for SEO
      -Can Be Placed in a Plugin
    • Cons
      -Whats the point of creating a reference?
  • Query Based Multiple Page Service
    -We would create a page that is based off a template we created
    -In the template we would get the queries and give the appropiate data back

    • Pros
      -clean and neat
      -Can make it SEO Freindly
    • Cons
      -Would have to define an archive and various link tags to make it SEO freindly
      -Ugly Urls
  • Single Page Service
    -Using Ajax, we would do everything right from the one page

    • Pros
      -Clean and Neat
      -Pretty Url… Well theres only one….
      -Can be stored in a plugin
      -Nothing is stored
    • Cons
      -Requires Javascript
      -Will need to deal with the data in the browser
      -No SEO

So here’s our choices, I’ll assume you assumed which I’m going with… And if you didn’t assume, I’ll give you a hint “Type Post Custom”. WordPress is wonderful in that it gives you pretty URLS, it gives you proper SEO in a variety of ways, makes your URLs beautful and on top of that you can avoid alot of the struggles you would enter into with your own Content Management System,  such as creating a proper PHP class to interact with sql.

We really want to make sure this is a plugin also to allow ourselves some breathing room in terms of installation.

So Lets begin by creating our plugin

Now Things we will have to include are….

  1.  Creating a Custom Post Type for Users and associating it to a User
  2. Creating a Custom Post Type for Projects
  3.  Giving people the opportunity to choose their Calender
  4.  Auto Load on new sites to old calanders

So lets prepare in the Init, we’re going to leave out the auto load for now

add_action( 'init', 'initialize_clockin' );
function initialize_clockin() {
 register_post_type( 'clockin_dev',
  array(
   'labels' =&gt; array(
    'name' =&gt; __( 'Developers' ),
    'singular_name' =&gt; __( 'Developer' )
   ),
   'description' =&gt; 'The user object associated with the wordpress user. stores the guthub username as well',
   'public' =&gt; true,
   'has_archive' =&gt; true,
   'show_ui' =&gt; false,
   'show_in_menu' =&gt; false,
   'supports' =&gt; false
  )
 );
 register_post_type( 'clockin_project',
  array(
   'labels' =&gt; array(
   'name' =&gt; __( 'Github Projects' ),
   'singular_name' =&gt; __( 'Github Project' )
),
   'description' =&gt; 'Associated to Github Project',
   'public' =&gt; true,
   'has_archive' =&gt; true,
   'show_in_menu' =&gt; false,
   'supports' =&gt; false
  )
 );
 add_option("Calander ID", null);
}

Now lets create our admin page

This is the code I came up with. I preferred the object oriented approach so that I can store it in a different file

<?php
class clock_in_admin {
 public $options;
public function __construct(){
 add_action( 'admin_menu', array( $this, 'add_to_menu' ) );
 add_action( 'admin_init', array( $this, 'page_init' ) );
 }
 public function add_to_menu(){
 add_options_page( "Clock In Settings", "Clockin", "manage_options", "clock-in-admin", array($this, "admin_page"));
 }
 public function admin_page(){
 $this->options = get_option( 'clock-in' );
?>
 <div class="wrap">
 <?php screen_icon(); ?>
 <h2>Clock In Settings</h2>
 <form method="post" action="options.php"> 
 <?php 
settings_fields( 'clock_in_fields' );
 do_settings_sections( 'clock-in-admin' );
 ?>
<?php submit_button(); ?>
 </form>
 </div>
<?php
 }
 public function page_init(){
 register_setting('clock_in_fields', 'clock-in', array( $this, 'sanitize' ) );
 add_settings_section('clock-in-cal', 'Google Calender Setting', array( $this, 'print_section_info' ),'clock-in-admin');
 add_settings_field('calender-id','Calander ID',array( $this, 'calander_id_input' ),'clock-in-admin','clock-in-cal');
 }
 public function print_section_info()
 {
 echo 'Enter your settings below:';
 }
 public function sanitize( $input ){
 if( isset( $input['calender-id'] ) ){
 //need to check if the calender exists and we can't view and edit it
 //if we can't edit it, we need to ask for permission
 $this->options['calender-id'] = $input['calender-id'];
 }
return $this->options;
 }
 public function calander_id_input()
 { ?>
 <input id='calender-id' name='clock-in[calender-id]' size='40' type='text' value='<?php echo $this->options['calender-id'] ?>' />
<?php
 }
}
?>

 

A ReEntry to WordPress

I build wordpress for clients mostly, but had big plans for my own website. However, after a month of work and a lot of research I’ve come to understand what it really means to… create a content management system. There are many things to keep in mind, access to your database, providing a nice looking interface. Making things simple yet also allowing complete customization. The User Object. Which should be static methods, which should be instance? There is a lot too it, and I finally had decided that getting my website up and running is far more important than spending years on a website that (no offense to websites) is not very high on my priority list.

What I will say though is
1) CMS’ are meant to be easy to install, easy to begin and easy to use
-Wordpress is absolutely adorable compared to what I had been working on so hard for most of my workday.
2) CMS’s data are meant to be transportable
-Now wordpress isn’t necessarilly transportable, however you can definitely export your data as a solid XML file and due to its popularity importable as well
-for my own work, its definitely obvious I won’t be accessing the data quite so soon. Exporting to XML is the easy part, importing is a completely seperate beast
3) If your going to make a user interface make you can use it again
-for me I wanted to use XSL badly, and I still do. But the complexity in automation turned an interesting idea into a beast of its own. I’ll talk about it later when I get back into it. However, the important parts isn’t the XSL but rather the HTML. css and javascript
4) Routing is one if not the most important part of a CMS
-User Permissions are based off what is asked for
-Automation is very very important when dealing with an unknown amount of objects with unknown methods
-These are two things that held me back the most

Now I can’t say I want to use wordpress, but I definitely prefer it currently over slaving away for hours inorder to give myself more hurdles. Having the requirements change, introducing new technology mid project, these are things I’ll have to deal regardless. However, to me, finishing something is far more important than making it perfect.