<?php

/**
* b3 wordpress import - Simon Benjamin - http://benjamin.hu/ - 2007.04.20.
*
* Leiras
* ------
* A b3 (blogter blog backup) altal keszitett ser.txt formatumu blog adatok importalasa wordpressbe.
*
* Informaciok
* -----------
* Elozmenyek: http://benjamin.hu/2007/03/08/februari-hianyzas-es-valtas/
*
* Hasznalat
* ---------
* Az importalo scriptet masold be a wp-admin/import ala, ezutan a wordpress admin intezo -> import
* menupontban megjelenik a "Blogter" lehetoseg. Add meg feltoltendo filekent a lementett ser.txt
* formatumu file-t es vard meg amig feler.
* Importalas elott lehetoseged van modositani a cimet, datumot, beallithatod hogy mi melyik
* bejegyzesek legyenek importalva, illetve modosithatod a cimkeket.
* Az importalas vegen general a kod egy JavaScriptet amit az oldaladba illesztve az osszes regi
* blog bejegyzesedet az ujra iranyithatod!
*
* Licensz
* -------
* GPL, a kod szabadon terjesztheto es modosithato a fejlesztesekrol visszajelzest kernek
*
* Kapcsolat
* ---------
* Javaslatokat, eszreveteleket, hibakat, kerdeseket a blogter2wp [kukac] benjamin [pont] hu cimre
* lehet kuldeni.
*
* Valtozasok
* ----------
* 0.2 - 2007.04.20.
*         Megjegyzes, NEW_BLOG_URL bevezetese.
*
* 0.1 - 2007.04.19.
*         Elso publikus megjelenes
**/

define('NEW_BLOG_URL', 'http://benjamin.hu/');

function
p($v) { echo '<pre>'; print_r($v); echo '</pre>'; }
function
checkArray(&$array) { return (is_array($array) && count($array)) ? TRUE : FALSE; }

ini_set('memory_limit', '32M');
set_time_limit(0);

class
Blogter_Import {

    var
$file;

    function
header() {
        echo
'<div class="wrap">';
        echo
'<h2>'.__('Blogter importálás').'</h2>';
    }

    function
footer() {
        echo
'</div>';
    }

    function
greet() {
        echo
'<p>'.__('Bejegyzések és hozzászólások importálása a Blogter blogból (serialzált változat!).').'</p>';
        
wp_import_upload_form("admin.php?import=blogter&amp;step=1");
    }

    function
read() {
        global
$wpdb, $current_user;

        
$file = wp_import_handle_upload();
        if (isset(
$file['error'])) { echo $file['error']; return; }

        
$this->file = $file['file'];

        
set_magic_quotes_runtime(0);

        
$content = join('', file($this->file));
        
update_option('import-blogter', $content);
        
wp_import_cleanup($file['id']);
        
$blog = unserialize($content);

        
// nem megfelelo struktura!
        
if (!checkArray($blog['posts'])) die('<h1>'.__('Nincsenek megjeleníthető adatok!').'</h1>');

        
$show = array();
        echo
'<h4>'.__('Import beállítások!').'</h4>';
        echo
'<p>'.__('Itt lehetőséged van módosítani, hogy melyik bejegyzéseket és milyen címkékkel (használd a vesszőt így meagadhatsz szóközt tartalmazó címkéket is!) importálja a script a wordpressbe!').'</p>';
        echo
'<form method="post" action="admin.php?import=blogter&step=2">';
        echo
'<center><input type="submit" name="submit_import1" value="'.__('Importálás').'"/></center>';
        echo
'<table>';
        echo
'<tr>';
        echo
'<td>'.__('Import?').'</td>';
        echo
'<td>'.__('Bejegyzés címe').'</td>';
        echo
'<td>'.__('Bejegyzés dátuma').'</td>';
        echo
'<td>'.__('Címkék').'</td>';
        echo
'</tr>';
        foreach (
$blog['posts'] as $post) {
            echo
'<tr>';
            echo
'<td><input type="checkbox" name="import[]" value="'.$post['postid'].'" checked="checked"/></td>';
            echo
'<td><a href="http://'.$blog['blog'].'/?post_id='.$post['postid'].'">'.mb_convert_encoding($post['title'], 'UTF-8', 'ISO-8859-2').'</a></td>';
            echo
'<td>'.date('Y.m.d. H:i:s', $post['stamp']).'</td>';
            echo
'<td><input type="text" size="40" name="tags['.$post['postid'].']" value="'.mb_convert_encoding(str_replace(' ', ', ', $post['tags']), 'UTF-8', 'ISO-8859-2').'"/></td>';
            echo
'</tr>';
        }
        echo
'</table>';
        echo
'<center><input type="submit" name="submit_import2" value="'.__('Importálás').'"/></center>';
    }

    function
import() {
        global
$wpdb, $current_user;

        
$content = get_option('import-blogter', $content);
        
$blog = unserialize($content);

        if (!
checkArray($_POST) || !checkArray($blog['posts'])) wp_redirect("admin.php?import=blogter");

        
settype($_POST['import'], 'array');

        
$redirectinfo = array();

        echo
'<ol>';
        foreach (
$blog['posts'] as $post) {
            
$redirectinfo[$post['postid']] = '';
            
// nem kell importalni
            
if (!in_array($post['postid'], $_POST['import'])) continue;

            
$tags = preg_split('/\s*[,]\s*/', $_POST['tags'][$post['postid']], -1, PREG_SPLIT_NO_EMPTY);;

            
$post['title'] = mb_convert_encoding($post['title'], 'UTF-8', 'ISO-8859-2');

            
$post_title = $post['title'];
            
$post_content = $wpdb->escape(mb_convert_encoding($post['html'], 'UTF-8', 'ISO-8859-2'));
            
$post_date = date('Y-m-d H:i:s', $post['stamp']);
            
$post_author = $current_user->ID;
            
$post_status = 'publish';

            echo
'<li>';
            if (
$post_id = post_exists($post_title, $post_content, $post_date)) {
                
printf(__('A bejegyzés (<i>%s</i>) már szerepel az adatbázisban!'), stripslashes($post_title));
            } else {
                
printf(__('Bejegyzés importálása <i>%s</i>...'), stripslashes($post_title));
                
$postdata = compact('post_author', 'post_date', 'post_content', 'post_title', 'post_status');
                
$post_id = wp_insert_post($postdata);
                if (!
$post_id) {
                    
_e('Hiba a bejegyzés beszúrása közben!');
                    echo
'</li>';
                    break;
                }
                
$postdata = get_post($post_id);

                
$redirectinfo[$post['postid']] = get_permalink($post_id);

                if (
count($tags)) wp_create_categories($tags, $post_id);

                if (
checkArray($post['comments'])) {
                    
$comment_post_ID = $post_id;
                    
$num_comments = 0;
                    foreach (
$post['comments'] as $comment) {
                        
$comment_content = mb_convert_encoding($comment['comment'], 'UTF-8', 'ISO-8859-2');

                        
// Clean up content
                        
$comment_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $comment_content);
                        
$comment_content = str_replace('<br>', '<br />', $comment_content);
                        
$comment_content = str_replace('<hr>', '<hr />', $comment_content);
                        
$comment_content = $wpdb->escape($comment_content);

                        
$comment_date = date('Y-m-d H:i:s', $comment['stamp']);
                        
$comment_author = $wpdb->escape(mb_convert_encoding($comment['name'], 'UTF-8', 'ISO-8859-2'));
                        
$comment_author_email = $wpdb->escape($comment['email']);
                        
$comment_author_url = $wpdb->escape($comment['www']);
                        
$comment_author_IP = $comment['ip'];

                        
$comment_approved = 1;

                        
// Check if it's already there
                        
if (!comment_exists($comment_author, $comment_date)) {
                            
$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_date', 'comment_content', 'comment_approved', 'comment_author_url', 'comment_author_IP');
                            
$commentdata = wp_filter_comment($commentdata);
                            
wp_insert_comment($commentdata);
                            
$num_comments++;
                        }
                    }
                    if (
$num_comments) { echo ' ';     printf(__('(%s hozzászólás)'), $num_comments); }
                }
            }
            echo
'</li>';
            
flush();
            
ob_flush();
        }
        echo
'</ol>';

        echo
$this->genRedirectInfo(array('redirect' => $redirectinfo, 'blog' => $blog['blog']));
    }

    function
genRedirectInfo($arr)
    {
        if (!
checkArray($arr['redirect'])) return '';

        
$olduri = 'var olduri = new Array("'.implode('", "', array_keys($arr['redirect'])).'");';
        
$newuri = 'var newuri = new Array("'.implode('", "', array_keys(array_flip($arr['redirect']))).'");';

        
$str .= '<textarea rows="25" cols="90" name="rewritecode" onclick="this.select();">';
        
$str .='<script type="text/javascript">
                <!--
                '
.$olduri.'
                '
.$newuri.'
                var find = "post_id=";
                var pos = location.href.indexOf(find);
                if (pos > -1) {
                    var postid = parseInt(location.href.substr(pos + find.length));
                    var length = olduri.length;
                    for (i = 0; i < length; i++) {
                        if (olduri[i] == postid) window.location = newuri[i];
                    }
                } else window.location = "'
.NEW_BLOG_URL.'";
                //-->
                </script>'
;
        
$str .='</textarea>';

        return
$str;
    }

    function
dispatch() {
        if (empty (
$_GET['step'])) $step = 0;
        else
$step = (int) $_GET['step'];

        
$this->header();

        switch (
$step) {
            case
0 :
                
$this->greet();
                
delete_option('import-blogter');
                break;
            case
1 : $this->read(); break;
            case
2 : $this->import(); break;
        }

        
$this->footer();
    }

    function
Blogter_Import() {
        
// Nothing.
    
}
}

$blogter_import = new Blogter_Import();

register_importer('blogter', 'Blogter', __('Bejegyzések és hozzászólások importálása Blogter blogból'), array ($blogter_import, 'dispatch'));

?>