<?php
/**
 * import_gallery2.php - Script to export Menalto Gallery2 to Coppermine 1.3.x and 1.4.x
 *
 * To install and use simply -
 * 1. put this file in the same directory as your coppermine installation,
 * 2. Enter the Gallery2 config parameters below and save the file with .php extension
 * 3. login as admin and access it using your browser
 * 4. Follow the instructions on screen
 *
 * Tested with Gallery 2 stable
 *
 * @copyright Aditya Mooley <adityamooley@sanisoft.com>, Tarique Sani <tarique@sanisoft.com>
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License
 *
 */

define('IN_COPPERMINE', true);

require('include/init.inc.php');
require('include/picmgmt.inc.php');

if (!GALLERY_ADMIN_MODE) cpg_die(ERROR, $lang_errors['access_denied'], __FILE__, __LINE__);

/**
 * Menalto Gallery2 config values
 * Enter the values from config.php (You can find this file in gallery2's root folder)
 * Search for $storeConfig in the file and enter the correct values below
 */
$storeConfig['type'] = 'mysql';
$storeConfig['hostname'] = 'localhost';
$storeConfig['database'] = 'gallery2';
$storeConfig['username'] = 'root';
$storeConfig['password'] = '';
$storeConfig['tablePrefix'] = 'g2_';
$storeConfig['columnPrefix'] = 'g_';

/**
 * Get the following value from config.php by searching -> data.gallery.base
 * This must be the value after last slash.
 * ex. if value is -> /home/httpd/html/gallery2/g2images then enter just -> gallery2
 */
$galleryAlbPath = "g2images";

pageheader("Import Albums from Menalto Gallery2");
//We need to flush periodically, so output buffering disabled.
ob_end_flush();
//Function to draw the gallery path form
function form_gallery_path()
{
    global $HTTP_POST_VARS;
    $path = $_SERVER['DOCUMENT_ROOT'];
    //echo $path;
    $login_falied =
    starttable('-1', "Enter path for Menalto Gallery2 to be imported", 2);
      if (isset($HTTP_POST_VARS['gallery_album'])) {
          $invalid_path = "<tr><td class='tableh2' colspan='2' align='center'>
                   <font color='red' size='1'>Invalid path entered.</font></td></tr>
           ";
      }
    echo <<<EOT
      $invalid_path
      <tr>
        <td colspan="2" class="tablef">
          We tried to find out the webroot of your gallery install, just put the name of the gallery install folder below.<br />
          If the path given below is not correct, enter the complete path.
        </td>
      </tr>
      <tr>
        <form method="post" action="">
        <input type="hidden" name="gallery_album" value="gallery_album"/>
        <td class="tableb" width="40%">Path : </td>
        <td class="tableb" width="60%"><input type="text" class="textinput" name="gallery_path" size="50" value="$path" /></td>
        </tr>
        <tr>
        <td class="tablef" colspan="2" align="center"><input type="submit" class="button" name="submit" value="Get Albums" />
        </form>
     </tr>

EOT;
      endtable();
}

function form_gallery_album($optionStr)
{
  starttable('-1', "Select album from Menalto Gallery2 to be imported to Coppermine", 2);
  echo <<<EOT
    <tr>
              <form method="post" action="">
              <input type="hidden" name="select_album" value="select_album"/>
              <input type="hidden" name="gallery_path" value="{$_POST['gallery_path']}"/>
              <td class="tableb" width="40%">Albums from G2 : </td>
              <td class="tableb" width="60%">
                <select name="galAlbum">$optionStr</select>
              </td>
             </tr>
             <tr>
              <td class="tablef" colspan="2" align="center"><input type="submit" class="button" name="submit" value="Import" />
              </form>
     </tr>

EOT;
  endtable();
}

$valid = false;
$showAlbums = false;
if (isset($HTTP_POST_VARS['gallery_album'])) {
  $galDir = $HTTP_POST_VARS['gallery_path'];
  if (is_dir($galDir) && is_file("$galDir/config.php")) {
    $valid = true;
    $showAlbums = true;
  }
} elseif ($_POST['select_album']) {
  //Process the album selected
  $galleryPath = $_POST['gallery_path'];

  $tp = $storeConfig['tablePrefix'];
  $cp = $storeConfig['columnPrefix'];
  if ($storeConfig['type'] != 'mysql') {
    cpg_die(ERROR, 'Currently we support only MySQL database for importing');
  }

  $link = mysql_connect($storeConfig['hostname'], $storeConfig['username'], $storeConfig['password'], true);
  if (!$link) {
    cpg_die(ERROR, 'Could not connect to database: MySQL Said: '.mysql_error());
  }

  if (!mysql_select_db($storeConfig['database'], $link)) {
    cpg_die(ERROR, 'Could not select the gallery database: MySQL Said: '.mysql_error());
  }

  list($galAlbum, $albumName)= explode ('^', $_POST['galAlbum']);
  if (!@mkdir ($CONFIG['fullpath']."/".$albumName, 0777)) {
    echo "<br />Unable to create album directory. Directory with the same name <b>".$CONFIG['fullpath'].$albumName."</b> already exists. Exiting ...<br />";
    endtable();
    pagefooter();
    flush();
    exit;
  }
  echo "<br />Album directory <b>$albumName</b> created... <br />";
  flush();

  //Get title and description from G2
  $query = "SELECT {$cp}title, {$cp}description FROM {$tp}Item WHERE {$cp}id = '$galAlbum'";
  $result = mysql_query($query);
  if (!mysql_num_rows($result)) {
    cpg_die(ERROR, "Selected Album <B>$galAlbum</B> Not Found");
  }
  $row = mysql_fetch_array($result, MYSQL_NUM);
  mysql_free_result($result);

  $query = "INSERT INTO {$CONFIG['TABLE_ALBUMS']} SET title='".addslashes($row[0])."', description='".addslashes($row[1])."'";
  mysql_query($query, $CONFIG['LINK_ID']);

  if ($result) {
    //Get the aid for the newly created album
    $aid = mysql_insert_id($CONFIG['LINK_ID']);
    mysql_free_result($result);
    echo "<br />Album $albTitle created...<br />";
    echo "Importing images <br />";
    flush();

    //Get all the photos in this album. Leave the sub albums
    $query = "SELECT
                i.*, fs.{$cp}pathComponent, ia.{$cp}viewCount
              FROM
                {$tp}Item i, {$tp}ChildEntity ce, {$tp}FileSystemEntity fs, {$tp}ItemAttributesMap ia
              WHERE
                ce.{$cp}id = i.{$cp}id AND
                i.{$cp}id = fs.{$cp}id AND
                ia.{$cp}itemId = i.{$cp}id AND
                ce.{$cp}parentId = '$galAlbum' AND
                i.{$cp}canContainChildren = 0";
    echo "<BR>Q: $query<BR>";
    $result = mysql_query($query, $link);
    if (!mysql_num_rows($result)) {
      cpg_die(ERROR, 'No Photos in the album');
    }
    while ($row = mysql_fetch_array($result)) {
      $itemid = $row["{$cp}id"];
      $imageFullName = $row["{$cp}pathComponent"];
      $imageTitle = $row["{$cp}title"];
      $imageCaption = $row["{$cp}description"];
      $viewCount = $row["{$cp}viewCount"];

      $source = "$galleryPath/$galleryAlbPath/albums/";
      $source .= ($albumName != 'Base') ? "$albumName/" : '';
      $source .= $imageFullName;
      $target = $CONFIG['fullpath'].$albumName."/$imageFullName";
      //echo "<BR>IMAGE: SRC -> $source&nbsp;&nbsp;&nbsp;TGT -> $target<BR>";
      flush();

      @copy($source, $target);

      //Call add_picture
      $result1 = add_picture ($aid, $albumName."/", $imageFullName, '', $imageTitle, $imageCaption, $imageKeywords, '', '', '', '', 0, $raw_ip, $hdr_ip, $viewCount);

      if ($result1) {
        echo "<br />File <b>$imageFullName</b> Inserted.<br />";
        flush();
        //Picture inserted successfully.
        $pid = mysql_insert_id($CONFIG['LINK_ID']); //Picture id of the recently inserted picture. We need this for inserting comments for this picture.

        //See whether this item has any comments in G2.
        $query = "SELECT c.{$cp}id
                  FROM
                    {$tp}ChildEntity c, {$tp}Entity e
                  WHERE
                  c.{$cp}id = e.{$cp}id AND
                  e.{$cp}entityType = 'GalleryComment' AND
                  {$cp}parentId = '$itemid'";
        echo "<BR>Q: $query<BR>";
        $result1 = mysql_query($query, $link);
        if (mysql_num_rows($result1)) {
          $comArr = array();
          while ($com = mysql_fetch_array($result1, MYSQL_NUM)) {
            $comArr[] = $com[0];
          }
          $comStr = implode(',', $comArr);
          $query = "SELECT c.*, u.{$cp}userName
                    FROM
                      {$tp}Comment c LEFT JOIN {$tp}User u
                    ON
                      c.{$cp}commenterId = u.{$cp}id
                    WHERE
                      c.{$cp}id IN ($comStr)
                  ";
          echo "<BR>Q: $query<BR>";
          $result1 = mysql_query($query);
          if (mysql_num_rows($result1)) {
            //Some comments are available. Get them and put in database.
            while ($comRow = mysql_fetch_array($result1)) {
              $commentText = addslashes($comRow["{$cp}comment"]);
              $name = $comRow["{$cp}userName"];
              $datePosted = date("Y-m-d H:i:s", $comRow["{$cp}date"]);
              $IPNumber = $comRow["{$cp}host"];

              $query = "INSERT INTO {$CONFIG['TABLE_COMMENTS']} (pid, msg_author, msg_body, msg_date, msg_raw_ip, msg_hdr_ip) VALUES ('$pid', '$name', '$commentText', '$datePosted', '$IPNumber', '$IPNumber')";
              echo "<BR>Q: $query<BR>";
              $result2 = cpg_db_query($query);

              if ($result2) {
                echo "<br />Comment Inserted.<br /><hr />";
              } else {
                echo "<br />Unable to insert comment. Skipping...<br /><br /><hr />";
              }
            }
          }
        }
      } else {
        echo "<br />Unable to insert file <B>$imageFullName</B>. Skipping...<br />";
        flush();
      }
    }
    echo "<BR>Successfully imported album <b>$albumName</b> from Gallery2 to Coppermine<br>";
    endtable();
    pagefooter();
    flush();
    exit;
  } else {
    echo "<br />Unable to create album in database. Exiting ...<br /> $query";
    endtable();
    pagefooter();
    flush();
    exit;
  }
}

if (!$valid) {
  form_gallery_path();
} elseif ($showAlbums) {
  //Correct path entered, try to connect to database and fetch all the albums

  $tp = $storeConfig['tablePrefix'];
  $cp = $storeConfig['columnPrefix'];
  if ($storeConfig['type'] != 'mysql') {
    cpg_die(ERROR, 'Currently we support only MySQL database for importing');
  }

  $link = mysql_connect($storeConfig['hostname'], $storeConfig['username'], $storeConfig['password']);
  if (!$link) {
    cpg_die(ERROR, 'Could not connect to database: MySQL Said: '.mysql_error());
  }

  if (!mysql_select_db($storeConfig['database'], $link)) {
    cpg_die(ERROR, 'Could not select the gallery database: MySQL Said: '.mysql_error());
  }

  //echo "<br />Database opned successfully, generating album list<br />";
  //flush();
  //Get the id of dafault album
  $query = "SELECT {$cp}id FROM {$tp}ChildEntity WHERE {$cp}parentId = 0";
  $result = mysql_query($query, $link);
  $row = mysql_fetch_array($result, MYSQL_NUM);
  $parentAlbum = $row[0];
  mysql_free_result($result);

  $query = "SELECT i.{$cp}id, fs.{$cp}pathComponent
            FROM
              {$tp}Item i, {$tp}FileSystemEntity fs
            WHERE
              i.{$cp}canContainChildren = 1 AND
              i.{$cp}id = fs.{$cp}id
           ";
  $result = mysql_query($query, $link);
  $albumArr[$parentAlbum] = 'Base';
  $optionStr = '';
  while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    $albumName = $row[1] ? $row[1] : 'Base';
    $optionStr .= "<option value='$row[0]^$albumName'>$albumName</option>";
  }
  mysql_free_result($result);
  form_gallery_album($optionStr);
  mysql_close($link);
}
pagefooter();
?>