<?php 
// $Id: image_pub.module,v 1.2.2.2 2006/05/20 12:28:56 pangloss Exp $

/*
 * Image publishing support module
 * Glue code for various 3rd party image publishing frontends, 
 * including:
 * - Gallery Remote (http://gallery.menalto.com)
 * - Windows Web Publishing Wizard
 */

/**
 * Implementation of hook_help().
 */
function image_pub_help($section = 'admin/help#image_pub') {
  switch ($section) {
    case 'admin/modules#description':
      return t('Supports image uploads using 3rd party publishing apps');
    case 'admin/image_pub':
      return t('The Image Publishing module supports 3rd party image upload and management applications.');
  }
}

/**
 * Implementation of hook_menu().
 */
function image_pub_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array('path' => 'gallery_remote2.php',
      'callback' => '_image_pub_gr_request',
      'access' => TRUE,
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'publish_xp',
      'callback' => '_image_pub_xp_request',
      'access' => TRUE,
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/image_pub_xp_reghack',
      'callback' => '_image_pub_xp_reghack',
      'access' => TRUE,
      'type' => MENU_CALLBACK);
    $items[] = array('path' => 'admin/image_pub',
      'title' => t('image publishing'),
      'callback' => '_image_pub_admin',
      'access' => user_access('create images'));
  }
  return $items;
}

function _image_pub_admin() {
  $output = '';
  $group = '';
  $group .= t('The below link will send a registry editor file to your computer.  Merging this file will add a new option to the list of sites to which Web content can be published, using the <em>Publish this file/folder to the Web</em> option in Explorer.  If you ever wish to remove this site from your system\'s list of publishing sites, you must manually edit your system registry.<br />');
  $group .= t('<em>Windows XP or a more recent version of Windows is required to use this feature.</em><br />');
  $group .= '<a href="'.url('admin/image_pub_xp_reghack').'">'.t('Install Windows Web Publishing Wizard Support').'</a>.<br />';
  
  return $group;
}


/*
 * Generalized helper functions for tasks that require tight integration 
 * with other parts of Drupal, such as image.module and taxonomy.module.
 *	_image_pub_get_vid()
 *	_image_pub_base_url()
 *	_image_pub_image_baseurl()
 *	_image_pub_get_imagefilename()
 *	_image_pub_get_imageinfo()
 *	_image_pub_album_get()
 *	_image_pub_album_enum()
 *	_image_pub_album_selector()
 *	_image_pub_album_access()
 *	_image_pub_album_images()
 *
 *	_image_pub_authenticate()
 *	_image_pub_album_add()
 *	_image_pub_image_add()
 */
function _image_pub_get_vid() {
  return _image_gallery_get_vid();
}
function _image_pub_base_url() {
  global $base_url;
  return $base_url;
}
function _image_pub_image_baseurl() {
  return _image_pub_base_url() .'/'. variable_get('file_directory_path', 'files') .'/'. variable_get('image_default_path', 'images');
}
function _image_pub_get_imagefilename($node, $size = '_original') {
  $fname = $node->images[$size];
  if (isset($fname)) {
    $imgbase = variable_get('image_default_path', 'images') .'/';
    if (!strncmp($fname, $imgbase, strlen($imgbase))) {
      $fname = substr($fname, strlen($imgbase));
    }
  }
  return $fname;
}
function _image_pub_get_imageinfo($node, $size = '_original') {
  $file = file_create_path($node->images[$size]);
  $info = image_get_info($file);
  $info['filesize'] = filesize($file);
  return $info;
}
function _image_pub_album_get($albumid) {
  
  $term = taxonomy_get_term($albumid);
  if (!$term) {
	if ($albumid == 0)
		$term = taxonomy_get_term('<root>');
    else
		$term = NULL;
  }
  return $term;
}
function _image_pub_album_enum($albumid = 0, $subalbums = TRUE) {
  return taxonomy_get_tree(_image_pub_get_vid(), $albumid, -1,
			   ($subalbums ? NULL : 1));
}
function _image_pub_album_selector($fname, $showroot = FALSE, $selalbum = NULL) {
  /* This is mostly redundant with taxonomy_form(). */
  $body = array();
  $tree = _image_pub_album_enum();
  $options = array();
  $albumid = 0;
  if (isset($selalbum)) {
    $albumid = $selalbum->tid;
  }
  if ($showroot) {
    $options[0] = '&lt;Root Album&gt;';
  }
  if ($tree) {
    foreach ($tree as $term) {
      if (!$showroot && ($albumid == 0)) {
        $albumid = $term->tid;
      }
      $dashes = '';
      for ($i = 0; $i < $term->depth; $i++) {
        $dashes .= '-';
      }
      $options[$term->tid] = $dashes . $term->name;
    }
  }
  $body[] = '<select name="'.$fname.'">';
  foreach ($options as $aid => $term) {
    $sel = '';
    if ($aid == $albumid) {
      $sel = ' selected="selected"';
    }
    $body[] = '<option value="'.$aid.'"'.$sel.'>'.$term.'</option>';
  }
  $body[] = '</select>';
  return implode("\r\n", $body);
}

function _image_pub_album_access($type, $album) {
  switch ($type) {
    case 'view':
      return user_access('access content');
    case 'update':
      return user_access('administer images');
    case 'create':
      return user_access('create images');
  }
  return FALSE;
}
function _image_pub_album_images($tid) {
  $nodes = array();
  $sql = "SELECT n.nid FROM {node} n INNER JOIN {term_node} t ON t.nid = n.nid WHERE t.tid = $tid AND n.type = 'image';";
  $res = db_query($sql);
  while ($term = db_fetch_object($res)) {
    $nodes[] = node_load(array('nid' => $term->nid));
  }
  return $nodes;
}
function _image_pub_authenticate($uname, $pass) {
  global $user;
  if ($user->uid) {
    watchdog('image_pub', t('Session closed for %user', array('%user' => theme('placeholder', $user->name))));
    unset($user);
  }
  $user = user_authenticate($uname, $pass);
  if (!$user->uid) {
    return FALSE;
  }
  watchdog('image_pub', t('Session opened for %user', array('%user' => theme('placeholder', $user->name))));
  return TRUE;
}
function _image_pub_album_add($title, $descr, $palbum) {
  watchdog('image_pub', t('Album added with title %title', array('%title' => $title)));

  if (empty($title)) {
    $title = 'Untitled album';
  }
  $edit = array(
    'name' => $title,
    'description' => $descr,
    'vid' => _image_pub_get_vid(),
    'parent' => array(isset($palbum) ? $palbum->tid : 0),
    'weight' => 0,
  );
  $term = taxonomy_save_term($edit);
  if (isset($term)) {
    return (object)$term;
  }
  return NULL;
}
function _image_pub_image_add($album, $caption, $description, $srcfield) {
  if (!isset($_FILES[$srcfield])) {
    return array('success' => FALSE,
                 'reason' => 'Forgetting a file?');
  }

  if (empty($caption)) {
    $caption = $_POST['force_filename'];
    if (empty($caption)) {
      $caption = $file->filename;
      if (empty($caption)) {
        $caption = 'Untitled image';
      }
    }
  }

  // move the file into the drupal filesystem
  $filelocation = $_FILES[$srcfield]['tmp_name'];
  $filename = basename($_FILES[$srcfield]['name']);

  if (file_exists(file_directory_temp() . '/' . $filename)) {
  	// FIXME either rename or throw an error;
  }
  if (!move_uploaded_file($filelocation, file_directory_temp() . '/' . $filename)) {
  	// FIXME throw an error;
  }

  // create a drupal node
  global $user;
  $node = new StdClass();
  $node->uid = $user->uid;
  $node->name = $user->name;
  $node->type ='image';
  $node->title = $caption;
  $node->body = $description;
  $node->comment = 0;
  $node->status = 1;
  $node->taxonomy = array($album->tid);
  $node->images['_original'] = file_directory_temp() . '/' . $filename;

  // let the image module generate the preview/thumbnail
  _image_build_derivatives($node, true);

  // save the node
  node_save($node);

  // FIXME: check that the uploaded image was accepted.
  return array('success' => TRUE, 'node' => $node);
}


/*
 * Definitions for handling the gallery remote protocol
 * See http://gallery.menalto.com/ for more info.
 */

define('GR_STAT_SUCCESS', 0);
define('GR_STAT_PROTO_MAJ_VER_INVAL', 101);
define('GR_STAT_PROTO_MIN_VER_INVAL', 102);
define('GR_STAT_PROTO_VER_FMT_INVAL', 103);
define('GR_STAT_PROTO_VER_MISSING', 104);
define('GR_STAT_PASSWD_WRONG', 201);
define('GR_STAT_LOGIN_MISSING', 202);
define('GR_STAT_UNKNOWN_CMD', 301);
define('GR_STAT_NO_ADD_PERMISSION', 401);
define('GR_STAT_NO_FILENAME', 402);
define('GR_STAT_UPLOAD_PHOTO_FAIL', 403);
define('GR_STAT_NO_WRITE_PERMISSION', 404);
define('GR_STAT_NO_CREATE_ALBUM_PERMISSION', 501);
define('GR_STAT_CREATE_ALBUM_FAILED', 502);

define('GR_SERVER_VERSION', '2.15');

function _image_pub_gr_get_albumname($term) {
  return 'Album' . $term->tid;
}
function _image_pub_gr_get_albumid($albname) {
  if (!strncmp($albname, 'Album', 5)) {
    return substr($albname, 5);
  }
  return 0;
}


/*
 * Protocol request handler entry points below
 *    _image_pub_gr_request()               (main entry point)
 *    _image_pub_gr_finish()                (completion helper)
 *    _image_pub_gr_login()
 *    _image_pub_gr_fetch_albums()
 *    _image_pub_gr_fetch_album_images()
 *    _image_pub_gr_add_album()
 *    _image_pub_gr_move_album()
 *    _image_pub_gr_add_image()
 */

function _image_pub_gr_request() {
  $cmd = $_POST['cmd'];
  $numref = FALSE;

  //watchdog('image_pub', t('Processing command %cmd', array('%cmd' => theme('placeholder', $cmd))));

  switch($cmd) {
    case 'login':
      _image_pub_gr_login($_POST['uname'], $_POST['password']);
      break;

    case 'fetch-albums':
      $numref = TRUE;
    case 'fetch-albums-prune':
      $check_writeable = ($_POST['check-writeable'] == 'yes') ? TRUE : FALSE;
      _image_pub_gr_fetch_albums($numref, $check_writeable);
      break;

    case 'fetch-album-images':
      $albums_too = ($_POST['albums_too'] == 'yes') ? TRUE : FALSE;
      _image_pub_gr_fetch_album_images($_POST['set_albumName'],
                                       $albums_too);
      break;

    case 'new-album':
      _image_pub_gr_add_album($_POST['set_albumName'],
                              $_POST['newAlbumTitle'],
                              $_POST['newAlbumDesc']);
      break;

    case 'move-album':
      _image_pub_gr_move_album($_POST['set_albumName'],
                               $_POST['set_destalbumName']);
      break;

    case 'add-item':
      _image_pub_gr_add_image($_POST['set_albumName'],
			      $_POST['caption'],
			      $_POST['extrafield.Description']);
      break;

    case '':
      echo 'For more information about Gallery Remote, see Gallery\'s website located at <a href="http://gallery.sourceforge.net">http://gallery.sourceforge.net</a>';
      exit;

    default:
      _image_pub_gr_finish(GR_STAT_UNKNOWN_CMD, '', t('Unknown command "%cmd"', array('%cmd' => theme('placeholder', $cmd))));
      break;
  }
}


function _image_pub_gr_finish($code, $body = NULL, $message = NULL) {
  static $gr_messages;
  if (!isset($gr_messages)) {
    $gr_messages = array(
      GR_STAT_SUCCESS => t('Successful'),
      GR_STAT_PROTO_MAJ_VER_INVAL => t('The protocol major version the client is using is not supported.'),
      GR_STAT_PROTO_MIN_VER_INVAL => t('The protocol minor version the client is using is not supported.'),
      GR_STAT_PROTO_VER_FMT_INVAL => t('The format of the protocol version string the client sent in the request is invalid.'),
      GR_STAT_PROTO_VER_MISSING => t('The request did not contain the required protocol_version key.'),
      GR_STAT_PASSWD_WRONG => t('The password and/or username the client send in the request is invalid.'),
      GR_STAT_LOGIN_MISSING => t('The client used the login command in the request but failed to include either the username or password (or both) in the request.'),
      GR_STAT_UNKNOWN_CMD => t('The value of the cmd key is not valid.'),
      GR_STAT_NO_ADD_PERMISSION => t('The user does not have permission to add an item to the gallery.'),
      GR_STAT_NO_FILENAME => t('No filename was specified.'),
      GR_STAT_UPLOAD_PHOTO_FAIL => t('The file was received, but could not be processed or added to the album.'),
      GR_STAT_NO_WRITE_PERMISSION => t('No write permission to destination album.'),
      GR_STAT_NO_CREATE_ALBUM_PERMISSION => t('A new album could not be created because the user does not have permission to do so.'),
      GR_STAT_CREATE_ALBUM_FAILED => t('A new album could not be created, for a different reason (name conflict).'),
    );
  }
  if (!isset($message)) {
    $message = $gr_messages[$code];
    if (!isset($message)) {
      $message = 'Undefined error code';
    }
  }
  if ($code != GR_STAT_SUCCESS) {
    watchdog('image_pub', t('Request failure: %code, %msg', array('%code' => $code, '%msg' => $message)));
  } else {
    //watchdog('image_pub', t('Command succeeded: %msg', array('%msg' => theme('placeholder', $message))));
  }

  drupal_set_header("Content-Type: text/plain");
  echo "#__GR2PROTO__\n" .
       $body .
       "status=$code\n" .
       "status_text=$message\n";
  exit;
}


function _image_pub_gr_login($uname, $pass) {
  global $user;
  $body = 'server_version='.GR_SERVER_VERSION."\n";
  if (!$uname || !$pass) {
    if (!$uname && !$pass) {
      // Not trying to log in, just asking for a version number.
      _image_pub_gr_finish(GR_STAT_SUCCESS, $body);
    }
    _image_pub_gr_finish(GR_STAT_LOGIN_MISSING);
  }
  if (!_image_pub_authenticate($uname, $pass)) {
    _image_pub_gr_finish(GR_STAT_PASSWD_WRONG);
  } else {
    _image_pub_gr_finish(GR_STAT_SUCCESS, $body);
  }
}


function _image_pub_gr_fetch_albums($refnum, $check_writeable) {
  $body = '';
  $thumb_dims = _image_get_dimensions('thumbnail');
  $thumb_max = min($thumb_dims[0], $thumb_dims[1]);
  $preview_dims = _image_get_dimensions('preview');
  $preview_max = min($preview_dims[0], $preview_dims[1]);
  $nalbums = 0;
  $cperm = 'false';
  $aperm = 'false';
  $crperm = 'no';
  if (user_access('create images')) {
    $cperm = 'true';
  }
  if (user_access('administer images')) {
    $aperm = 'true';
    $crperm = 'yes';
  }
  $tree = _image_pub_album_enum();
  $aid = 0;
  $aidref = array();
  foreach ($tree as $term) {
    if (_image_pub_album_access('view', $term)) {
      $aid++;
      $aname = _image_pub_gr_get_albumname($term);
      $aidref[$aname] = $aid;

      $pname = 0;
      if (!empty($term->parents[0])) {
        $pterm = _image_pub_album_get($term->parents[0]);
        $pname = $pterm->tid;
        if ($refnum) {
          $pname = $aidref[$pname];   // Guaranteed to exist?
        } else {
          $pname = _image_pub_gr_get_albumname($pterm);
        }
      }

      $body .= 'album.name.'.$aid.'='.$aname."\n";
      $body .= 'album.title.'.$aid.'='.$term->name."\n";
      $body .= 'album.summary.'.$aid.'='.$term->description."\n";
      $body .= 'album.parent.'.$aid.'='.$pname."\n";
      $body .= 'album.resize_size.'.$aid.'='.$preview_max."\n";
      $body .= 'album.max_size.'.$aid.'='.'0'."\n";
      $body .= 'album.thumb_size.'.$aid.'='.$thumb_max."\n";
      $body .= 'album.perms.add.'.$aid.'='.$cperm."\n";
      $body .= 'album.perms.write.'.$aid.'='.$aperm."\n";
      $body .= 'album.perms.del_item.'.$aid.'='.$aperm."\n";
      $body .= 'album.perms.del_alb.'.$aid.'='.$aperm."\n";
      $body .= 'album.perms.create_sub.'.$aid.'='.$aperm."\n";
      $body .= 'album.extrafields.'.$aid."=Description\n";
      $nalbums++;
    }
  }
  $body .= 'album_count='.$nalbums."\n";
  $body .= 'can_create_root='.$crperm."\n";
  _image_pub_gr_finish(GR_STAT_SUCCESS, $body);
}


function _image_pub_gr_fetch_album_images($albname, $albumstoo) {
  $body = '';
  $album = _image_pub_album_get(_image_pub_gr_get_albumid($albname));
  if (!isset($album) || !_image_pub_album_access('view', $album)) {
    _image_pub_gr_finish(GR_STAT_NO_FILENAME, $body, 'No such album');
  }

  if ($albumstoo) {
    $tree = _image_pub_album_enum($album->tid, FALSE);
    foreach ($tree as $term) {
      if (_image_pub_album_access('view', $term)) {
        $body .= 'album.name.'.$term->tid.'='._image_pub_gr_get_albumname($term)."\n";
      }
    }
    $numimages = taxonomy_term_count_nodes($album->tid, 'image');

  } else {
    $numimages = 0;
    $nodes = _image_pub_album_images($album->tid);
    $iid = 0;
    foreach ($nodes as $node) {
      if (node_access('view', $node)) {
        $iid++;
        $body .= 'image.name.'.$iid.'='._image_pub_get_imagefilename($node)."\n";
        $info = _image_pub_get_imageinfo($node);
        $body .= 'image.raw_width.'.$iid.'='.$info['width']."\n";
        $body .= 'image.raw_height.'.$iid.'='.$info['height']."\n";
        $body .= 'image.raw_filesize.'.$iid.'='.$info['filesize']."\n";

        $body .= 'image.resizedName.'.$iid.'='._image_pub_get_imagefilename($node, 'preview')."\n";
        $info = _image_pub_get_imageinfo($node, 'preview');
        $body .= 'image.resized_width.'.$iid.'='.$info['width']."\n";
        $body .= 'image.resized_height.'.$iid.'='.$info['height']."\n";
        //$body .= 'image.resized_filesize.'.$iid.'='.$info['filesize']."\n";

        $body .= 'image.thumbName.'.$iid.'='._image_pub_get_imagefilename($node, 'thumbnail')."\n";
        $info = _image_pub_get_imageinfo($node, 'thumbnail');
        $body .= 'image.thumb_width.'.$iid.'='.$info['width']."\n";
        $body .= 'image.thumb_height.'.$iid.'='.$info['height']."\n";
        //$body .= 'image.thumb_filesize.'.$iid.'='.$info['filesize']."\n";

        $body .= 'image.caption.'.$iid.'='.$node->title."\n";
        $body .= 'image.clicks.'.$iid.'='.'0'."\n";
        $body .= 'image.extrafield.Description.'.$iid.'='.$node->teaser."\n";

        $ctime = $node->created;
        $body .= 'image.capturedate.year.'.$iid.'='.date('Y', $ctime)."\n";
        $body .= 'image.capturedate.mon.'.$iid.'='.date('n', $ctime)."\n";
        $body .= 'image.capturedate.mday.'.$iid.'='.date('j', $ctime)."\n";
        $body .= 'image.capturedate.hours.'.$iid.'='.date('H', $ctime)."\n";
        $body .= 'image.capturedate.minutes.'.$iid.'='.date('i', $ctime)."\n";
        $body .= 'image.capturedate.seconds.'.$iid.'='.date('s', $ctime)."\n";
        $body .= 'image.hidden.'.$iid.'='.($node->status != 1 ? 'yes' : 'no')."\n";
        $numimages++;
      }
    }
  }

  $body .= 'image_count='.$numimages."\n";
  $body .= 'baseurl='._image_pub_image_baseurl()."/\n";

  _image_pub_gr_finish(GR_STAT_SUCCESS, $body);
}


function _image_pub_gr_add_album($parentaname, $title, $descr) {
  $body = '';

  $palbum = _image_pub_album_get(_image_pub_gr_get_albumid($parentaname));
  if (!isset($palbum)) {
    _image_pub_gr_finish(GR_STAT_CREATE_ALBUM_FAILED, $body, t('No such parent album: %parent', array('%parent' => $parentname)));
  }
  if (!_image_pub_album_access('update', $palbum)) {
    _image_pub_gr_finish(GR_STAT_NO_CREATE_ALBUM_PERMISSION, $body);
  }

  $term =_image_pub_album_add($title, $descr, $palbum);
  if (!isset($term)) {
    _image_pub_gr_finish(GR_STAT_CREATE_ALBUM_FAILED);
  } else {
    $body .= 'album.name='. _image_pub_gr_get_albumname($term)."\n";
    _image_pub_gr_finish(GR_STAT_SUCCESS, $body, 'Album created');
  }
}


function _image_pub_gr_move_album($albname, $destaname) {
  $body = '';

  $album = _image_pub_album_get(_image_pub_gr_get_albumid($albname));
  if (!isset($album)) {
    _image_pub_gr_finish(GR_STAT_CREATE_ALBUM_FAILED, $body, 'No such album');
  }

  if (!_image_pub_album_access('update', $album)) {
    _image_pub_gr_finish(GR_STAT_NO_WRITE_PERMISSION, $body);
  }

  if (!isset($destaname) || ($destaname == '0') || ($destaname == 'rootalbum')) {
    $dtid = 0;
  } else {
    $dalbum = _image_pub_album_get(_image_pub_gr_get_albumid($destaname));
    if (!isset($dalbum) || !_image_pub_album_access('update', $dalbum)) {
      _image_pub_gr_finish(GR_STAT_CREATE_ALBUM_FAILED, $body, 'Invalid destination album '.$destaname);
    }
    $dtid = $dalbum->tid; 
  }

  $album->parent = array($dtid);
  $term = (array)$album;
  $status = taxonomy_save_term( $term );

  _image_pub_gr_finish(GR_STAT_SUCCESS, $body, 'Album reparented');
}


function _image_pub_gr_add_image($albname, $caption, $description) {
  $body = '';
  $album = _image_pub_album_get(_image_pub_gr_get_albumid($albname));
  if (!isset($album)) {
    _image_pub_gr_finish(GR_STAT_UPLOAD_PHOTO_FAIL, 'No such album');
  }
  if (!_image_pub_album_access('create', $album)) {
    _image_pub_gr_finish(GR_STAT_NO_ADD_PERMISSION);
  }

  $result = _image_pub_image_add($album, $caption, $description, 'userfile');

  if (!$result['success']) {
    _image_pub_gr_finish(GR_STAT_UPLOAD_PHOTO_FAIL, $result['reason']);
  } else {
    _image_pub_gr_finish(GR_STAT_SUCCESS, $body, 'Added node '.$result['node']->nid);
  }
}


/*
 * Windows Web publishing wizard support
 *
 * Below is support for the Windows XP Web publishing wizard.  It's just a 
 * glorified file picker and MSIE instance in a wizard form factor, but 
 * it gets the job done, and did we mention it comes with every copy of 
 * Windows?
 *
 * Microsoft even appears to have some sort of documentation for the 
 * publishing wizard on the MSDN site, although debugging is a major 
 * pain:
 *
 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/publishing_wizard/pubwiz.asp
 *
 * Our part of the wizard has three steps:
 * 1. Authenticate.
 * 2. Select or create album.
 * 3. Publish.  We send a blank page with a magic script to configure
 *    the wizard.
 *
 * We send bare HTML and don't use themes.  Why not themes?
 * -> The XP publishing wizard has a microscopic embedded MSIE instance 
 *    that we don't want to overflow with content.  That is hard to
 *    guarantee using an arbitrary theme.
 * -> Themes will display distracting links in headers and sidebars.  We 
 *    don't want the user navigating to one of the distractions.
 */


/*
 * Concoct a magic registry file to add this site to the list of
 * usable destinations for the publishing wizard.
 */
function _image_pub_xp_reghack() {
  $pub_url = url('publish_xp', NULL, NULL, TRUE);
  $site_name = variable_get('site_name', 'drupal');
  $site_descr = sprintf(t("Publish Your Photos to %s."), $site_name);
  if (!strncmp($pub_url, 'https:', 6)) {
    $site_descr .= ' (Secure)';
  } else {
    $site_descr .= ' (Insecure)';
  }
  drupal_set_header("Cache-control: private");
  drupal_set_header("Content-Type: application/octet-stream");
  drupal_set_header("Content-Disposition: filename=install_registry.reg");

  $lines[] = 'Windows Registry Editor Version 5.00';
  $lines[] = '';
  $lines[] = '[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\PublishingWizard\PublishingWizard\Providers\\' . $site_name . ']';
  $lines[] = '"displayname"="' . $site_name . '"';
  $lines[] = '"description"="' . $site_descr . '"';
  $lines[] = '"href"="' . $pub_url . '"';
  $lines[] = '"icon"="' . _image_pub_base_url() . '/favicon.ico"';
  $lines[] = '';
  echo join("\r\n", $lines);
  exit;
}


/*
 * Implementation of wizard forms and such:
 *	_image_pub_xp_request()		(main entry point)
 *	_image_pub_xp_login()
 *	_image_pub_xp_album()
 *	_image_pub_xp_addimage()
 *	_image_pub_xp_page()		(HTML form template)
 *	_image_pub_xp_login_form()
 *	_image_pub_xp_album_form()
 *	_image_pub_xp_addimage_script()
 */

function _image_pub_xp_request() {

  /*
   * We require the user to be logged in to publish.
   * We honor cookies saved from other MSIE sessions, and don't
   * require the user to log in if they already have a session.
   */

  global $user;
  $cmd = $_REQUEST['cmd'];
  if (!$user->uid) {
    if (!isset($cmd)) {
      $cmd = 'login';
    }
  }

  switch($cmd) {
    case 'login':
      _image_pub_xp_login($_REQUEST['uname'], $_REQUEST['password']);
      break;
    case 'addimage':
      _image_pub_xp_addimage($_REQUEST['albumid']);
    default:
      _image_pub_xp_album($_REQUEST['edit']);
      break;
  }
}


function _image_pub_xp_login($uname, $pass) {
  if (empty($uname) && empty($pass)) {
    _image_pub_xp_login_form();
  } else if(!_image_pub_authenticate($uname, $pass)) {
    _image_pub_xp_login_form("Invalid Login", $uname);
  } else {
    _image_pub_xp_album_form();
  }
}


function _image_pub_xp_album($edit) {
  if (!isset($edit)) {
    _image_pub_xp_album_form();
    return;
  }

  $create_new = $edit['create_new'];

  if ($create_new) {
    $albumid = $edit['create_parentid'];
    $create_name = $edit['create_name'];
    $create_descr = $edit['create_descr'];

    $album = _image_pub_album_get($albumid);
    if (!_image_pub_album_access('update', $album)) {
      _image_pub_xp_album_form('Create Album Permission Denied', $album);
    }
    $newalbum = _image_pub_album_add($create_name, $create_descr, $album);
    if (isset($newalbum)) {
      _image_pub_xp_album_form('Created Album "'.$newalbum->name.'"', $newalbum);
    } else {
      _image_pub_xp_album_form('Error Creating Album', $album);
    }
    return;
  }

  $albumid = $edit['albumid'];
  $album = _image_pub_album_get($albumid);

  if (!isset($album)) {
    _image_pub_xp_album_form('Invalid album specified');
    return;
  }
  if (!_image_pub_album_access('create', $album)) {
    _image_pub_xp_album_form('Create Image Permission Denied', $album);
    return;
  }
  _image_pub_xp_addimage_script($album);
}


function _image_pub_xp_addimage($albumid) {
  $album = _image_pub_album_get($albumid);
  if (!isset($album)) {
    _image_pub_xp_album_form('Invalid album specified');
    return;
  }
  if (!_image_pub_album_access('update', $album)) {
    _image_pub_xp_album_form('Create Image Permission Denied', $album);
    return;
  }

  $result = _image_pub_image_add($album, NULL, NULL, 'userfile');
}


function _image_pub_xp_page($body, $next, $back = NULL) {
  global $language;
  $site_name = variable_get('site_name', 'drupal');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $language ?>" xml:lang="<?php print $language ?>">
<head>
</head>
<body bgcolor="threedface">
<?php echo $body; ?>
<script>
function OnBack() {
<?php if (isset($back)) { ?>
	window.location.href = "<?php echo $back; ?>";
<?php } else { ?>
	window.external.FinalBack();
<?php } ?>
	window.external.SetWizardButtons(true,true,false);
}
function OnNext() {
	<?php echo $next; ?>.submit();
}
function window.onload() {
	window.external.SetHeaderText("<?php echo $site_name; ?>", "Upload Photos");
	window.external.SetWizardButtons(true,true,false);
}
</script>
</body>
</html>
<?php
  exit;
}


function _image_pub_xp_login_form($message = NULL, $uname = NULL) {
  $form_action = 'publish_xp?'.session_name().'='.session_id();
  if (!isset($uname)) {
    $uname = '';
  }
  if (isset($message)) {
    $body[] = '<p style="color:red;font-weight:bold;text-align:center;">'.$message.'</p>';
  }
  $body[] = '<form method="post" id="login" action="'.$form_action.'">';
  $body[] = '<table border="0" align="center">';
  $body[] = '<tr><th>User:</th><td><input type="text" name="uname" value="'.check_plain($uname).'" /></td></tr>';
  $body[] = '<tr><th>Password:</th><td><input type="password" name="password" value="" /></td></tr>';
  $body[] = '</table>';
  $body[] = '<input type="hidden" name="cmd" value="login" />';
  $body[] = '<input type="hidden" name="lcid" value="'.check_plain($_REQUEST['lcid']).'" />';
  $body[] = '<input type="hidden" name="langid" value="'.check_plain($_REQUEST['langid']).'" />';
  $body[] = '<input type="hidden" name="'.session_name().'" value="'.check_plain(session_id()).'">';
  //$body[] = '<input type="submit" value="Submit" />';
  $body[] = '</form>';
  $body[] = '';

  _image_pub_xp_page(implode("\r\n", $body), 'login');
}


function _image_pub_xp_album_form($message = NULL, $select_album = NULL) {
  global $user;
  $body[] = '<form method="post" id="album">';
  $body[] = '<table align="center">';
  $body[] = '<tr><td>';
  $body[] = '<label for="publish-now"><input type="radio" id="publish-now" name="edit[create_new]" value="0" checked="checked" /> <strong>Publish Images to This Gallery:</strong></label>';
  $body[] = '</td></tr>';
  $body[] = '<tr><td><div style="margin-left:25px">';
  $body[] = _image_pub_album_selector('edit[albumid]', FALSE, $select_album);
  $body[] = '</div></td></tr>';
  $body[] = '<tr><td>&nbsp;</td></tr>';
  $body[] = '<tr><td>';
  $body[] = '<label for="create-new"><input type="radio" id="create-new" name="edit[create_new]" value="1" /> <strong>Create a Sub-Gallery</strong></label>';
  $body[] = '</td></tr>';
  $body[] = '<tr><td><div style="margin-left:25px">';
  $body[] = '<table>';
  $body[] = '<tr><td>Within:</td><td>';
  $body[] = _image_pub_album_selector('edit[create_parentid]', TRUE, $select_album);
  $body[] = '</td></tr>';
  $body[] = '<tr><td>Name:</td><td><input type="text" name="edit[create_name]" value="" /></td></tr>';
  $body[] = '<tr><td>Description:</td><td><input type="text" name="edit[create_descr]" value="" /></td></tr>';
  $body[] = '</table>';
  $body[] = '</div></td></tr>';
  $body[] = '<tr><td>&nbsp;</td></tr>';
  $body[] = '<tr><td><div style="text-align:center">';
  $body[] = '<em>You are logged in as <strong>'.$user->name.'</strong></em><br />';
  if (isset($message)) {
    $body[] = '<div style="color:red;font-weight:bold;">'.$message.'</div>';
  }
  $body[] = '</div></td></tr>';
  $body[] = '</table>';
  $body[] = '<input type="hidden" name="cmd" value="album">';
  $body[] = '<input type="hidden" name="lcid" value="'.check_plain($_REQUEST['lcid']).'">';
  $body[] = '<input type="hidden" name="langid" value="'.check_plain($_REQUEST['langid']).'">';
  $body[] = '<input type="hidden" name="'.session_name().'" value="'.check_plain(session_id()).'">';
  //$body[] = '<input type="submit" value="Submit" />';
  $body[] = '</form>';
  $body[] = '';

  _image_pub_xp_page(implode("\r\n", $body), 'album');
}


/*
 * Concoct a magic ecmascript to configure the XP publishing wizard
 * to perform the required image submission tasks.
 */
function _image_pub_xp_addimage_script($album) {
  $albumid = $album->tid;
?>
<html>
<head>
<script>
function OnBack() {
}
function OnNext() {
}
function window.onload() {
	window.external.SetWizardButtons(true,true,true);
}

var xml = window.external.Property("TransferManifest");
var files = xml.selectNodes("transfermanifest/filelist/file");

for (i = 0; i < files.length; i++) {
	var postTag = xml.createNode(1, "post", "");
	postTag.setAttribute("href", "<?php echo url('publish_xp', NULL, NULL, TRUE); ?>");
	postTag.setAttribute("name", "userfile");

	var dataTag = xml.createNode(1, "formdata", "");
	dataTag.setAttribute("name", "albumid");
	dataTag.text = "<?php echo $albumid; ?>";
	postTag.appendChild(dataTag);

	dataTag = xml.createNode(1, "formdata", "");
	dataTag.setAttribute("name", "cmd");
	dataTag.text = "addimage";
	postTag.appendChild(dataTag);

	dataTag = xml.createNode(1, "formdata", "");
	dataTag.setAttribute("name", "<?php echo session_name(); ?>");
	dataTag.text = "<?php echo session_id(); ?>";
	postTag.appendChild(dataTag);

	dataTag = xml.createNode(1, "formdata", "");
	dataTag.setAttribute("name", "userfile_name");
	dataTag.text = files[i].getAttribute("destination");
	postTag.appendChild(dataTag);

	dataTag.setAttribute("name", "action");
	dataTag.text = "SAVE";
	postTag.appendChild(dataTag);

	files.item(i).appendChild(postTag);
}

var uploadTag = xml.createNode(1, "uploadinfo", "");
var htmluiTag = xml.createNode(1, "htmlui", "");
htmluiTag.text = "<?php echo url('image/tid/'.$albumid, NULL, NULL, TRUE); ?>";
uploadTag.appendChild(htmluiTag);

xml.documentElement.appendChild(uploadTag);

window.external.Property("TransferManifest")=xml;
window.external.SetWizardButtons(true,true,true);
window.external.FinalNext();

</script>
</head>
</html>
<?php
  exit;
}
