<?php

/**********************************************************************
 * Copyright (C) 2006 The Wikigraphe Team
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * any later version.
 *
 * This program 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
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * See also http://www.fsf.org
 *********************************************************************/
require_once('conf/conf.php');
require_once('lib/validation.php');
require_once('model/node.php');
require_once('lib/image_resize.php');

/* This is the control script that is run in order to save the image. */
if (isset($_POST['image_save'])) {
  // Save the image
  if (save_image_file()) {
    header('Location: index.php?view=display&title='.$_POST['title']);
  }
}

/**
 * Uploads the image file.
 * 
 * @return true if the image was uploaded successfuly
 */
function save_image_file() {
  global $_FILES;
  global $_POST;
  
  /** Check if image needs to be changed. */
  if (!empty($_FILES['uploadedfile']['name'])) {
    if (preg_match(ALLOWED_FILE_EXT, $_FILES['uploadedfile']['name'], $matches)) {
       if (($pos = strrpos($_FILES['uploadedfile']['name'], ".")) === FALSE) {
           trigger_error("Error - file doesn't have a dot... weird.", E_USER_ERROR);
       } else {
           $extension = substr($_FILES['uploadedfile']['name'], $pos + 1);
       }
       /* Check if image has the right size. */
       /*
       list($width, $height, $type, $attr) = getimagesize($_FILES['uploadedfile']['tmp_name']);
       if ($width > MAX_IMAGE_WIDTH || $height > MAX_IMAGE_HEIGHT) {
         trigger_error("Image size (".$width."x".$height. ") is too large, should be a maximum of " . MAX_IMAGE_WIDTH . "x" . MAX_IMAGE_HEIGHT . ".", E_USER_ERROR);
         return false;
       } else { */
       	 if (save_uploaded_image_file($_POST['title'], $extension) !== FALSE) {
           return TRUE;
         }
       /* } */
     } else {
        trigger_error("Illegal or unknown filetype", E_USER_ERROR);
        return FALSE;
     }
  } else {
    return TRUE;
  }
}

/**
 * Help function to save an uploaded image file in the DB.
 * 
 * @param image_basename the name of the image file
 * @return string|boolean The name of the image it successfuly saved to the DB, of FALSE in case of error.
 */
function save_uploaded_image_file($title, $extension) {
  global $_FILES;
  global $_POST;
  
  /* Add the original filename to our target path. Result is "uploads/filename.extension" */
  /* XXX added validation for the file name. */ 
  $image_basename = validate_name($_POST['title']);
  $image_name = $image_basename . "." . $extension;
  $target_path = IMAGE_DIR . $image_basename . "." . $extension;
  
  if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
      $resized = wg_resizeImageBeautifulFactor($target_path, IMAGE_DIR . $image_basename . '.jpg' , MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
      if (PEAR::isError($resized)) {
        trigger_error($result->getMessage());
      } else {
        if ($extension != 'jpg') {
          unlink(IMAGE_DIR . $image_basename . "." . $extension);
          $extension = 'jpg';
          $target_path = IMAGE_DIR . $image_basename . "." . $extension;;
        }
      }
      // Check if node already exists.
      $node = DB_DataObject_Node::staticGet('title', $title);
      if ($node) {
        $node = new DB_DataObject_Node;
        $node->get('title', $title);
        $node->extension = $extension;
        $result = $node->update();  
      } else {
      	$node = new DB_DataObject_Node;
        $node->title = $title;
        $node->extension = $extension;
        $result = $node->insert();        
      }

      if (PEAR::isError($result)) {
        echo 'Standard Message: ' . $result->getMessage() . "\n";
           echo 'Standard Code: ' . $result->getCode() . "\n";
           echo 'DBMS/User Message: ' . $result->getUserInfo() . "\n";
           echo 'DBMS/Debug Message: ' . $result->getDebugInfo() . "\n";
           exit;
      }

      return $target_path;
  } else {
    trigger_error("There was an error uploading the file, please try again!", E_USER_ERROR);
    return false;
  }
}