<?php
// $Id$

/**
 * @file: 分析节点 body 中的 img 标签，将远程图片保存到本地服务器
 */

/**
 * @Implement of hook_menu()
 * @access public
 * @return array
 */
function get_image_menu() {
  $items = array();
  
  $items['admin/settings/get_image'] = array(
    'title' => 'Get Image',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('get_image_settings_form'),
    'access callback' => 'user_access',
    'access arguments' => array('Administer get image'),
    'type' => MENU_NORMAL_ITEM
  );
  
  return $items;
}

/**
 * @Implement of hook_permission()
 * @access public
 * @return array
 */
function get_image_permission() {
  return array(
    'administer get images' => array(
      'title' => t('Administer get image'),
    ),
  );
}

/**
 * @Implement of hook_nodeapi() 
 * @param object $node 
 * @access public
 * @return void
 */
function get_image_node_presave($node) {
  if (variable_get('get_image_'.$node->type, 0) && !empty($node->body['und'])) {
    global $_get_image_save_node;
    $_get_image_save_node = $node;
    if ($node->body['und'][0]) {
      $node->body['und'][0]['value'] = preg_replace_callback('/(<img.*?src=["|\'])(.*?)["|\']/ms', '_get_image_save', $node->body['und'][0]['value']);
    }
  }
}

/**  
 * 分析内容中的 img 标签，将远程图片保存到本地服务器
 * @param array $mat 
 * @access protected
 * @return string
 */
function _get_image_save($mat) {
  global $_get_image_save_node;

  static $files;
  
  if (isset($files[$mat[2]])) {
    return $files[$mat[2]];
  }
    
  $files[$mat[2]] = $mat[0];
  
  /**
   * 包含当前域名的路径、相对路径，不做处理
   */
  if (strpos($mat[2], $GLOBALS['base_url']) !== false || strpos($mat[2], 'http://') === false) {
    return $files[$mat[2]];
  }

  /**
   * @TODO 用于保存到数据库
   */
  $file = new stdClass;
  $file->filepath = $mat[2];
   
  $result = drupal_http_request($file->filepath);

  if ($result->code == 200) {
    $file->filename = basename($file->filepath);

    /**
     * test.jpg?width=100&height=200
     * image/test
     */
    $file->extension = strtolower(ltrim(substr($file->filename, -4), '.'));

    if (!in_array($file->extension, array('png', 'gif', 'jpeg', 'jpg'))) {
      if (!empty($result->headers['content-type'])) {
        $file->extension = end(explode('/', $result->headers['content-type']));
      } else {
        $file->extension = 'jpg';
      }
    }

    if (variable_get('get_image_rename', 0)) {
      $file->filename = md5($file->filename) . '.' . $file->extension;
    }
    
    if ($path = get_image_path($_get_image_save_node)) {
      $file->filepath = $path . '/' . $file->filename;
    } else {
      return $files[$mat[2]];
    }
 
    if (file_put_contents($file->filepath, $result->data)) {
      $file->uri = $file->filepath; 
        /**
         * 验证是否为图片文件
         */
      if ($error = file_validate_is_image($file)) {
        @unlink($file->filepath);
        drupal_set_message(t('Save "@name" failed', array('@name' => $mat[2])), 'error');
      } else {

        if (variable_get('get_image_absolute', 0)) {
          $file->filepath = $GLOBALS['base_url'] . $GLOBALS['base_path'] . $file->filepath;
        } else {
          $file->filepath = $GLOBALS['base_path'] . $file->filepath;
        }

        drupal_set_message(t('Save "@name" success', array('@name' => $mat[2])));
        $files[$mat[2]] = $mat[1] . $file->filepath.'"';
      }

    } else {
      drupal_set_message(t('Save "@name" failed', array('@name' => $mat[2])), 'error');
    }
    
  }

  return $files[$mat[2]];
}

/**
 * 创建文件夹
 * @param object $node
 * @access public
 * @return string 返回路径
 */
function get_image_path($node = NULL) {
  global $user;
  
  $path = variable_get('file_public_path', conf_path() . '/files') . '/';
  
  if (!variable_get('get_image_path', 0)) {
    $path .= 'get_image';
  } else {
    
    $m = explode('|', format_date(time(), 'custom', "Y|m|d"));
    $a = array(
      '%uid' => $user->uid,
      '%username' => $user->name,
      '%Y' => $m[0],
      '%m' => $m[1],
      '%d' => $m[2]
    );
    
    if (isset($node)) {
      if (!empty($node->nid)) {
        $a['%nid'] = $node->nid;
      }
      
      if (!empty($node->uid)) {
        $a['%uid'] = $node->uid;
      }
    }

    $path .= strtr(variable_get('get_image_path', 'get_image'), $a);
  }

  if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
    return $path;
  }
}

/**
 * 模块设置
 * @access public
 * @return array
 */
function get_image_settings_form() {
  $form['get_image_path'] = array(
		'#type'=> 'textfield',
		'#title' => t('Path of saving'),
		'#default_value' => variable_get('get_image_path', 'get_image'),
		'#description' => t('The path where the files should be saved, may save by user id or user name or time, e.g.: get_image/%uid or photos/%username or image/%Y/%m/%d. Available variables: %uid, %username, %Y, %m, %d.'),
		'#size' => '40',
		'#required' => TRUE,
  );

  $form['get_image_absolute'] = array(
		'#title' => t('Absolute path'),
		'#type' => 'checkbox',
    '#description' => t('View %absolute or %relative', array(
      '%absolute' => $GLOBALS['base_url'] . $GLOBALS['base_path'] . 'files/1.jpg',
      '%relative' => $GLOBALS['base_path'] . 'files/1.jpg'
    )),
		'#default_value' => variable_get('get_image_absolute', 0),
  );

  $form['get_image_rename'] = array(
		'#title' => t('Image Rename'),
		'#type' => 'checkbox',
		'#description' => t('e.g: md5("imagename");'),
		'#default_value' => variable_get('get_image_rename', 0),
  );
  
  $types = node_type_get_types();
  
  foreach ($types as $type) {
    $form['get_image_'.$type->type] = array(
  		'#title' => $type->name,
  		'#type' => 'checkbox',
  		'#default_value' => variable_get('get_image_'.$type->type, 0),
    );
  }

  return system_settings_form($form);
}
