welcome.h

welcome to home page of kubilay erdogan -a freelancer php, iOS and .net developer. he hates postbacks.
Sample Apple Push Notification PHP Script

Sample Apple Push Notification PHP Script

This is an old script that I used to use for sending notifications. I don’t remember the source, on the other hand, it has been modified a couple of times already.

Even though I could manage to send notifications with this script, the Apple server was rejecting the connection after the amount reaches more than 50. It was usually getting cut off around 70. So it needs to get some management for not sending in a loop, like threading or whatever.

<?php

// set time limit to zero in order to avoid timeout
set_time_limit(0);

// charset header for output
header('content-type: text/html; charset: utf-8');

// this is the pass phrase you defined when creating the key
$passphrase = 'my_secret_pass';

// you can post a variable to this string or edit the message here
if (!isset($_POST['msg'])) {
$_POST['msg'] = "Notification message here!";
}

// tr_to_utf function needed to fix the Turkish characters
$message = tr_to_utf($_POST['msg']);

// load your device ids to an array
$deviceIds = array(
'lh142lk3h1o2141p2y412d3yp1234y1p4y1d3j4u12p43131p4y1d3j4u12p4313',
'y1p4y1d3j4u12p43131p4y1d3j4u12p4313lh142lk3h1o2141p2y412d3yp1234'
);

// this is where you can customize your notification
$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}';

$result = 'Start' . '<br />';

////////////////////////////////////////////////////////////////////////////////
// start to create connection
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyAppGenerated.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

echo count($deviceIds) . ' devices will receive notifications.<br />';

foreach ($deviceIds as $item) {
	// wait for some time
	sleep(1);
	
	// Open a connection to the APNS server
	$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);

	if (!$fp) {
		exit("Failed to connect: $err $errstr" . '<br />');
	} else {
		echo 'Apple service is online. ' . '<br />';
	}

	// Build the binary notification
	$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
	
	// Send it to the server
	$result = fwrite($fp, $msg, strlen($msg));
	
	if (!$result) {
		echo 'Undelivered message count: ' . $item . '<br />';
	} else {
		echo 'Delivered message count: ' . $item . '<br />';
	}

	if ($fp) {
		fclose($fp);
		echo 'The connection has been closed by the client' . '<br />';
	}
}

echo count($deviceIds) . ' devices have received notifications.<br />';

// function for fixing Turkish characters
function tr_to_utf($text) {
	$text = trim($text);
	$search = array('Ü', 'Þ', 'Ð', 'Ç', 'Ý', 'Ö', 'ü', 'þ', 'ð', 'ç', 'ý', 'ö');
	$replace = array('Ãœ', 'Åž', '&#286;ž', 'Ç', 'Ä°', 'Ö', 'ü', 'ÅŸ', 'ÄŸ', 'ç', 'ı', 'ö');
	$new_text = str_replace($search, $replace, $text);
	return $new_text;
}

// set time limit back to a normal value
set_time_limit(30);
?>
March 17, 2014 0 comments
Node.js -3 | Reading user input from the command line

Node.js -3 | Reading user input from the command line

Readline module, which comes with the Node.js core reads user input so that you can use it as an interaction.

In this example, the user will tell how many glasses of water he/she drinks each day and we’ll say if it’s healthy enough or not.

In the script.js file, require the module like:

var rl = require("readline");

Create the prompts variable:

var prompts = rl.createInterface(process.stdin, process.stdout);

Request user input with a question:

prompts.question("How many glass of water do you drink each day?", function (glasses) {
	var message = "";
	if (glasses > 5) {
		message = "Great! Water is the key of a healthy life.";
	} else {
		message = "Are you drinking just " + glasses + " glass of water? You should drink at least " + (6 - glasses) + " more.";
	}
	console.log(message);
	process.exit();
});

Output will be like:

> node script.js
> How many glass of water do you drink each day?
> 5
> Are you drinking just 5 glass of water? You should drink at least 1 more.
> node script.js
> How many glass of water do you drink each day?
> 7
> Great! Water is the key of a healthy life.
March 10, 2014 0 comments
Node.js -2 | Modules: Custom Module and Sample Usage of Markdown Module

Node.js -2 | Modules: Custom Module and Sample Usage of Markdown Module

In this post, I’ll share some code about how to use modules in Node.js. I will use a custom module (user-defined) and a public module (Markdown module). The code samples are form Lynda.com’s Node.js lessons.

——

Defining a local module (A module that returns Fibonacci numbers)

1- In the root of Node.js application, navigate to node_modules folder and then create a dir for your module:

> cd node_modules
> mkdir data_module

2- Create module file:

> nano fibonacci.js

And edit its content like this:

exports.data = [1,1,2,3,4,8,13,21];

Save and exit the editor.

3- In app root folder, create the main file:

> cd ..
> nano script.js

And edit like this:

// './' prefix tells that the module is local, not global
var sequence = require("./fibonacci");
console.log(sequence.data);

Note: “Local modules are useful for when you want to separate your data from your code.”

——

Markdown module simple usage

First, create a Node.js app with Markdown module dependency enabled and install these dependencies as I talked about here.

In your script.js file:

var parser = require("node-markdown");
var html = parser.Markdown("This is a **markdown** text.");
console.log(html);
March 10, 2014 0 comments
Node.js -1 | Initialize a Node.js project with dependencies

Node.js -1 | Initialize a Node.js project with dependencies

Not so long ago I’ve started to study lessons about Node.js. There’s no need to praise or to talk about it or why I want to learn it, it just excites me as a new platform and I intend to keep studying unless I don’t feel like it’s not worth it -which I doubt.

Here I want to share my Node.js notes regularly, from very basic to the complex(hopefully).

———

Running Node.js scripts

Download and install from:


http://nodejs.org/

To build (run) a Node.js script:

> node file.js

———

Initializing a node app and build it with dependencies

1- Initialize:

> npm init

2- After initialization, package.json contains project information. You can add “dependencies” to this file like:

"dependencies": {
	"node-markdown": "0.1.0"
}

If you want to require latest version of a dependency module:

"node-markdown": "*"

3- Install these dependencies:

> npm install

———

Some other useful stuff about managing the app

Update these dependencies to latest versions:

> npm update

Update node.js global libraries:

> npm update -g

Remove an installed library:

# remove from "dependencies" object in package.json, then:
> npm prune

Search through node.js modules available for free:

> npm search 
# better not to use it without grep or it may take quite long time
> npm search | grep markdown
# or find from http://npmjs.org

Tail changes of a file and execute it automatically on console after each change:

# -g installs as global
> sudo npm install node-dev -g
> node-dev script.js

———

No “Hello, world!” yet. These are just basics that we’ll probably do quite seldom.

March 10, 2014 0 comments
Selecting Grouped Row Count When Using MySQL GROUP BY Column

Selecting Grouped Row Count When Using MySQL GROUP BY Column

You may have been using subqueries to get how many rows were grouped when using MySQL’s GROUP BY function. There’s a little trick that helps to get this number without using subqueries, more clean and faster (when the amount of rows get higher).

Let’s assume we have a table contain folks from different cities. Like this:

folk_name   |   city_name
---------------------------
evren       |   ohio
steve       |   ohio
cem         |   weston
don         |   sunderland
ritchie     |   weston
ian         |   hounslow
alican      |   ohio

When we want to get only city names (distinct) from this table, we may group the data by city_name column like this:

SELECT f.* FROM `folks` f GROUP BY f.`city_name`

And the result would be:

folk_name   |   city_name
---------------------------
ian         |   hounslow
evren       |   ohio
don         |   sunderland
cem         |   weston

The expected behaviour of GROUP BY is to select first rows so other folks from same cities do not appear. It also orders by the GROUP BY column (ascending).

Let’s say we want to get how many folks exist in each city by grouping by. First thing comes to mind could be using a subquery like this:

SELECT f1.*, (SELECT COUNT(f2.`folk_name`) FROM `folks` f2 WHERE f2.`city_name` = f1.`city_name`) AS `folk_count` FROM `folks` f1 GROUP BY `city_name`

And the result would be:

folk_name   |   city_name   |   folk_count
-------------------------------------------
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Let’s admit, subqueries are messy. They make the query more complicated to read and also are question marks on performance.

How about selecting number 1 (one) for each row and sum it up on grouping by?

Doing something like this:

SELECT f.*,SUM(1) AS `folk_count` FROM `folks` f GROUP BY f.`city_name`

Would return:

folk_name   |   city_name   |   folk_count
-------------------------------------------
ian         |   hounslow    |   1
evren       |   ohio        |   3
don         |   sunderland  |   1
cem         |   weston      |   2

Nicely done.

February 17, 2014 0 comments
DateTime Ticks With Objective-C

DateTime Ticks With Objective-C

If you need to generate unique strings for every case, the concept of DateTime.Ticks is probably the best solution for you. It represents the count of seconds since the oldest DateTime object available.

However, DateTime.Ticks usage comes from .NET platform and it is that easy in .NET, not in Objective-C.

To generate a ticks number in Objective-C, you need to do the following:

  1. Create an NSDate (01.01.0001), I know, rocking.
  2. Calculate the ticks between this oldest date and [NSDate date] (which means now).
  3. Turn that double variable to an integer. Well, long integer. Or… long long integer. (True story).

Here’s how I did it:

// Create the date formatter
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd"];

// Create the oldest day possible
NSDate *ticksDate = [dateFormat dateFromString:@"00010101"];

// Get ticks difference between now and 01.01.0001 in double    
double ticksDouble = [[NSDate date] timeIntervalSinceDate:ticksDate];

// Turn it to a long long int
long long int ticks = llround(ticksDouble);

// Test it
NSLog(@"%lli",ticks);
February 14, 2014 0 comments
How to Install Git 1.8.x || Upgrade Git to 1.8.x

How to Install Git 1.8.x || Upgrade Git to 1.8.x

hins2

You don’t get surprised when you see that your CentOS, Ubuntu or another server already has Git installed. However, the default Git version that comes with the OS bundle is usually v1.7.1 and this might be a problem when you want to install applications which require higher Git versions(For example, Gitlab).

This article contains the steps that I followed while installing(or upgrading to) Git 1.8.3.4 to a CentOS 6.4 server.

First of all, make sure if you have git installed:

which git

This has to return a value like “/usr/local/bin/git”. If it doesn’t, than you don’t have Git installed on your machine.

If it does return a path, than you better know which version, by using this command:

git --version

The result should be like: “git version 1.7.1″. If it returns the number equals or higher than the version you want to install, well, you got lucky. The day is over for you.

OK, let’s begin with a new installation.

1. Go to /tmp folder:

cd /tmp

(Those who have older version of Git installed may go to step 3.)

2. Install default version of Git and maker for installing git:

yum -y install git perl-ExtUtils-MakeMaker

3. Clone git repo to your /tmp folder:

git clone git://github.com/git/git.git

4. Get inside of the repo and checkout your favorite version. I chose v1.8.3.4, you may choose something else.

cd /tmp/git/
git checkout v1.8.3.4

5. Continue preparing installation:

autoconf
./configure --prefix=/usr/local

IMPORTANT: You might have got an error like “-bash: ./configure: Permission denied”. If you haven’t, continue with step 7. If you have, no need to worry, we’ll fix it by using these commands:
6. Fix “Permission denied” error if exist

mount -o remount,exec,suid /tmp
mount -o remount,exec,suid /var/tmp

7. Do it

make && make install

8. Cleanup

rm -rf /tmp/git/

9. Verify your installation:

which git

(Should return Git path like “/usr/local/bin/git”)

10. Verify your version

git --version

(Should return your version, like: “git version 1.8.3.4″)

You may find most of the steps above in various websites, however it really took me a while to find out how to fix the permission error which I declared in step 6.

Fair enough, let’s go make some fork!

September 24, 2013 0 comments
html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

html2canvas- Take Screenshot of Web Page and Save It to Server (Javascript and PHP)

FeedBack is important. Usually, end-users struggle to clarify their problems. And you might be unreachable for a phone call or remote connection.

That causes a huge need of visualization. First solution that appears in mind is to capture the current screen of user.

However, when I tried to implement that, it wasn’t so easy as I expected. Some old ways offer ActiveX but it seems too outdated. Since there’s a bridge needed between client side and server, JS libraries are the best way.

There’s a great library, html2canvas. It is told to be reverse-engineered version of Google Plus’ way of taking screenshots.

When I first discovered this library, it took me a while to use for simplest implementation. I just wanted to visualize a div element. However, there was no single page to tell the whole path to follow, thus I had to combine various sources.

Here’s how you can easily use for taking a screenshot of a div:

1- Import libraries
There are 3 libraries to import:

  • jquery.js
  • html2canvas.js
  • jquery.plugin.html2canvas.js

You can download html2canvas and html2canvas jQuery plugin from this link.
Note: The source link contains html2canvas v0.40. I recommend you to check for a newer version and use it instead from official html2canvas site.

I have used jquery.min.js v1.7.1 but you can try other versions. For this jQuery library, use this link.
Here’s first lines of code:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<!-- -->

2- Create your div
In my code, I used html2canvas for a div. You can use the whole body tag instead, it’s up to you.
Attach a div element to the page with a certain id:

<div id="target">
<!-- Render your page inside of this div. -->
</div>

3- Create a button and a hidden form
This part is important. In order to save the image to server, we need to pass captured image data with a form field.
In 4th step, you’ll see JavaScript code that writes the image data to hidden field and posts the form.

<input type="submit" value="Take Screenshot Of Div" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
    <input type="hidden" name="img_val" id="img_val" value="" />
</form>

4- JavaScript Code

    function capture() {
        $('#target').html2canvas({
            onrendered: function (canvas) {
                //Set hidden field's value to image data (base-64 string)
                $('#img_val').val(canvas.toDataURL("image/png"));
                //Submit the form manually
                document.getElementById("myForm").submit();
            }
        });
    }

5- Use the posted values
Here I used a form to post the value. You can use Ajax calls or whatever. I have a PHP file, save.php. In this file, we will both show the picture and save it to the server.

//save.php code

//Show the image
echo '<img src="'.$_POST['img_val'].'" />';

//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);

6- Enjoy your day
So that’s pretty much it. Click here for a live demo or download the codes from Github repository page.

7- Notes

* This tutorial uses html2canvas v0.4.0 – 30.1.2013. It has a new release, v0.4.1 – 7.9.2013, can be downloaded from here. Though avaliability of newer versions haven’t been tested with the code above.

* Some people have declared that they had issues with checkbox/radiobutton states on the captured image. Stu has shared his code to capture these elements with their states. I haven’t tried by myself but people who face problem about this may get some opinion from his comment.

March 1, 2013 75 comments
Javascript: Export HTML Table to Excel With Custom File Name

Javascript: Export HTML Table to Excel With Custom File Name

Web browser wars hurt developers’ hearts. It is mostly about CSS, sometimes about JavaScript, HTML etc…

Thus I know how it feels when you expect something to get done easily appears a lot more harder than you expected.

Code below is tested only with Chrome (24+). It is making these processes:

  • Gets the HTML code of your table inside your div element.
  • Replaces the spaces in the code with correct syntax for Excel (otherwise spaces will be removed in your Excel sheet).
  • Generates a specific file name (for minutes) in order to avoid overriding old files and to supply archiving by date values.
  • And lastly and most importantly, saving the file with a custom file name.

Here’s my combination of codes (from different SO questions or tutorials) if you want to save HTML table to client computer using JavaScript code.

$(document).ready(function() {
	$("#btnExport").click(function(e) {
		//getting values of current time for generating the file name
		var dt = new Date();
		var day = dt.getDate();
		var month = dt.getMonth() + 1;
		var year = dt.getFullYear();
		var hour = dt.getHours();
		var mins = dt.getMinutes();
		var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
		//creating a temporary HTML link element (they support setting file names)
		var a = document.createElement('a');
		//getting data from our div that contains the HTML table
		var data_type = 'data:application/vnd.ms-excel';
		var table_div = document.getElementById('dvData');
		var table_html = table_div.outerHTML.replace(/ /g, '%20');
		a.href = data_type + ', ' + table_html;
		//setting the file name
		a.download = 'exported_table_' + postfix + '.xls';
		//triggering the function
		a.click();
		//just in case, prevent default behaviour
		e.preventDefault();
	});
});
February 3, 2013 49 comments
Generate DateTime Value in PHP for Using in MySQL Command

Generate DateTime Value in PHP for Using in MySQL Command

When we work with date and/or time values in MySQL, it’s always easy to use built-in MySQL functions such as NOW(), DATE_ADD(), TIMESTAMP() etc… Now imagine you have to pass date/time values to MySQL from PHP variables. First time I tried that, it didn’t work out so easy for me.

Yes, if you simply take one column value and use it again, you have no problem. But here’s an example that you take date and time from MySQL column, add 1 seconds to that value and use it in query again:

//Here's just stuff in order to get a datetime value from MySQL DB.
$query = "SELECT TOP 1 `date` FROM `table`";
$result = mysql_query($query, $db_link);
$date_time_val = "";
if ($result) {
    while($row = mysql_fetch_assoc($result)) {
        //Here we get the value.
        $date_time_val = $row["date"];
    }
}

//Now we add one second to this value and use it again.
//First, use it for generating a DateTime variable from PHP library.
$time = new DateTime($date_time_val);
//If you need current time in PHP, you can use this:
//$time = new DateTime(date("Y-m-d H:i:s"));

//Add one second,
$time->modify("+1 seconds");

//You can not use it as it is
//You need to convert to a string in MySQL datetime format.
$time_string = $time->format("Y-m-d H:i:s");

//Now you're free to use in your query
$query_new = "SELECT * FROM `table` WHERE `date` = '".$time_string."' ";
December 23, 2012 0 comments