<?php

/* Original  WP convert       */
/* COPYRIGHT  Radek HULAN     */
/* http://hulan.cz/         */
/*                            */
/* nuke flexible by  Ihra     */
/* Version 1.0 - 200804       */
/* Version 1.1 - 310804       */
/* Version 1.2 - 010904       */
/* Version 1.3 - 050904       */
/*                            */
/* this script will convert   */
/* your phpNuke into          */
/* BLOG:CMS weblog            */

  function def($s){
    if (isset($_POST[$s]))
      echo addslashes(stripslashes($_POST[$s]));
    else {
      if (strstr($s,'host')) echo "localhost";
      if (strstr($s,'username')) echo "root";
      if (strstr($s,'nukeprefix')) echo "nuke_";
    }
  }

  function error($s){
    global $isok;
    $isok=false;
    echo "<h3>Error: $s</h3>";
  }

  // line breaks into properly formatted paragraphs
  function paragraph($text, $br = false) {
    $text=trim($text);
    $text = str_replace("\r",'',$text);
    $text = preg_replace('/&([^#])(?![a-z]{1,8};)/', '&$1', $text);
    if ($text=="") return "";
    $text = $text . "\n"; // just to make things a little easier, pad the end
    $text = preg_replace('|<br/>\s*<br/>|', "\n\n", $text);
    $text = preg_replace('!(<(?:table|ul|ol|li|pre|form|blockquote|h[1-6])[^>]*>)!', "\n$1", $text); // Space things out a little
    $text = preg_replace('!(</(?:table|ul|ol|li|pre|form|blockquote|h[1-6])>)!', "$1\n", $text); // Space things out a little
    $text = preg_replace("/(\r\n|\r)/", "\n", $text); // cross-platform newlines
    $text = preg_replace("/\n\n+/", "\n\n", $text); // take care of duplicates
    $text = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "\t<p>$1</p>\n", $text); // make paragraphs, including one at the end
    $text = preg_replace('|<p>\s*?</p>|', '', $text); // under certain strange conditions it could create a P of entirely whitespace
    $text = preg_replace("|<p>(<li.+?)</p>|", "$1", $text); // problem with nested lists
    // blockquote
    $text = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $text);
    $text = str_replace('</blockquote></p>', '</p></blockquote>', $text);
    // now the hard work
    $text = preg_replace('!<p>\s*(</?(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)!', "$1", $text);
    $text = preg_replace('!(</?(?:table|tr|td|th|div|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)\s*</p>|</div>"!', "$1", $text);
    if ($br) $text = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $text); // optionally make line breaks
    $text = preg_replace('!(</?(?:table|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|p|h[1-6])[^>]*>)\s*<br/>!', "$1", $text);
    $text = preg_replace('!<br/>(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $text);
    // some cleanup
    $text = str_replace('</p><br />','</p>',$text);
    $text = str_replace("<br />\n</p>",'</p>',$text);
    return $text;
  }

  function encoding($s){
    global $input;
    if (is_callable("iconv"))
      return iconv($input,'utf-8',$s);
    else
      return $s;
  }



?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>phpNuke to BLOG:CMS convertor</title>
<meta http-equiv='Pragma' content='no-cache' />
<meta http-equiv='Cache-Control' content='no-cache, must-revalidate' />
<meta http-equiv='Expires' content='-1' />
<style type="text/css">
body { font-size: 15px; color: #000000; margin: 0; padding: 0; border: 0; font-family: "Trebuchet MS", "Bitstream Vera Sans", verdana, lucida, arial, helvetica, sans-serif; padding-bottom: 25px; background: #7797BD; }
#content{ width: 600px; margin: 15px auto 0 auto; padding: 0 20px 20px 20px; background: #ffffff; border: 1px solid #314864; border-top:1px solid #233447}
h1{margin:0 -20px 0 -20px;color:#FFF;font-size:x-large;font-weight:bold;background:#336699;padding:15px 0 15px 0; text-align:center }
h2{margin:20px 0 5px 0;color:green;font-size:medium}
h3{margin:20px 0 5px 0;color:red;font-size:medium}
li{margin:5px}
fieldset{padding:10px; text-align:right; margin:0 0 0 0}
a{text-decoration:none;color:blue}
a:hover{text-decoration:underline}
</style>
</head>
<body>
  <div id='content'>
  <h1><small>phpNuke ��</small> BLOG:CMS <small>�� convertor</small></h1>

<?php
  if (!isset($_POST['convert'])) {
?>
  <p>This tool will convert your <a href="http://www.phpnuke.org">phpNuke</a> into <a href='http://blogcms.com/'>BLOG:CMS
      weblog</a> publishing system. First, install BLOG:CMS, in a default
      install, and only after that run this tool. It will transfer all posts,
      reviews, comments and (unique!!!) members into blog #1. Note: Uses
      NP_Views to import times viewed  and <a href="http://forum.blogcms.com/viewtopic.php?id=582">NP_Reviews</a> to
    add ratings to articles (both only if selected). If you don't know what these mean, leave default selections as is (NP_Views is installed with default BLOG:CMS installation). </p>
  <p> Adds same members and categories as in
        nuke - <strong>your
        blog categories will not be overwritten </strong>(but many categories added
        to existing categories will bloat your blog). Note that member-name is <em>unique </em>- script will fail if there exists user with same name!
      So if your nuke database includes blog:cms member that is currently admin - <strong>CHANGE</strong> your admin name in either database!<br />
    Script will convert images from phpNuke reviews to <em>/media/public/</em> directory where they are available to everyone. After running the script, make /media/public with access to everyone (chmod 777) and copy your images to directory from phpNuke directory (normally images/reviews and/or images/articles). Update also your links in articles itself! <br />
    <?php
  } else {
     // whether everything stays ok.
    $isok=true;
    $np_reviews=$_POST['np_reviews'];
    $np_views=$_POST['np_views'];
    $popupusage=$_POST['popupusage'];
    // connect to phpNuke database
      $linkwp = @mysql_connect($_POST['nukehost'],$_POST['nukeusername'],$_POST['nukepassword'],true);
    if($linkwp==false)
      error("Cannot connect to phpNuke DB..");
    else {
        @mysql_select_db($_POST['nukedatabase'],$linkwp) or error("Cannot select phpNuke DB...");
      }

    // connect to BLOG:CMS database
      $linkblogcms = @mysql_connect($_POST['blogcmshost'],$_POST['blogcmsusername'],$_POST['blogcmspassword'],true);
    if($linkblogcms==false)
      error("Cannot connect to BLOG:CMS DB..");
    else {
        @mysql_select_db($_POST['blogcmsdatabase'],$linkblogcms) or error("Cannot select BLOG:CMS DB...");
      }

      if (!$isok) {
        echo "<p>Please correct these errors first!</p><hr />";
    } else {
      /*                 */
      /* transfer data ! */
      /*                 */
      $prefixwp=$_POST['nukeprefix'];
      $prefixblogcms=$_POST['blogcmsprefix'];

      /* *********************************************** */
      echo "<h2>Setting encoding...</h2>";
      $input="utf-8";
      echo "<p>Encoding: $input</p>";

      /* *********************************************** */
      echo "<h2>Transfering categories...</h2>";
        // find category id number, convert it to blog:cms category
        // uses crosslinked array where there is category=categoryBlogCms[categoryNuke]
        $blogcmscat[0]=0;
    $query="select topicid, topicname, topictext  from ".$prefixwp."topics order by topicid";
    $querywp=mysql_query($query,$linkwp) or die($query);
    // catid (auto), cblog (1), cname, iurltitle (remove stuff?), cdesc = all you need in blog:cms
    // browse through all the topics and put new categories to blog:cms
    echo "<p>categories to transfer: ".mysql_num_rows($querywp)."</p>";
    echo "<p>";
    $i=1;
    while ($row=mysql_fetch_object($querywp))
       {
        $query=
          "insert into ".$prefixblogcms."nucleus_category ".
          "(cblog,cname,iurltitle,cdesc) values (".
          "1,'".$row->topicname."','".$row->topicname."','".$row->topictext."'".
          ")";
        $result = mysql_query($query,$linkblogcms) or die($query);
        // get auto increment field value to make index
        $rowid=mysql_insert_id($linkblogcms);
        // now we can insert article to $blogcmscat[$nuketopic]
        $blogcmscat[$row->topicid]=$rowid;
        echo "row: ".$i++." ".$row->topicname." nuke ".$row->topicid.", blogcms ".$rowid."<br /> ";
       }

      echo "<h2>Transfering members...</h2>";
        // find author / poster from blog:cms, as phpNuke will use informant field only as a link to
        // modules.php?module=member&name=informant
        // uses crosslinked array, where there is author=memberBlogCms[memberNuke]
        // REMEMBER THAT USERNAME SHOULD BE UNIQUE! Script will fail if there is existing user with same name
        $query="select user_id, name, username, user_email, user_website, user_password from ".$prefixwp."users order by user_id";
        $querywp=mysql_query($query,$linkwp) or die($query);
    // nucleus: mnumber (auto), mname (16), mrealname (60), mpassword (40 - md5, same as phpNuke), memail (60)
    //   murl (100), mnotes (100), madmin (2), mcanlogin (2), mcookiekey (40), deflang (20)
    // browse through all the nuke members and put members to blog:cms
    echo "<p>Members to transfer: ".mysql_num_rows($querywp)." (total includes bogus members like Anonymous)</p>";
    echo "<p>";
    $i=1;
    $blogcmsauthor["0"]=0;
    while ($row=mysql_fetch_object($querywp))
       {
        if ($row->username<>"Anonymous")
        { $queryins=
          "insert into ".$prefixblogcms."nucleus_member ".
          "(mname, mrealname, mpassword, memail, murl) values (".
          "\"".$row->username."\",\"".$row->name."\",\"".$row->user_password."\", \"".$row->user_email."\", \"".$row->user_website."\"".
          ")";
        $result = mysql_query($queryins,$linkblogcms) or die($queryins);
        // get auto increment field value to make index
        $rowid=mysql_insert_id($linkblogcms);
        // now we can insert article to $blogcmscat[$nuketopic]
        $blogcmsauthor[strtoupper("$row->username")]=$rowid;
        // use first inserted name as a default owner of the unknown articles
           if ($i ==1) { $defaultuser = strtoupper("$row->username"); };
        // reviews are mostly done with real name, catch this
        $reviewsauthor[strtoupper("$row->name")]=$rowid;
        echo "row: ".$i++." ".$row->name." nuke ".$row->user_id.", blogcms ".$rowid." - check ".$blogcmsauthor['$row->username']."<br>";
        }
       }

      /* *************Total conversion part******************** */
      echo "<h2>Transfering posts and comments to categories...</h2>";
      $query="select sid, topic, time, title, hometext, bodytext, counter, informant  from ".$prefixwp."stories order by sid";
      $querywp=mysql_query($query,$linkwp) or die($query);
      echo "<p>rows to transfer: ".mysql_num_rows($querywp)."</p>";
      echo "<p>";
      $i=1;
      while ($row=mysql_fetch_object($querywp)) {
        echo $i++." (".$row->informant."), ";

        // insert post
        $blogauthornuke=$blogcmsauthor[strtoupper("$row->informant")];
         if (($blogauthornuke==0) || ($blogauthornuke==''))
            { $blogauthornuke= $blogcmsauthor[$defaultuser]; };
        $query=
          "insert into ".$prefixblogcms."nucleus_item ".
          "(ititle,ibody,imore,iblog,iauthor,itime,icat) values (".
          "'".addslashes($row->title)."','".addslashes(paragraph(encoding(stripslashes($row->hometext)),false))."','".addslashes(paragraph(encoding(stripslashes($row->bodytext)),false))."',1,'".$blogauthornuke."','".$row->time."',".$blogcmscat[$row->topic].")";
        $result = mysql_query($query,$linkblogcms) or die($query);
        $itemid=mysql_insert_id($linkblogcms);
        if ($np_views==1)
         {
        // Insert visited times to NP_viewed; (counter->pageviews)
        $query="insert into ".$prefixblogcms."nucleus_plugin_views (id,views) values (".$itemid.",".$row->counter.")";
        $query_views=mysql_query($query,$linkblogcms) or die($query);
        };
        // insert comments from nuke. nuke_comment.sid = story to attach comment to (nuke_story.sid)
        // nucleus_comment.citem = nuke_story.sid
        $query="select name,email,url,host_name,date,comment,score from ".$prefixwp."comments where sid=".$row->sid;
        $querywp_detail=mysql_query($query,$linkwp) or die($query);
        while ($row_detail=mysql_fetch_object($querywp_detail)) {
          $query=
            "insert into ".$prefixblogcms."nucleus_comment ".
            "(cbody,cuser,cmail,cmember,citem,ctime,cip,cblog,chost) values (".
              "'".addslashes(paragraph(encoding(strip_tags(stripslashes($row_detail->comment))),true))."',".
              "'".encoding($row_detail->name)."',".
              "'".$row_detail->email."',".
              "0,".
              "$itemid,".
              "'".$row_detail->date."',".
              "'".$row_detail->host_name."',".
              "1,".
              "'@phpnuke')";
          $result = mysql_query($query,$linkblogcms) or die($query);

        }
      }
      echo "</p>";

      echo "<h2>Converting reviews...</h2>";
        // now, convert reviews -> items, separate script, not many uses these
        // NP_Reviews is downloadable from http://forum.blogcms.com/viewtopic.php?id=582
        // Convert ratings in reviews and comments to blog:cms.
        // Insert new category "reviews" (can be changed later-on)
        // Put cover as popupimage (automatical thumbnail) + more info link
        //  to bottom of the post

        $query=
          "insert into ".$prefixblogcms."nucleus_category ".
          "(cblog,cname,iurltitle,cdesc) values (".
          "1,'Reviews".$i."','Reviews".$i."','Reviews".$i."'".
          ")";
          $result = mysql_query($query,$linkblogcms) or die($query);
        // get auto increment field value to make index
        $rowid=mysql_insert_id($linkblogcms);
        // now we can insert article to $blogcmscat[$nuketopic] - this is left with option to add more review classes
        $blogcmsrev[1]=$rowid;

      $query="select id, date, title, text, reviewer, email, hits, url, url_title, cover, score from ".$prefixwp."reviews";
      $querywp_detail=mysql_query($query,$linkwp) or die($query);
      echo "<p>Reviews to transfer: ".mysql_num_rows($querywp_detail)."</p>";
      echo "<p>";
      $i=1;

      while ($row_detail=mysql_fetch_object($querywp_detail))
      {
           echo " ".$i++." ".$row_detail->id." ";
         // same authors will do, some might however be anonymous
         $blogauthornuke=$reviewsauthor[strtoupper("$row_detail->reviewer")];
         if (($blogauthornuke==0) || ($blogauthornuke==''))
             { $blogauthornuke=$blogcmsauthor[strtoupper("$row_detail->reviewer")]; };
        // have to put default which is first added user
         if (($blogauthornuke==0) || ($blogauthornuke=='') || (!isset($blogauthornuke)))
            { $blogauthornuke= $blogcmsauthor[0]; };
         // remove (blaa blaa) from title (used in my nuke for example to clarify review format)
         // Uncomment following two lines to remove everything between "(" and ")".
           // $title =$row_detail->title;
           // if (strpos($title, "(")) { $title= substr($title, 0, strpos($title, "(")); };
         // Make more-info link (insert text if you want)
         $moreinfo = "<br /><a href=\"".$row_detail->url."\">".$row_detail->url_title."</a>";
         // picture from cover-field
         $picture="";
         if (strlen($row_detail->cover)>1)
         { if ($popupusage==1)
           { $picture = "<div class=leftbox><%Image(public/".$row_detail->cover."|||||)%></div>"; }
           else
           { $picture = "<div class=leftbox><%image(public/".$row_detail->cover."|||||)%></div>"; }
         };
         if ($np_reviews==1)
         {
          $query=
          "insert into ".$prefixblogcms."nucleus_item ".
          "(ititle,ibody,iblog,iauthor,itime,icat,irating) values (".
          "'".addslashes($title)."','".$picture."".addslashes(paragraph(encoding(stripslashes($row_detail->text)),false))."".$moreinfo."',".
          "1,".$blogauthornuke.",'".$row_detail->date."',".$blogcmsrev[1].",".$row_detail->score.")";
         }
         else
         {
          $query=
          "insert into ".$prefixblogcms."nucleus_item ".
          "(ititle,ibody,iblog,iauthor,itime,icat) values (".
          "'".addslashes($title)."','".addslashes(paragraph(encoding(stripslashes($row_detail->text)),false))."".$moreinfo."',".
          "1,".$blogauthornuke.",'".$row_detail->date."',".$blogcmsrev[1].")";
         }
         // no matter what query, just insert it to db
         $query_reviews=mysql_query($query,$linkblogcms) or die($query);
         // add view-times
         if ($np_views==1)
         {
           $itemid=mysql_insert_id($linkblogcms);
           $query="insert into ".$prefixblogcms."nucleus_plugin_views (id,views) values (".$itemid.",".$row_detail->hits.")";
           $query_reviews_views=mysql_query($query,$linkblogcms) or die($query);
         };
         // insert review_comments to nucleus_comments
         $query="select cid,rid,userid,date,comments, score from ".$prefixwp."reviews_comments where rid=".$row_detail->id;
        $query_recomm=mysql_query($query,$linkwp) or die($query);
        while ($row_comm=mysql_fetch_object($query_recomm)) {
         if ($np_reviews==1)
         {
          $query=
            "insert into ".$prefixblogcms."nucleus_comment ".
            "(cbody,cuser,cmail,cmember,citem,ctime,cip,cblog,chost,crating) values (".
              "'".addslashes(paragraph(encoding(strip_tags(stripslashes($row_comm->comments))),true))."',".
              "'".encoding($row_comm->userid)."',".
              "'',".
              "0,".
              "$itemid,".
              "'".$row_comm->date."',".
              "'',".
              "1,".
              "'@phpnuke',".$row_comm->score.")";
          } else // no np_reviews
          {
               $query=
              "insert into ".$prefixblogcms."nucleus_comment ".
            "(cbody,cuser,cmail,cmember,citem,ctime,cip,cblog,chost) values (".
              "'".addslashes(paragraph(encoding(strip_tags(stripslashes($row_comm->comments))),true))."',".
              "'".encoding($row_comm->userid)."',".
              "'',".
              "0,".
              "$itemid,".
              "'".$row_comm->date."',".
              "'',".
              "1,".
              "'@phpnuke')";

          };
          $result = mysql_query($query,$linkblogcms) or die($query);

          }
      }


      echo "<h2>It is done...</h2>";
      echo "<p>Now please login to BLOG:CMS, uninstall NP_FancyText plugin, and install it again to reset SEO URLs.</p>";
      die;
    }

    }
?>
  </p>
  <form method='post' action='./phpnuke.php'>

    <h2>Obsolete phpNuke (v6.5-7.3) Database Info</h2>
    <fieldset>
    <legend>Nuke info (works for multiple nuke installations)</legend>
      <label>Host: <input type='text' name='nukehost' size='50' value='<?php def('nukehost'); ?>' /></label><br />
      <label>Username: <input type='text' name='nukeusername' size='50' value='<?php def('nukeusername'); ?>' /></label><br />
      <label>Password: <input type='text' name='nukepassword' size='50' value='<?php def('nukepassword'); ?>' /></label><br />
      <label>Database Name (nuke): <input type='text' name='nukedatabase' size='50' value='<?php def('nukedatabase'); ?>' /></label><br />
      <label>Table Prefix: <input type='text' name='nukeprefix' size='50' value='<?php def('nukeprefix'); ?>' /></label>
    </fieldset>

    <h2>New BLOG:CMS Database Info</h2>
    <fieldset><legend>BLOG:CMS info</legend>
      <label>Host: <input type='text' name='blogcmshost' size='50' value='<?php def('blogcmshost'); ?>' /></label><br />
      <label>Username: <input type='text' name='blogcmsusername' size='50' value='<?php def('blogcmsusername'); ?>' /></label><br />
      <label>Password: <input type='text' name='blogcmspassword' size='50' value='<?php def('blogcmspassword'); ?>' /></label><br />
      <label>Database Name (blogcms): <input type='text' name='blogcmsdatabase' size='50' value='<?php def('blogcmsdatabase'); ?>' /></label><br />
      <label>Table Prefix: <input type='text' name='blogcmsprefix' size='50' value='<?php def('blogcmsprefix'); ?>' /></label>
      <p>Use NP_Views (convert viewed/read to blog:cms)<label>
        <input name="np_views" type="radio" value="1" checked="checked" />
Yes</label>
        <label>
        <input type="radio" name="np_views" value="0" />
No</label>
        <br />
        Use NP_Reviews (convert ratings from phpNuke to Blog:cms)
        <label>
        <input type="radio" name="np_reviews" value="1" />
Yes</label>
        <label>
        <input name="np_reviews" type="radio" value="0" checked="checked" />
No</label>
        <br />
        Use NP_PopupImageNetPBM/GD (uses %Image instead of %image)
        <label>
        <input type="radio" name="popupusage" value="1" />
Yes</label>

        <label>
        <input name="popupusage" type="radio" value="0" checked="checked" />
No</label>

      </p>
    </fieldset>

    <h2>Submit</h2>
    <fieldset>
      <input type='submit' value='Convert data from phpNuke into BLOG:CMS!' name='convert' />
    </fieldset>

  </form>
  </div>
</body></html>