<?php
// ; $Id: phpbb2privatemsg.module,v 1.21 2009/10/03 17:35:02 nbz Exp $

/**
 * Implementation of hook_menu()
 */
function phpbb2privatemsg_menu() {
  $items = array();

  $items['admin/phpbb2privatemsg'] = array(
    'title' => 'phpBB to Privatemsg',
    'access callback' => 'user_access',
    'access arguments' => array('migrate phpBB'),
    'page callback' => 'phpbb2privatemsg_main', 
  );
    $items['admin/phpbb2privatemsg/cleanup'] = array(
    'title' => 'Cleanup',
    'access callback' => 'user_access',
    'access arguments' => array('migrate phpBB'),
    'page callback' => 'phpbb2privatemsg_cleanup', 
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Callback admin/phpbb2drupal
 */
function phpbb2privatemsg_main() {
  $output .= '<p>';
  $output .= t('This module imports private messages from phpBB to Drupal. It uses settings and data from the main phpbb2drupal module. Before importing Private Messages, you must:');
  $output .= '</p>';
  $output .= '<ol><li>';
  $output .= l(t('Check import settings'), 'admin/settings/phpbb2drupal');
  $output .= '</li>';
  $output .= '<li>';
  $output .= t('Import atleast user data from phpBB using the <a href="@phpbb2drupal">phpbb2drupal</a> module if you have not already done so', array('@phpbb2drupal' => url('admin/phpbb2drupal/execute')));
  $output .= '</li>';
  $output .= '<p>';
  $output .= t('In cases where either recipients or senders of a message have NOT had their user data already imported into Drupal, that message will be lost.');
  $output .= '</p>';

  if (!variable_get('phpbb2drupal_ready', 0)) {
    return '<p>'. t('the phpBB2Drupal settings. Please <a href="@settings">complete the setup first</a>', array('@settings' => url('admin/settings/phpbb2drupal'))) .'</p>';
  }
  if (variable_get('phpbb2privatemsg_import_successful', 0) == 1) { 
    return t('Private Messages have already been imported. You can now <a href="@cleanup">clean up</a> any variables set by this module and deactivate/uninstall it.', array('@cleanup' => url('admin/phpbb2privatemsg/cleanup')));
  }

  $pre = variable_get('phpbb2drupal_table_prefix', 'phpbb_');
  $tables = array($pre .'privmsgs', $pre .'privmsgs_to');
  $result = _phpbb2drupal_check_tables($tables, 'phpbb', 0);
  $output .= $result['html'];
	  
  if ($result['result'] != 1) {
    $output .= '<p class="marker">';
    $output .= t('Please use the correct database settings!');
    $output .= '</p>';
  }
  else{
    $output .= drupal_get_form('phpbb2privatemsg_migrate_form');
  }
  return $output;
}

function phpbb2privatemsg_migrate_form() {
  _phpbb2drupal_db_connect() ;
  // Causes problems with form api redirect
  //ini_set('display_errors', TRUE);

  // Adjust how long you want the script to run...
  if (!ini_get('safe_mode')) {
    set_time_limit(variable_get('phpbb2drupal_time_limit', 0));
  }

  $form['import'] = array(
    '#type' => 'hidden',
    '#title' => t('Import Private Messages'),
    '#options' => 'pm',
  );
  $form[] = array(
    '#type' => 'submit',
    '#value' => t('Import Private Messages'),
  );
  return $form;
}

function phpbb2privatemsg_migrate_form_submit($form, $form_state) {
  if (isset($form_state['values']['import'])) {  
      phpbb2privatemsg_import();
  }
}

/**
 * Private Message Import Functions
 */
function phpbb2privatemsg_import() {
  $pre = variable_get('phpbb2drupal_table_prefix', 'phpbb_');
  $format = variable_get('phpbb2drupal_input_format', 0);
  if (variable_get('phpbb2privatemsg_import_successful', 0) == 1) {
    return t('Messages have already been imported successfully.');
  }
  db_set_active('phpbb');
  $query = "SELECT * FROM %sprivmsgs ORDER BY msg_id ASC";
  $messages = db_query($query, $pre);
  
  db_set_active('default');
  while ($pm = db_fetch_object($messages)) {    
    $from = db_result(db_query('SELECT uid FROM {phpbb2drupal_temp_user} WHERE user_id = %d', $pm->author_id));
    // don't import private messages from or to users who are not imported.
    if ($from) {
      // remove the bbcode_uid from post_text
      if(!empty($pm->bbcode_uid)) {
        $pm->message_text = preg_replace("/:$pm->bbcode_uid/", '', $pm->message_text);
      }
      $pm->message_text = _phpbb2drupal_strip_bbcode($pm->message_text);
      $pm->message_text = _phpbb2drupal_text_sanitise($pm->message_text);
      $pm->message_text = _phpbb2drupal_replace_links($pm->message_text);
      $pm->message_subject = _phpbb2drupal_text_sanitise($pm->message_subject);
      
        // Borrow and adapt  code from patch to upgrade privatemsg module to Drupal 6 (http://drupal.org/node/202348#comment-700061).
        $message = array(
          'author' => $from,
          'subject' => substr($pm->message_subject, 0, 64),
          'body' => $pm->message_text,
          'timestamp' => $pm->message_time,
        );

	    //save message if no duplicates
	    $dupe = db_result(db_query('SELECT COUNT(*) FROM {pm_message} WHERE author = %d AND timestamp = %d', $message['author'], $message['timestamp']));
	    if (!($dupe)) {

        $result = drupal_write_record('pm_message', $message);
        $message['mid'] = db_last_insert_id('pm_message', 'mid');

        // Fix the message threading.
        if ($pm->root_level <> 0) {
          // This message is part of an existing thread.
          $message['thread_id'] = db_result(db_query('SELECT thread_id FROM {phpbb2privatemsg} WHERE msg_id = %d', $pm->root_level));
        }
        else {
          $message['thread_id'] = $message['mid'];
        }

        $result = db_query('INSERT INTO {phpbb2privatemsg} (mid, thread_id, msg_id) VALUES (%d, %d, %d)', $message['mid'], $message['thread_id'], $pm->msg_id);

        //insert index record for the author and all recipients of a message.
        db_set_active('phpbb');
        $query = "SELECT * FROM %sprivmsgs_to  WHERE msg_id = %d ORDER BY msg_id ASC";
        $result = db_query($query, $pre, $pm->msg_id);
        db_set_active('default');
        while ($index = db_fetch_object($result)) {
          // Fill in appropriate fields.
          $message['uid'] = db_result(db_query('SELECT uid FROM {phpbb2drupal_temp_user} WHERE user_id = %d', $index->user_id));
          $message['is_new'] = $index->pm_unread;
          $message['deleted'] = $index->pm_deleted;
          
          //Save to the index.
          $save = drupal_write_record('pm_index', $message);
        }
	    }
    }
  }
  variable_set('phpbb2privatemsg_import_successful', 1);
  drupal_set_message(t('Private Message Import successful'));
}

function phpbb2privatemsg_cleanup() {

  variable_del('phpbb2privatemsg_import_successful');
  return '<p>'. t('phpbb2privatemsg settings removed.') .'</p>';

}