<?php
/*
 +--------------------------------------------------------------------+
 | CiviCRM version 1.7                                                |
 +--------------------------------------------------------------------+
 | Copyright CiviCRM LLC (c) 2004-2007                                |
 +--------------------------------------------------------------------+
 | This file is a part of CiviCRM.                                    |
 |                                                                    |
 | CiviCRM is free software; you can copy, modify, and distribute it  |
 | under the terms of the Affero General Public License Version 1,    |
 | March 2002.                                                        |
 |                                                                    |
 | CiviCRM is distributed in the hope that it will be useful, but     |
 | WITHOUT ANY WARRANTY; without even the implied warranty of         |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
 | See the Affero General Public License for more details.            |
 |                                                                    |
 | You should have received a copy of the Affero General Public       |
 | License along with this program; if not, contact CiviCRM LLC       |
 | at info[AT]civicrm[DOT]org.  If you have questions about the       |
 | Affero General Public License or the licensing  of CiviCRM,        |
 | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
 +--------------------------------------------------------------------+
*/

define('PROCESS_ROWS', 250);

if (!ini_get("safe_mode")) {
  set_time_limit(180);
}



$conf_dir = conf_init();
$settings = $conf_dir . '/settings.php';

include_once $settings;

ini_set('session.save_handler', 'files');
ini_set('session.use_only_cookies', 0);

session_start();

function db_connect_mysql($url) {
  $url = parse_url($url);

  // Allow for non-standard MySQL port.
  if (isset($url['port'])) {
     $url['host'] = $url['host'] .':'. $url['port'];
  }

  $connection = mysql_connect($url['host'], $url['user'], $url['pass'], TRUE) or die(mysql_error());
  mysql_select_db(substr($url['path'], 1)) or die('unable to select database');

  return $connection;
}

function conf_init() {
  static $conf = '';

  if ($conf) {
    return $conf;
  }

  $confdir = 'sites';
  $uri = explode('/', $_SERVER['PHP_SELF']);
  $server = explode('.', rtrim($_SERVER['HTTP_HOST'], '.'));
  for ($i = count($uri) - 1; $i > 0; $i--) {
    for ($j = count($server); $j > 0; $j--) {
      $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
      if (file_exists("$confdir/$dir/settings.php")) {
        $conf = "$confdir/$dir";
        return $conf;
      }
    }
  }

  $conf = "$confdir/default";
  return $conf;
}

$authorized = FALSE;
$session_id = session_id();  

$drupal_db_url = is_array($db_url) ? $db_url['default'] : $db_url;

$conn = db_connect_mysql($drupal_db_url);

if ($row = mysql_fetch_object(mysql_query("SELECT * FROM ". $db_prefix ."sessions WHERE uid = 1 AND sid = '".  htmlspecialchars($session_id) ."'", $conn))) {
  $authorized = TRUE;
}
else {
  if ($row = mysql_fetch_object(mysql_query("SELECT * FROM ". $db_prefix ."variable WHERE name = 'update_session_id'", $conn))) {
    if ($session_id == unserialize($row->value)) {
      $authorized = TRUE;
    }
  }
}

if (!$authorized) {
  header('HTTP/1.0 403 Forbidden');
  print "There was an authorization error when running the DrupalUser-to-CiviCRM synchronization script.";
  exit;
}

// to prevent browser timeouts, perform queries in small chunks
$count = mysql_fetch_object(mysql_query("SELECT COUNT(*) AS rows FROM ". $db_prefix ."users WHERE mail != ''"));
$last = (int)$_GET['last'];
if ($count->rows > PROCESS_ROWS) {
  $next = $last + PROCESS_ROWS;
  if ($next < $count->rows) {
    // we have more to process, immediately reload page when finished
    header('refresh: 0; ?last='. $next);
  }
  else {
    $done = (int)$_GET['done'];
    if ($done) {
      echo "Successfully updated $count->rows contacts, processing complete.";
      exit;
    }
    else {
      // finish gracefully, let the user know we're done
      header('refresh: 0; ?last='. $next .'&done=1');
    }
  }
  echo "Processing $count->rows users, this web page will automatically reload.  Please be patient...<br />";
}

$users2civicrm_script = "  \n
                           require_once '". $conf_dir ."/civicrm.php';\n
                           require_once './modules/civicrm/packages/DB.php';\n
                           require_once './modules/civicrm/CRM/Core/Config.php';\n
                           require_once './modules/civicrm/CRM/Core/BAO/UFMatch.php';\n
                           \n
                           function user_access( \$string ) {\n
                             return true;\n
                           }\n
                           \n
                           function module_list() {\n
                             return array();\n
                           }\n
                           \n
                           \$config =& CRM_Core_Config::singleton( );\n
                           \n
                           \$dsn_drupal  = '". $drupal_db_url ."';\n
                           \n
                           \$db_drupal = DB::connect(\$dsn_drupal);\n
                           \n
                           if ( DB::isError( \$db_drupal ) ) {\n
                             die( 'Cannot connect to drupal db via \$dsn, ' . \$db_drupal->getMessage( ) );\n
                           }\n
                           \n
                           \$sql = 'SELECT uid,mail FROM users WHERE mail != \'\' LIMIT '. $last .', '. PROCESS_ROWS;\n
                           \$query = \$db_drupal->query( \$sql );\n
                           \n
                           \$user  = null;\n
                           \$uf    = 'Drupal';\n
                           \$counter = $last;\n
                           \n
                           while ( \$row = \$query->fetchRow( DB_FETCHMODE_ASSOC ) ) {\n
                             \$counter++;\n
                             echo \$counter .': Processing \''. \$row['mail'] .'\'';\n
                             if ( CRM_Core_BAO_UFMatch::synchronizeUFMatch( \$user, \$row['uid'], \$row['mail'], \$uf ) ) {\n
                               echo \": created contact for user.<br />\\n\";\n
                             }\n
                           }\n
                           \n
                           \$db_drupal->disconnect( );\n
                           \n
                         ";

eval($users2civicrm_script);  

?>
