GGshow reloaded GGshow reloaded

January 4, 2014

2014 – A new beginning

Yes I know I know, this site was missing for several months. Losing visitors/readers, site pagerank dropped to zero, pages totally been removed from Google index, this is definitely not what I wanted to see.

Blog comments flooded with spam, web hosting plan (with 1TB monthly bandwidth limit) been suspended due to “overuse”, I’ve been tied up with work, couldn’t squeeze in some time for fixing this issue, until I was required to use my year end leave.

Not mentioning what the reason, I’ve decided to migrate the blog from b2evolution (b2evo) to WordPress (self hosted), I’ll share the migration script later, migrate from shared hosting service to Google App Engine (GAE). I’ve deployed WordPress multisite up there. Look! on the cloud ^^

This is just a beginning, a new beginning. There are still enhancements required, many things to be learned, and hopefully more to be shared too.

Over Quota

Last but not least, a belated new year greeting, Happy 2014… Happy 2013A for those who avoiding inauspicious number “4”, Happy 2013S for those who believe suffix S means something better although it is the same, happy new year for all 🙂

Filed under: Logs — Tags: , , , , , , , , , , — GG @ 5:24 am

April 11, 2016

RPi RF Transmitter & Radio Controlled Sockets

Playing with my new toy – Pi-mote Control starter kit with 2 sockets.

Sample code – turn on all plugs for 5 seconds.

import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(17,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
GPIO.setup(27,GPIO.OUT)
GPIO.setup(24,GPIO.OUT)
GPIO.setup(25,GPIO.OUT)

GPIO.output(17,True)
GPIO.output(22,True)
GPIO.output(23,False)
GPIO.output(27,True)
sleep(0.1)
GPIO.output(25,True)
sleep(0.25)
GPIO.output(25,False)

sleep(5)

GPIO.output(17,True)
GPIO.output(22,True)
GPIO.output(23,False)
GPIO.output(27,False)
sleep(0.1)
GPIO.output(25,True)
sleep(0.25)
GPIO.output(25,False)

Complicated? There is an easier way, by using Energenie library.

Installing Energenie library

For Python 3

sudo apt-get install python3-pip
sudo pip-3.2 install energenie

For Python 2

sudo apt-get install python-pip
sudo pip install energenie

* pip is a package management system used to install and manage software packages written in Python.

Sample code – turn on all plugs for 5 seconds

from energenie import switch_on, switch_off
from time import sleep
switch_on()
sleep(5)
switch_off()

It is much easier now, doesn’t it?

Updated: 11/9/2016
To control each switch separately, hold down the green button on one switch for 10-15 seconds, send channel 1 on command, hold down the green button on the other switch for 10-15 seconds, send channel 2 on command.
Now I can switch on/off the plug separately.

from energenie import switch_on, switch_off
from time import sleep
switch_on(1)
sleep(3);
switch_off(1)
sleep(3);
switch_on(2)
sleep(3);
switch_off(2)

Now I’ll be able to automatically turn on my radio every morning to wake me up, or remotely turn on my rice cooker before I arrive at home 😉

Reference
Controlling electrical sockets with Energenie Pi-mote – Raspberry Pi
Energenie Documentation
Energenie Python library source code

February 27, 2016

RPi camera

Enabling camera on your RPi

  • sudo raspi-config
    

Terminal commands

  • To take a picture
    raspistill -o filename.jpg
    
  • To play a recorded h264 video
    omxplayer filename.h264
    
  • To record a slow motion video (10 seconds, resolution 640×480 pixels, 90 frames per second)
    raspivid -w 640 -h 480 -fps 90 -t 10000 -o filename.h264

Installing Python API for RPi camera

  • sudo apt-get install python-picamera python3-picamera python-rpi.gpio
    

Python code samples

  • Preview and capture a photo
    import time
    import picamera
    with picamera.PiCamera() as camera:
        camera.start_preview()
        time.sleep(10)
        camera.capture('filename.jpg')
        camera.stop_preview()
    
  • Capturing multiple photos
    import time
    import picamera
    with picamera.PiCamera() as camera:
        i = 0
        while True:
            camera.start_preview()
            time.sleep(1)
            camera.capture(str(i)+(".jpg"))
            i += 1
            time.sleep(5)
    
  • Capturing photo when push switch pressed
    * connect a push switch to GPIO2 & GND
    * use current timestamp as filename
    * save JPG when push switch pressed

    from time import gmtime, strftime, sleep
    import picamera
    import RPI.GPIO as GPIO
    GPIO.setmode(GPIO.BCM)
    button=2
    GPIO.setup(button,GPIO.IN,pull_up_down=PIO.PUD_UP)
    while True:
        with picamera.PiCamera() as camera:
            camera.resolution = 1920,1080
            GPIO.wait_for_edge(button, GPIO.FALLING)
            camera.start_preview()
            sleep(2)
            camera.capture(strftime("%Y%m%d%H%M%S",gmtime())+'.jpg')
            camera.stop_preview()
    

    A photo posted by @le_g_end on

    #raspberrypi #camera & #pushswitch

    A video posted by @le_g_end on

  • Recording a 10 seconds video
    from time import sleep
    import picamera
    with picamera.PiCamera() as camera:
        camera.start_recording('filename.h264')
        sleep(10)
        camera.stop_recording()
    
    
  • Video recording and playback
    import os
    while True:
        os.system("raspivid -w 640 -h 480 -fps 90 -t 10000 -o filename.h264")
        os.system("omxplayer filename.h264")
    

Reference

June 6, 2015

When Pi open Windows

Microsoft released Windows 10 IoT Core Insider Preview today.

Download Windows 10 IoT Core Insider Preview with support for Raspberry Pi 2
Unzip Windows_IoT_Core_RPI2_BUILD.zip
Run Command Prompt as Administrator, navigate to the unzipped folder.

Insert SD card into card reader.
Install image file (flash.ffu) to your SD card.

dism.exe /Apply-Image /ImageFile:flash.ffu /ApplyDrive:\\.\PhysicalDriveN /SkipPlatformCheck

If your SD card is disk number 3, use /ApplyDrive:\\.\PhysicalDrive3
To find the disk number of your SD card:

diskpart
list disk
exit

Remove your SD card with Safely Remove Hardware. Your SD card is now ready to boot Windows 10. Insert SD card into your Pi, Connect HDMI monitor, network cable, power supply. Boot Windows 10 IoT Core Insider Preview.

Windows 10 IoT Core Insider Preview

Reference
PowerShell documentation

Filed under: Raspberry Pi,Windows — Tags: , , — GG @ 6:24 am

May 3, 2015

60″ TV on the ceiling

To use your chromecast without a television? All you need is a mini LED projector with HDMI input (you can get it at US$60 or less), and a metal book stand (Yes, metal book stand, and this might be the best thing you ever do with a metal book stand, to stand a projector ^_^)

Chromecast, mini LED projector, metal book stand Chromecast, mini LED projector, metal book stand

And enjoy your movie with 60″ screen on the ceiling 🙂

Filed under: Logs — Tags: , , , , — GG @ 6:53 pm

April 25, 2015

My first contact with Raspberry Pi

My new toys = berry + bread, lol

Raspberry Pi, solderless breadboard, HDMI, jumper, LED, switch, MicroSD...

Attended Raspberry Pi workshop today, learned Raspbian, Python programming, solderless breadboard, 7 segment numeric LED display…

One step further in exploration, one step closer to invention.

Filed under: Raspberry Pi — Tags: , , , , , — GG @ 5:03 pm

April 23, 2015

Google cloud storage for static website hosting

Synopsis

  • Using Google Cloud Storage as low cost yet reliable website hosting service for static webpages / files.

Requirements

  1. To host a static website on Google Cloud Storage, you need to create a Cloud Storage bucket with the domain/subdomain name as the bucket name.
  2. To create a domain named bucket or any bucket name contains dot (.), you need to pass the domain name ownership verification at Google Webmaster Tools.
  3. There are several methods to verify your site, however since you are creating a new storage to host your web files, I assume that you do not have an existing web hosting storage to store your HTML files at the moment, options by adding Meta tag, HTML file, Google Analytics or Tag Manager code might not be possible. Hence, adding new DNS records could be the only option that works for everyone.

Steps

  1. Creating DNS records
    Two new DNS records need to be created.

    1. A CNAME record of your subdomain hostname (e.g. www) with canonical name c.storage.googleapis.com.
      Creating CNAME record for Google Cloud Storage bucket
    2. Another TXT or CNAME record need to be created for Google Webmaster Tools domain ownership verification.
  2. Verify domain ownership
    Add your site at Google Webmaster Tools and verify the site ownership.
    Google Webmaster Tools site ownership verification
  3. Create bucket
    At Google Developers Console, under Storage > Cloud Storage, create a new bucket.
    Creating new Google Cloud Storage bucket
  4. Upload your web files
    Upload files to Google Cloud Storage bucket
  5. Set files permission
    From Storage Browser, enable public link option for all web files.
    Google Cloud Storage public link
  6. Edit bucket website configuration
    Configure main page and custom 404 page for your website.
    Google Cloud Storage website configuration, main page and custom 404 page

Useful gsutil / gsutil.py commands
You can also change file permission and website configuration using gsutil command.

Configuring main page and custom 404 page:

gsutil web set -m index.html -e 404.html gs://www.ggshow.com

Enabling public read file permission for a single file:

gsutil acl set public-read gs://www.ggshow.com/file.html

Enabling public read file permission for all files in bucket:

gsutil acl set public-read gs://www.ggshow.com/*.*

Uploading local files to bucket

gsutil cp -R \var\www gs://www.ggshow.com

Copying an object (file or folder) from one bucket to another bucket

gsutil cp -R gs://www.ggshow.com/object gs://mybackup.ggshow.com

Moving files from one folder to another folder

gsutil -m mv  gs://www.ggshow.com/folder1/*.* gs://www.ggshow.com/folder2

List files in bucket

gsutil ls gs://www.ggshow.com

Reference

Grayscaling your website

A quick solution to convert webpages into black and white using CSS grayscale filter, supported by all major web browsers including MSIE, Firefox, Chrome, Safari. Suitable for making mourning page, paying tribute, & etc.

Demo

Convert the entire page into black & white:

body {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
  filter: gray;
  -webkit-filter: grayscale(1);
}

Convert selected elements into black & white:

.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
  filter: gray;
  -webkit-filter: grayscale(1);
}

And add grayscale class to selected HTML elements. E.g.:

<div class="grayscale">
 ...
<div>

Print webpages in black & white:

@media print {
  .grayscale {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale");
    filter: gray;
    -webkit-filter: grayscale(1);
  }
}

CDN options
CSS also available on CDN.

Grayscale all:

<link rel="stylesheet" type="text/css" href="http://cdn.ggshow.com/styles/grayscale-all.css">

Grayscale selected:

<link rel="stylesheet" type="text/css" href="http://cdn.ggshow.com/styles/grayscale.css">

Grayscale print:

<link rel="stylesheet" type="text/css" href="http://cdn.ggshow.com/styles/grayscale-print.css">

Or using CSS import method:

Grayscale all:

@import url("http://cdn.ggshow.com/styles/grayscale-all.css");

Grayscale selected:

@import url("http://cdn.ggshow.com/styles/grayscale.css");

Grayscale print:

@import url("http://cdn.ggshow.com/styles/grayscale-print.css");
Filed under: CSS,HTML,Uncategorized — Tags: , , , , — GG @ 6:59 pm

January 4, 2014

b2evolution to WordPress migration

I’ve been looking for b2evolution to WordPress importer for long time. What I can find on the web are only migration script for older version of b2evo/wp, hence I’ve decided to write one on my own, for importing data from b2evolution 4.0.5 to WordPress 3.7.1. I’ve tested the script with WordPress 3.8.0 too. I’m hereby sharing it to whoever needs it.

Instruction

  1. Place this file at the same directory with your wp-config.php
  2. Access the URL at web browser, e.g.: http://localhost/b2wp.php
  3. Fill up the form with database connection detail, and submit.
  4. Select import options, and start import.

Warning

  1. Backup all your databases safely before proceed.
  2. Try it with a fresh installation of WordPress instead of production site.
  3. Use this script at your own risk 🙂

Download

  • b2wp.php – Tested with b2evo 4.0.5 to wp 3.7.1/3.8.0
  • b2wp_kp.zip – provided by KP for b2evo 5.1.2 to wp 4.
<?php
/*
* b2wp.php
* Title        : B2evolution to WordPress Importer
* Version      : 1.0.2
* Author URL   : http://www.ggshow.com
* Description  : Import Authors, Categories, Posts, Tags, and Comments, from
*               B2evolution database to WordPress database.
*/

function slug($str) {
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $str)));
}

$output = '';
$step = 1;
require_once( dirname(__FILE__) . '/wp-config.php' );
$target['db_host'] = DB_HOST;
$target['db_user'] = DB_USER;
$target['db_password'] = DB_PASSWORD;
$target['db_name'] = DB_NAME;
$wp_con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$target['status'] = (mysqli_connect_errno()) ? 'Error' : 'Connected';
$output .= ($target['status'] == 'Error') ? 'Error connecting WordPress database!<br />' : '';
$source['db_host'] = ($_POST['source_dbhost'] == '') ? 'localhost' : htmlentities($_POST['source_dbhost']);
$source['db_user'] = htmlentities($_POST['source_dbuser']);
$source['db_password'] = htmlentities($_POST['source_dbpassword']);
$source['db_name'] = htmlentities($_POST['source_dbname']);
if (!empty($_POST['source_dbname'])) {
$b2_con = new mysqli($source['db_host'], $source['db_user'], $source['db_password'], $source['db_name']);
$source['status'] = (mysqli_connect_errno()) ? 'Error' : 'Connected';
$output .= ($source['status'] == 'Error') ? 'Error connecting B2evolution database!<br />' : '';
} else {
$source['status'] = '';
$output .= 'Please fill up B2evolution database connection detail!<br />';
}
$target['table_prefix'] = (!empty($_POST['target_table_prefix'])) ? $wp_con->real_escape_string($_POST['target_table_prefix']) : 'wp_';
$source['table_prefix'] = (!empty($_POST['source_table_prefix'])) ? $wp_con->real_escape_string($_POST['source_table_prefix']) : 'evo_';
if ($source['status'] == 'Connected') {
$sql = " SHOW TABLES LIKE \"" . $source['table_prefix'] . "%\"";
$res = $b2_con->query($sql);
if ($res->num_rows <= 0) {
$source['status'] = 'Error';
$output .= "Invalid B2evo table prefix.<br />";
} else {
$sql = "SELECT DISTINCT `" . $source['table_prefix'] . "blogs`.* FROM `" . $source['table_prefix'] . "blogs`";
$res = $b2_con->query($sql);
$b2_blog_selected = ($_POST['b2_blog'] == '') ? 1 : $_POST['b2_blog'];
$b2_blog_select = '<select name="b2_blog">';
while ($row = $res->fetch_array()) {
$b2_blog_selected_str = '';
if ($row['blog_ID'] == $b2_blog_selected) {
$b2_blog_selected_str = 'selected';
$b2_blog_selected_row = $row;
}
$b2_blog_select .= '<option value="' . $row['blog_ID'] . '" ' . ($b2_blog_selected_str) . ' >' . $row['blog_name'] . '</option>';
}
$b2_blog_select .= '</select>';
}
}
if ($target['status'] == 'Connected') {
$sql = " SHOW TABLES LIKE \"" . $target['table_prefix'] . "%\"";
$res = $wp_con->query($sql);
if ($res->num_rows <= 0) {
$target['status'] = 'Error';
$output .= "Invalid WordPress table prefix.<br />";
} else {
$sql = "SELECT DISTINCT `" . $target['table_prefix'] . "users`.* FROM `" . $target['table_prefix'] . "users`";
$res = $wp_con->query($sql);
$b2_user_selected = ($_POST['b2_user'] == '') ? 0 : $_POST['b2_user'];
$b2_user_select = '<select name="b2_user">';
$b2_user_select .= '<option value="0">Import B2evo users</option>';
while ($row = $res->fetch_array()) {
if ($row['ID'] == $b2_user_selected) {
$b2_user_selected_str = 'selected';
$b2_user_selected_row = $row;
} else {
$b2_user_selected_str = '';
}
$b2_user_select .= '<option value="' . $row['ID'] . '" ' . ($b2_user_selected_str) . ' >Assign posts to ' . $row['user_login'] . '</option>';
}
$b2_user_select .= '</select>';
}
}
if ($source['status'] == 'Connected' && $target['status'] == 'Connected') {
$step = 2;
}
if ($step >= 2) {
$b2_cat_selected = ($_POST['b2_cat'] == '') ? 0 : $_POST['b2_cat'];
$b2_cat_select = '<select name="b2_cat">';
$b2_cat_select .= '<option value="1" ' . ($b2_cat_selected == 1 ? 'selected' : '') . '>a: Uncategorized</option>';
$b2_cat_select .= '<option value="2" ' . ($b2_cat_selected == 2 ? 'selected' : '') . '>b: Create a new category</option>';
$b2_cat_select .= '<option value="3" ' . ($b2_cat_selected == 3 ? 'selected' : '') . '>c: Import B2evo categories</option>';
$b2_cat_select .= '<option value="4" ' . ($b2_cat_selected == 4 ? 'selected' : '') . '>b+c</option>';
$b2_cat_select .= '</select>';
$b2_checbox_tags = '<input type="checkbox" value="1" name="b2_tags" ' . (($_POST['b2_tags'] == 1) ? 'checked' : '') . ' />';
$b2_checbox_comments = '<input type="checkbox" value="1" name="b2_comments" ' . (($_POST['b2_comments'] == 1) ? 'checked' : '') . ' />';
if ($_POST['step'] == '3' && $target['status'] != 'Error' && $source['status'] != 'Error') {
$step = 3;
}
}
if ($step >= 3) {
if ($b2_cat_selected == 1) {
$root_id = 1;
$taxonomy[1] = 1;
} else if ($b2_cat_selected == 2 || $b2_cat_selected == 4) {
unset($data);
$row = $b2_blog_selected_row;
$data['blog_name'] = $wp_con->real_escape_string($row['blog_name']);
$data['blog_urlname'] = slug($wp_con->real_escape_string($row['blog_urlname']));
$data['blog_description'] = empty($row['blog_description'])?$wp_con->real_escape_string($row['blog_tagline']):$wp_con->real_escape_string($row['blog_description']);
$sql = " INSERT INTO `" . $target['table_prefix'] . "terms` (`name`,`slug`,`term_group`) VALUES ('" . $data['blog_name'] . "','" . $data['blog_urlname'] . "','0');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$root_id = $wp_con->insert_id;
$newcat[0] = $root_id;
$sql = " INSERT INTO `" . $target['table_prefix'] . "term_taxonomy` (`term_id`,`taxonomy`,`description`,`parent`,`count`) VALUES ('" . $newcat[0] . "','category','" . $data['blog_description'] . "',0,0);";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$id = $wp_con->insert_id;
$taxonomy[$newcat[0]] = $id;
$output .= "1 new category created!<br />";
} else {
$root_id = 0;
$taxonomy[0] = 1;
}
if ($b2_cat_selected == 3 || $b2_cat_selected == 4) {
$sql = "SELECT DISTINCT `" . $source['table_prefix'] . "categories`.* FROM `" . $source['table_prefix'] . "categories` WHERE `cat_blog_ID` = " . $wp_con->real_escape_string($b2_blog_selected);
$res = $b2_con->query($sql);
$count = 0;
while ($row = $res->fetch_array()) {
$sql = " INSERT INTO `" . $target['table_prefix'] . "terms` (`name`,`slug`,`term_group`) VALUES ('" . $wp_con->real_escape_string($row['cat_name']) . "','" . $wp_con->real_escape_string($row['cat_urlname']) . "','0');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$id = $wp_con->insert_id;
$newcat[$row['cat_ID']] = $id;
$count++;
}
$sql = "SELECT DISTINCT `" . $source['table_prefix'] . "categories`.* FROM `" . $source['table_prefix'] . "categories` WHERE `cat_blog_ID` = " . $wp_con->real_escape_string($b2_blog_selected);
$res = $b2_con->query($sql);
while ($row = $res->fetch_array()) {
$data['parent_id'] = (isset($newcat[$row['cat_parent_ID']]) ? $newcat[$row['cat_parent_ID']] : $root_id);
$data['description'] = $wp_con->real_escape_string($row['cat_description']);
$sql = " INSERT INTO `" . $target['table_prefix'] . "term_taxonomy` (`term_id`,`taxonomy`,`description`,`parent`,`count`) VALUES ('" . $newcat[$row['cat_ID']] . "','category','" . $data['description'] . "','" . $data['parent_id'] . "',0);";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$id = $wp_con->insert_id;
$taxonomy[$newcat[$row['cat_ID']]] = $id;
}
$output .= $count . " categories imported!<br />";
}
if ($b2_cat_selected != 1) {
$sql = "UPDATE `" . $target['table_prefix'] . "options` SET `option_value`='' WHERE `option_name`='category_children';";
$wp_con->query(trim(str_replace("\n", "", $sql)));
}
if ($wp_user_selected == 0) {
$sql = " SELECT DISTINCT `" . $source['table_prefix'] . "users`.* FROM `" . $source['table_prefix'] . "users` INNER JOIN `" . $source['table_prefix'] . "blogusers` ON `" . $source['table_prefix'] . "users`.`user_ID` = `" . $source['table_prefix'] . "blogusers`.`bloguser_user_ID` WHERE `" . $source['table_prefix'] . "blogusers`.`bloguser_blog_ID` = " . $b2_con->real_escape_string($b2_blog_selected) . " AND `user_login`<>'admin'";
$res = $b2_con->query($sql);
$count = 0;
while ($row = $res->fetch_array()) {
$sql = " SELECT * FROM `" . $target['table_prefix'] . "users` WHERE `user_login` = '" . $wp_con->real_escape_string($row['user_login']) . "';";
$pres = $wp_con->query(trim(str_replace("\n", "", $sql)));
if ($prow = $pres->fetch_array()) {
$id = $prow['ID'];
} else {
$sql = " INSERT INTO `" . $target['table_prefix'] . "users` (`user_login`,`user_pass`,`user_nicename`,`user_email`,`user_url`,`user_registered`,`user_status`,`display_name`) VALUES ('" . $wp_con->real_escape_string($row['user_login']) . "','" . $wp_con->real_escape_string($row['user_pass']) . "','" . $wp_con->real_escape_string($row['user_login']) . "','" . $wp_con->real_escape_string($row['user_email']) . "','" . $wp_con->real_escape_string($row['user_url']) . "','" . $wp_con->real_escape_string($row['dateYMDhour']) . "','0','" . $wp_con->real_escape_string($row['user_login']) . "');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$id = $wp_con->insert_id;
$sql = " INSERT INTO `" . $target['table_prefix'] . "usermeta` (`user_id`,`meta_key`,`meta_value`) VALUES ('" . $id . "', 'first_name', '" . $wp_con->real_escape_string($row['user_firstname']) . "');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$sql = " INSERT INTO `" . $target['table_prefix'] . "usermeta` (`user_id`,`meta_key`,`meta_value`) VALUES ('" . $id . "', 'last_name', '" . $wp_con->real_escape_string($row['user_lastname']) . "');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$sql = " INSERT INTO `" . $target['table_prefix'] . "usermeta` (`user_id`,`meta_key`,`meta_value`) VALUES ('" . $id . "', 'nickname', '" . $wp_con->real_escape_string($row['user_nickname']) . "');";
$wp_con->query(trim(str_replace("\n", "", $sql)));
$count++;
}
$newuser[$row['user_ID']] = $id;
}
if ($count > 0) {
$output .= $count . " users imported!<br />";
}
} else {
$newuser[0] = $wp_user_selected;
}
$sql = "SELECT DISTINCT `" . $source['table_prefix'] . "items__item`.* FROM `" . $source['table_prefix'] . "items__item` INNER JOIN `" . $source['table_prefix'] . "categories` ON `" . $source['table_prefix'] . "items__item`.`post_main_cat_ID` = `" . $source['table_prefix'] . "categories`.`cat_ID` WHERE `" . $source['table_prefix'] . "categories`.`cat_blog_ID` = " . $b2_blog_selected;
$res = $b2_con->query($sql);
$pcount = 0;
$tcount = 0;
$ccount = 0;
while ($row = $res->fetch_array()) {
unset($data);
if ($b2_user_selected == 0) {
$data['user'] = isset($newuser[$row['post_creator_user_ID']]) ? $newuser[$row['post_creator_user_ID']] : 1;
} else {
$data['user'] = $b2_user_selected;
}
$data['category'] = isset($newcat[$row['post_main_cat_ID']]) ? $newcat[$row['post_main_cat_ID']] : $root_id;
switch ($row['post_status']) {
case 'published':
case 'deprecated':
$data['status'] = 'publish';
break;
case 'protected':
case 'private':
$data['status'] = 'private';
break;
case 'redirected':
$row['post_content'] = "<a href='".htmlentities($row['post_url'])."'>".htmlentities($row['post_url'])."</a>";
default:
$data['status'] = 'draft';
}
$data['date'] = $row['post_datecreated'];
$data['date_gmt'] = gmdate("Y-m-d G:i:s ", strtotime($data['date']));
$data['modified'] = $row['post_datemodified'];
$data['modified_gmt'] = gmdate("Y-m-d G:i:s ", strtotime($data['modified']));
$psql = "SELECT COUNT(1) AS comment_count FROM `" . $source['table_prefix'] . "comments` WHERE `" . $source['table_prefix'] . "comments`.`comment_post_ID` = " . $row['post_ID'];
$pres = $b2_con->query($psql);
$prow = $pres->fetch_array();
$data['comment_count'] = $prow['comment_count'];
$data['post_content'] = $row['post_content'];
$data['post_excerpt'] = $row['post_excerpt'];
$data['title'] = $row['post_title'];
$psql = "INSERT INTO `" . $target['table_prefix'] . "posts` (`post_author`,`post_content`,`post_title`,`post_excerpt`,`post_status`,`post_date`,`post_date_gmt`,`post_modified`,`post_modified_gmt`,`comment_count`, `to_ping`, `pinged`, `post_content_filtered`) VALUES ('" . $data['user'] . "','" . $wp_con->real_escape_string($data['post_content']) . "','" . $wp_con->real_escape_string($data['title']) . "','" . $wp_con->real_escape_string($data['post_excerpt']) . "','" . $data['status'] . "','" . $data['date'] . "','" . $data['date_gmt'] . "','" . $data['modified'] . "','" . $data['modified_gmt'] . "','" . $data['comment_count'] . "', '', '', '');";
$wp_con->query(trim(str_replace("\n", "", $psql)));
$id = $wp_con->insert_id;
$eid = $row['post_ID'];
$psql = "INSERT INTO `wp_term_relationships` (`object_id`,`term_taxonomy_id`,`term_order`) VALUES (" . $id . "," . $taxonomy[$data['category']] . ",0);";
$wp_con->query(trim(str_replace("\n", "", $psql)));
$psql = "SELECT * FROM `" . $source['table_prefix'] . "postcats` WHERE `postcat_post_ID` = " . $row['post_ID'];
$pres = $b2_con->query($psql);
while ($prow = $pres->fetch_array()) {
$psql = "INSERT INTO `wp_term_relationships` (`object_id`,`term_taxonomy_id`,`term_order`) VALUES (" . $id . "," . $taxonomy[$newcat[$prow['postcat_cat_ID']]] . ",0);";
$wp_con->query(trim(str_replace("\n", "", $psql)));
}
$pcount++;
if ($_POST['b2_tags'] == 1) {
$psql = "SELECT `itag_itm_ID`, LOWER(cast(`" . $source['table_prefix'] . "items__tag`.`tag_name` as char)) AS tag_name FROM `" . $source['table_prefix'] . "items__tag` INNER JOIN `" . $source['table_prefix'] . "items__itemtag` ON `itag_tag_ID` = `tag_ID` WHERE `itag_itm_ID` = " . $row['post_ID'];
$pres = $b2_con->query($psql);
while ($prow = $pres->fetch_array()) {
unset($data);
$data['tag_name'] = $wp_con->real_escape_string($prow['tag_name']);
$data['tag_slug'] = slug($data['tag_name']);
$tsql = "SELECT * FROM `" . $target['table_prefix'] . "terms` WHERE `slug` = '" . $data['tag_slug'] . "';";
$tres = $wp_con->query(trim(str_replace("\n", "", $tsql)));
if ($trow = $tres->fetch_array()) {
$tid = $trow['term_id'];
} else {
$tsql = "INSERT INTO `" . $target['table_prefix'] . "terms` (`name`,`slug`,`term_group`) VALUES ('" . $data['tag_name'] . "','" . $data['tag_slug'] . "',0);";
$wp_con->query(trim(str_replace("\n", "", $tsql)));
$tid = $wp_con->insert_id;
$tcount++;
}
$tsql = "SELECT * FROM `" . $target['table_prefix'] . "term_taxonomy` WHERE `term_id` = '" . $tid . "' AND `taxonomy`='post_tag';";
$tres = $wp_con->query(trim(str_replace("\n", "", $tsql)));
if ($trow = $tres->fetch_array()) {
$ttid = $trow['term_taxonomy_id'];
} else {
$tsql = "INSERT INTO `" . $target['table_prefix'] . "term_taxonomy` (`term_id`,`taxonomy`,`description`,`parent`,`count`) VALUES (" . $tid . ",'post_tag','',0,0);";
$wp_con->query(trim(str_replace("\n", "", $tsql)));
$ttid = $wp_con->insert_id;
}
$tsql = "SELECT * FROM `" . $target['table_prefix'] . "term_relationships` WHERE `object_id` = '" . $id . "' AND `term_taxonomy_id`='" . $ttid . "';";
$tres = $wp_con->query(trim(str_replace("\n", "", $tsql)));
if ($trow = $tres->fetch_array()) {

} else {
$tsql = "INSERT INTO `" . $target['table_prefix'] . "term_relationships` (`object_id`,`term_taxonomy_id`,`term_order`) VALUES (" . $id . "," . $ttid . ",0);";
$wp_con->query(trim(str_replace("\n", "", $tsql)));
}
}
}
if ($_POST['b2_comments'] == 1) {
$psql = "SELECT `" . $source['table_prefix'] . "comments`.* , `" . $source['table_prefix'] . "users`.`user_nickname`, `" . $source['table_prefix'] . "users`.`user_url`, `" . $source['table_prefix'] . "users`.`user_email` FROM `" . $source['table_prefix'] . "comments` LEFT JOIN `" . $source['table_prefix'] . "users` ON `" . $source['table_prefix'] . "comments`.`comment_author_ID` = `" . $source['table_prefix'] . "users`.`user_ID` WHERE `" . $source['table_prefix'] . "comments`.`comment_post_ID`=" . $eid;
$pres = $b2_con->query($psql);
while ($prow = $pres->fetch_array()) {
unset($data);
if ($prow['comment_author_ID'] != NULL) {
$data['author'] = $wp_con->real_escape_string($prow['user_nickname']);
$data['url'] = $wp_con->real_escape_string($prow['user_url']);
$data['email'] = $wp_con->real_escape_string($prow['user_email']);
} else {
$data['author'] = $wp_con->real_escape_string($prow['comment_author']);
$data['url'] = $wp_con->real_escape_string($prow['comment_author_url']);
$data['email'] = $wp_con->real_escape_string($prow['comment_author_email']);
}
$data['time'] = $wp_con->real_escape_string($prow['comment_date']);
$data['gm_time'] = gmdate("Y-m-d G:i:s ", strtotime($data['time']));
$data['comment_type'] = $wp_con->real_escape_string($prow['comment_type']);
switch ($data['comment_type']) {
case 'trackback':
break;
case 'pingback':
case 'linkback':
$data['comment_type'] = 'pingback';
break;
case 'comment':
default:
$data['comment_type'] = '';
break;
}
$data['comment_status'] = $wp_con->real_escape_string($prow['comment_status']);
switch ($data['comment_status']) {
case 'published':
case 'deprecated':
$data['comment_status'] = '1';
break;
case 'protected':
case 'private':
$data['comment_status'] = 'private';
break;
case 'draft':
case 'redirected':
default:
$data['comment_status'] = '0';
}
$data['comment_author_IP'] = $wp_con->real_escape_string($prow['comment_author_IP']);
$data['comment_content'] = $wp_con->real_escape_string($prow['comment_content']);
$data['comment_karma'] = $wp_con->real_escape_string($prow['comment_karma']);
$csql = "INSERT INTO `" . $target['table_prefix'] . "comments` (`comment_post_ID`,`comment_author`,`comment_author_email`,`comment_author_url`,`comment_author_IP`,`comment_date`,`comment_date_gmt`,`comment_content`,`comment_karma`, `comment_approved`, `comment_type`) VALUES ('" . $id . "','" . $data['author'] . "','" . $data['email'] . "','" . $data['url'] . "','" . $data['comment_author_IP'] . "','" . $data['time'] . "','" . $data['gm_time'] . "','" . $data['comment_content'] . "','" . $data['comment_karma'] . "','" . $data['comment_status'] . "','" . $data['comment_type'] . "');";
$wp_con->query(trim(str_replace("\n", "", $csql)));
$ccount++;
}
}
}
$output .= $pcount . " posts imported!<br />";
if ($_POST['b2_tags'] == 1) {
$output .= $tcount . " tags imported!<br />";
}
if ($_POST['b2_comments'] == 1) {
$output .= $ccount . " comments imported!<br />";
}
}
mysqli_free_result($res);
mysqli_free_result($pres);
mysqli_free_result($tres);
mysqli_close($wp_con);
mysqli_close($b2_con);
?>
<!DOCTYPE html>
<html>
<head>
<title>b2wp - b2evolution to wordpress importer</title>
<meta charset="UTF-8">
<style>
body { font: 10pt sans-serif; }
table { width: 480px; border: #ccc 1px solid; margin:10px auto; }
th, td { width: 160px; }
caption { font: bold 16pt sans-serif; }
</style>
</head>

<body>
<form action="" method="post">
<table>
<caption>B2WP</caption>
<tr>
<th></th>
<th>B2evolution</th>
<th>Wordpress</th>
</tr>
<tr>
<td>Host</td>
<td><input name="source_dbhost" type="text" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $source['db_host']; ?>" /></td>
<td><input type="text" disabled value="<?php echo $target['db_host']; ?>" /></td>
</tr>
<tr>
<td>User</td>
<td><input name="source_dbuser" type="text" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $source['db_user']; ?>" /></td>
<td><input type="text" disabled value="<?php echo $target['db_user']; ?>" /></td>
</tr>
<tr>
<td>Password</td>
<td><input name="source_dbpassword" type="password" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $source['db_password']; ?>" /></td>
<td><input type="password" disabled value="<?php echo $target['db_password']; ?>" /></td>
</tr>
<tr>
<td>Database</td>
<td><input name="source_dbname" type="text" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $source['db_name']; ?>" /></td>
<td><input type="text" disabled value="<?php echo $target['db_name']; ?>" /></td>
</tr>
<tr>
<td>Table Prefix</td>
<td><input type="text" name="source_table_prefix" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $source['table_prefix']; ?>" /></td>
<td><input type="text" name="target_table_prefix" <?php if ($step >= 2) echo 'readonly'; ?> value="<?php echo $target['table_prefix']; ?>" /></td>
</tr>
<tr>
<td>Status</td>
<td><input type="text" disabled value="<?php echo $source['status']; ?>" /></td>
<td><input type="text" disabled value="<?php echo $target['status']; ?>" /></td>
</tr>
<?php if ($step == 1) { ?>
<tr>
<td></td>
<td colspan="2"><input type="submit" value="Connect" /></td>
</tr>
<?php } else if ($step >= 2) { ?>
<tr>
<td colspan="3"><input type="hidden" name="step" value="3"/><hr /></td>
</tr>
<tr>
<td>B2evo Blog</td>
<td colspan="2">
<?php echo $b2_blog_select; ?>
</td>
</tr>
<tr>
<td valign="top">Import Options</td>
<td colspan="2">
<input type="checkbox" checked disabled> <label for="b2_posts">Posts</label><br />
<input type="checkbox" checked disabled> <label for="b2_user">Authors</label> <?php echo $b2_user_select; ?><br />
<input type="checkbox" checked disabled> <label for="b2_cat">Categories</label> <?php echo $b2_cat_select; ?><br />
<?php echo $b2_checbox_tags; ?> <label for="b2_tags">Tags</label><br />
<?php echo $b2_checbox_comments; ?> <label for="b2_comments">Comments</label><br />
</td>
</tr>
<tr>
<td></td>
<td colspan="2">
</td>
</tr>
<tr>
<td></td>
<td colspan="2">
<input type="submit" value="Import" />
<input type="button" value="Back" onclick="location.href='b2wp.php';" />
</td>
</tr>
<?php } ?>
<?php if (!empty($output)) { ?>
<tr>
<td colspan="3"><hr /><?php echo $output; ?></td>
</tr>
<?php } ?>
</table>
</form>
</body>
</html>

This is NOT a WordPress importer plugin, this is simply a PHP script to extract content (Authors, Categories, Posts, Tags, and Comments) from a b2evolution database and insert into WordPress database. This migration script does NOT catered importing of uploaded media files. Feel free to modify it as per your needs. You might want to try these WordPress plugins Add From Server or Import External Images for migrating your uploaded files.

Special thanks
Thanks to RealNitro’s b2evo2wp.php script, it was my primary source of reference for understanding b2evo/wp database schema.
Thanks to KP for sharing b2evolution 5.1.2 to WorPress 4 migration script.

Filed under: MySQL,PHP,Web — Tags: , , , , — GG @ 6:53 am

February 16, 2013

Webpage Editable Switch

FREE! A handy web browser extension/add-on to turn document body contentEditable on or off.

* Pencil icon used in this extension was downloaded from http://openclipart.org

Webpage Editable Switch 1.0 for Firefox

Download WES 1.0 for Firefox

Webpage Editable Switch 1.0 for Chrome

Download WES 1.0 for Chrome

Filed under: Web,Web Browsers — Tags: , , , , , — GG @ 10:50 pm
Older Posts »

© 2024 GGSHOW | Powered by WordPress