<?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__);

define('DS', DIRECTORY_SEPARATOR);

/**
 * 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'] = 'dname';
$storeConfig['username'] = 'duser';
$storeConfig['password'] = 'pass';
$storeConfig['tablePrefix'] = 'g2_';
$storeConfig['columnPrefix'] = 'g_';

/**
 * Get the following value from config.php by searching -> data.gallery.base
 */
$galleryAlbPath = "/home/gallery/g2data/";

pageheader("Import Albums from Menalto Gallery2");

echo <<<EOT
<style>
.error {
    color: #FF0000;
    font-weight: bold;
}
.success {
    color: #00FF00;
    font-weight: bold;
}
</style>
EOT;

//We need to flush periodically, so output buffering disabled.
ob_end_flush();

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"/>
        <td class="tableb" width="40%">Albums from G2 : </td>
        <td class="tableb" width="60%">
        <select name="galAlbum">$optionStr</select>
        </td>
        </tr>
        <tr>
        <td class="tableb" colspan="2">Import sub-albums of selected album: <input type="checkbox" name="subAlbums" value="Y" /></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 ($_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 Gallery 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($albId, $albDir, $albName)= explode ('^', $_POST['galAlbum']);
  $albDir = ($albDir == 'Base') ? '' : $albDir;
  
  function getParents($galAlbum){
    global $cp, $tp, $link;
    $query = "SELECT 
                ce.{$cp}parentId, fse.{$cp}pathComponent 
              FROM 
                {$tp}ChildEntity AS ce JOIN {$tp}FileSystemEntity AS fse
              ON 
                fse.{$cp}id = ce.{$cp}parentId
              WHERE 
                ce.{$cp}id = '$galAlbum'";
    $result = mysql_query($query, $link);

    $parentrow = mysql_fetch_array($result, MYSQL_NUM);
    mysql_free_result($result);
    return $parentrow;
  }

  $theAlbum = $albId;
  do 
  {
    $parent = getParents($theAlbum);
    $theAlbum = $parent[0];
    if ($parent[1] != "") {
      $parent[1] .= DS.$parentFilePath;
      $parentFilePath = $parent[1];   
    }
  } while ($parent[0] > 0);
 
  $albumsArr[$albId] = array('name' => $albName, 'gallery_path' => $parentFilePath.DS.$albDir, 'cpg_alb' => ($albDir == '') ? 'Base' : $albDir);
  
  //If user has opted to get the sub-albums as well, get the names and id's of all the sub-albums.
  //Remember this can nest to any level.
  if (isset($_POST['subAlbums'])) {
    //Get the directory name for the selected album
    $query = "SELECT {$cp}pathComponent
                FROM {$tp}FileSystemEntity
                WHERE {$cp}id = $albId;
             ";
    $result = mysql_query($query, $link);
    $row = mysql_fetch_array($result, MYSQL_NUM);
    $parentFilePath .= $row[0].DS;
    function getSubAlbums($albId, $path) {
        global $albumsArr, $cp, $tp, $link, $albName;
        
        $query = "SELECT i.{$cp}id, fs.{$cp}pathComponent, i.{$cp}title
            FROM
              {$tp}Item i, {$tp}FileSystemEntity fs, {$tp}ChildEntity ce
            WHERE
              i.{$cp}canContainChildren = 1 AND
              i.{$cp}id = fs.{$cp}id AND
              ce.{$cp}parentId = $albId AND
              ce.{$cp}id = i.{$cp}id
           ";
        $result = mysql_query($query, $link);
        
        if (mysql_num_rows($result)) {
            //$path = '';//$albumsArr[$albId]['path'];
            while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
                $albumsArr[$row[0]]['name'] = $row[2];
                $albumsArr[$row[0]]['cpg_alb'] = $row[1];

                //echo $path . $row[1].DS."<br />";
                $albumsArr[$row[0]]['gallery_path'] = $path . $row[1].DS;
                getSubAlbums($row[0], $path . $row[1].DS);
            }
        }
    }
    getSubAlbums($albId, $parentFilePath);
    
    echo "<br />Total number of albums to import: <b>".count($albumsArr)."</b><br />";
    flush();
  }
  print_r($albumsArr);
  
  foreach ($albumsArr as $galAlbum => $row) {
    $albumName = $row['name'];
    $albPath = $row['cpg_alb'];
    $gallery_album_path = $row['gallery_path'];
    if (!@mkdir ($CONFIG['fullpath'].DS.$albPath, octdec($CONFIG['default_dir_mode']))) {
        echo "<br />Unable to create album directory. Directory with the same name <b>".$CONFIG['fullpath'].$albPath."</b> already exists. <span class='error'>Skipping album $albumName</span> ...<br />";

        flush();
        continue;
    }
    
    echo "<br />Directory <b>$albPath</b> for album <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 /><span class='success'>Album $albTitle created</span><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)) {
            echo "<br />No photos found in album $albumName<br />";
            continue;
        }
        while ($row = mysql_fetch_array($result)) {
            set_time_limit(50);
            $itemid = $row["{$cp}id"];
            $imageFullName = $row["{$cp}pathComponent"];
            $imageTitle = addslashes($row["{$cp}title"]);
            $imageCaption = addslashes($row["{$cp}description"]);
            $viewCount = $row["{$cp}viewCount"];
        
            $source = $galleryAlbPath.'albums'.DS;
            $source .= ($albumName != 'Base') ? "$gallery_album_path".DS : '';
            $source .= $imageFullName;
            $target = $CONFIG['fullpath'].$albPath.DS."$imageFullName";
            //echo "<BR>IMAGE: SRC -> $source&nbsp;&nbsp;&nbsp;TGT -> $target<BR>";
            //flush();
        
            copy($source, $target);
        
            //Call add_picture
            $result1 = add_picture ($aid, $albPath."/", $imageFullName, 0, $imageTitle, $imageCaption, $imageKeywords, '', '', '', '', 0, $raw_ip, $hdr_ip, 0, 0, $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 = addslashes($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 /><span class='error'>Unable to insert file <B>$imageFullName</B>. Skipping...</span><br />";
                flush();
            }
        }
        echo "<BR><span class='success'>Successfully imported album <b>$albumName</b> from Gallery2 to Coppermine</span><hr />";
        flush();
    } else {
        echo "<br /><span class='error'>Unable to create album in database.</span> $query<br />";
    }
  } //end of foreach
  endtable();
}
  
$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());
}

//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, i.{$cp}title, 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)) {
  $albumDir = $row[2] ? $row[2] : 'Base';
  $albName = addslashes($row[1]);
  $optionStr .= "<option value=\"$row[0]^$albumDir^$albName\">{$row[1]}</option>";
}

mysql_free_result($result);
form_gallery_album($optionStr);
mysql_close($link);

pagefooter();
?>
