импорт комментариев из таблицы сторонней базы данных

Главные вкладки

Аватар пользователя qman qman 30 сентября 2007 в 20:35

Всем привет,
мне нужно было перенести сайт на drupal.
гостевую на drupal реализовал как простую страницу с включенными комментариями.
Чтобы перенести текст гостевой старого сайта пришлось импортировать комментарии из таблицы MySQL в drupal. Может быть мой код кому нибудь пригодится. Часть кода скрипта взята из comment.module, import.module. сам я php кодер слабый, сильно не пинайте.
описание импортируемой таблицы slite_gb
screen_name имя гостя;
message_email email гостя;
datetime дата комментария;
message_body сообщение гостя;
message_answer ответ админа сайта;

<?php
include_once "includes/bootstrap.inc";
include_once "includes/common.inc";
include_once  "includes/database.inc";
include_once  "includes/database.mysql.inc";

function add_comment_to_node($comment) {
  global $nid; // wow. I have to pee. huh.

  // woulda liked to use the API, but the timestamp needed to be
  // the original setting, not the time of the import. some other
  // issues here and there too (invalid e-mails that had been
  // accepted, the check for whether comments were enabled, etc.)
  db_query("INSERT INTO {comments} (cid, nid, pid, uid, subject, comment, hostname, ".
           "timestamp, status, score, users, thread, name, mail, homepage) VALUES ".
           "(%d, %d, %d, %d, '%s', '%s', '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
           $comment['cid'], $nid, $comment['pid'], $comment['uid'], $comment['title'], $comment['comment'], $comment['remote_addr'], $comment['timestamp'], 0, 0, "a:1:{i:0;i:0;}", $comment['thread'],
           $comment['name'], $comment['email'], $comment['URL']);
}

function format_comment ($thread, $cid, $comment, $timestamp, $email, $URL, $name ){
  $comment['thread']  = $thread;
  $comment['cid']     = $cid;
  print "<b>comment = $comment</b></br>";
  $comment['comment'] = $comment;
  $comment['timestamp'] = $timestamp;
  $comment['email'] = $email;
  $comment['URL'] = $URL;
  $comment['name'] = $name;
 return ($comment);
}

function get_thread($thread, $pid)
{
 global $nid;
        if ($pid == 0) {
          // This is a comment with no parent comment (depth 0): we start
          // by retrieving the maximum thread level.
          $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $nid));

          // Strip the "/" from the end of the thread.
          $max = rtrim($max, '/');

          // Finally, build the thread field for this new comment.
          $thread = int2vancode(vancode2int($max) + 1) .'/';
        }
        else {
          // This is comment with a parent comment: we increase
          // the part of the thread value at the proper depth.

          // Get the parent comment:
          $parent = _comment_load($pid);

          // Strip the "/" from the end of the parent thread.
          $parent->thread = (string) rtrim((string) $parent->thread, '/');

          // Get the max value in _this_ thread.
          $max = db_result(db_query("SELECT MAX(thread) FROM {comments} WHERE thread LIKE '%s.%%' AND nid = %d", $parent->thread, $nid));

          if ($max == '') {
            // First child of this parent.
            $thread = $parent->thread .'.'. int2vancode(0) .'/';
          }
          else {
            // Strip the "/" at the end of the thread.
            $max = rtrim($max, '/');

            // We need to get the value at the correct depth.
            $parts = explode('.', $max);
            $parent_depth = count(explode('.', $parent->thread));
            $last = $parts[$parent_depth];

            // Finally, build the thread field for this new comment.
            $thread = $parent->thread .'.'. int2vancode(vancode2int($last) + 1) .'/';
          }
        }
  return ($thread);
}

ini_set('display_errors', TRUE);

include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_maintenance_theme();

$nid=4;//номер страницы к которой добавляем комментарии
$user_id=4;//id пользователя

//$a = db_fetch_array(db_query("SELECT last_comment_timestamp, last_comment_name, comment_count FROM
$result = db_query("SELECT * FROM {slite_gb} ORDER BY `id` ");
while ($a = db_fetch_object($result))
{
  print "<br>id=".$a->id;
  print "<br>parent_id=".$a->parent_id;
  print "<br>screen_name=".$a->screen_name;
  print "<br>screen_subname=".$a->screen_subname;
  print "<br>datetime=".$a->datetime;
  print "<br>message_email=".$a->message_email;
  print "<br>message_body=".$a->message_body;
  print "<br>message_answer=".$a->message_answer."</br></br></br>";
  $thread = get_thread(0, 0);

  $comment_cid = db_next_id("{comments}_cid");
//добавляем комментарий гостя
  $comment['thread']  = $thread;
  $comment['cid']     = $comment_cid;
  $comment['uid']     = 0;//для анонимуов Shok
  $comment['pid']     = 0;
  $comment['comment'] = $a->message_body;
  $comment['timestamp'] = $a->datetime;
  $comment['email'] = $a->message_email;
  $comment['URL'] = "";
  $comment['name'] = $a->screen_name;

  add_comment_to_node($comment);

 if (($a->message_answer)<>"") {
print "<b>Answer Exist</b>";

  $thread = get_thread(0, $comment_cid);
//если существует ответ админа сайта, добавляем его
  print "thread = $thread<br>";
  $comment['thread']  = $thread;
  $comment['pid']     = $comment_cid;
  $comment['uid']     = $user_id;
  print "<b>comment_cid=$comment_cid</b></br>";
  $comment['cid']     = db_next_id("{comments}_cid");
  $comment['comment'] = $a->message_answer;
  $comment['timestamp'] = $a->datetime;
  $comment['email'] = $a->message_email;
  $comment['URL'] = "";
  $comment['name'] = "admin";
  add_comment_to_node($comment);
}
}
?>

P.S. написано это все для себя. т.к. память совсем плохая. Но надеюсь кому нибудь пригодится.