<?php


$WRITE_HTACCESS = true;


//-------------------------------------------
// http_get: get a file from a given URL
// (could use this to load a remote image)
// (however, is not used here ...)
//-------------------------------------------

function http_get($url)
{
   $url_stuff = parse_url($url);
   $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

   $fp = fsockopen($url_stuff['host'], $port);

   $query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
   $query .= 'Host: ' . $url_stuff['host'];
   $query .= "\n\n";

   fwrite($fp, $query);

   while ($tmp = fread($fp, 1024))
   {
       $buffer .= $tmp;
   }

   preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
   return substr($buffer, - $parts[1]); 
}




function save_pic($file,$pic){

  //create the needed subdirectories for this file
  $elements = explode("/", $file);
  $cwd = getcwd();
  for($i = 0; $i < (count($elements) - 1); $i++){
    my_mkdir($elements[$i], 0755);
    @chdir($elements[$i]);
  }
  @chdir($cwd);

  // Let's make sure the file exists and is writable first.
  //  if (!is_writable($file)) { echo "file $cwd/$file not writable!";return false; }
  if (!$handle = fopen($file, 'w')) { echo "cannot open file $file!";return false; }
  
  if (fwrite($handle, $pic) === FALSE) {
    echo "Cannot write to file ($file)";
    exit;
  }
  fclose($handle);
}



function postpic_form($file,$remote,$name){
  global $POSTBLOG;
  if (isset($POSTBLOG)){
    $html = '<form action="'.$POSTBLOG.'add_picpost.php" method="POST">';
    $html.='<input type="hidden" name="user" value="'.$_SESSION['user'].'" />';
    $html.='<input type="hidden" name="pass" value="'.$_SESSION['pass'].'" />';
    $html.=' <input type="submit" value="post as"> ';
    $html.='<input name="pic" value="'.$remote.'" />';
    $img = join("", file($file));
    $html.='<input type="hidden" name="img" value="'.base64_encode($img).'">';
    //    $html.=$name;
    $html.='</form>';
    return $html;
  }
  else{
    $html .= '<a href="'.$POSTBLOG.'add_picpost.php?pic=';
    $html .= $file . '">';
    $html .= '<img src="filemanager.php?image=file" alt="post" /></a> ';
    $html .= $name;
    return $html;
  }
}


function email_pic_form($album,$pic){

  global $UPLOADEMAIL;
  global $UPLOADSUBJECT;
  global $page;

  $html = '<form action="'.$POSTBLOG.'gallery.php" method="POST">';
  $html.='<input type="hidden" name="album" value="'.$album.'" />';
  if ($pic == null){
    $html.='<input type="hidden" name="page" value="'.$page.'" />';
    $html.='Send album to: ';
  }
  else{
    $html.='<input type="hidden" name="pic" value="'.$pic.'" />';
    $html.='Send picture to: ';
  }
  $html.='<input size="15" type="text" name="email" value="'.$UPLOADEMAIL.'" />';
  $html.=' Subject: ';
  $html.='<input size="15" type="text" name="subject" value="'.$UPLOADSUBJECT.'" />';
  $html.=' <input type="submit" name="send" value="send e-mail"> ';
  $html.='</form>';
  return $html;
}



function email_pic($email,$album,$pic,$subject){

  if (!isset($pic)){
    $liste = getPictureList($album);
    $ok = 1;
    foreach ($liste as $pic){
      $ok *= email_pic($email,$album,$pic,$subject);
    }
    return $ok;
  }

  $fileatt = getPictureURL($album,$pic);
  if (!file_exists($fileatt)){
    echo "cannot find ".$fileatt;
    return false;
  }

  $fileatt_type = "application/octet-stream"; // File Type 
  // Filename that will be used for the file as the attachment 
  $fileatt_name = basename($fileatt); 


  //  $email_from = "blog@blog"; // Who the email is from 
  global $blog_config;
  $email_from = $blog_config[ 'blog_email' ];
  $email_subject = $subject; // The Subject of the email 
  $email_txt = "Picture sent from ..."; // Message that the email has in it 

  $email_to = $email; // Who the email is too 

  $headers = "From: ".$email_from; 

  $file = fopen($fileatt,'rb'); 
  $data = fread($file,filesize($fileatt)); 
  fclose($file); 

  $semi_rand = md5(time()); 
  $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
   
  $headers .= "\r\nMIME-Version: 1.0\r\n" . 
    "Content-Type: multipart/mixed;\r\n" . 
    " boundary=\"{$mime_boundary}\""; 

  $email_message .= "This is a multi-part message in MIME format.\n\n" . 
    "--{$mime_boundary}\r\n" . 
    "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . 
    "Content-Transfer-Encoding: 7bit\n\n" . 
    $email_message . "\n\n"; 

  $data = chunk_split(base64_encode($data)); 

  $email_message .= "--{$mime_boundary}\n" . 
    "Content-Type: {$fileatt_type};\n" . 
    " name=\"{$fileatt_name}\"\n" . 
    //"Content-Disposition: attachment;\n" . 
    //" filename=\"{$fileatt_name}\"\n" . 
    "Content-Transfer-Encoding: base64\n\n" . 
    $data . "\n\n" . 
    "--{$mime_boundary}--\n"; 

  echo "sending ".$pic." to ".$email_to." ...\n";
  flush();ob_flush();
  if (@mail($email_to, $email_subject, $email_message, $headers)){
    echo " success!<br />";
  }
  else{
    echo " failure!<br />";
  }
  flush();ob_flush();
}



function img_post_button($album,$pic,$img_src){
  global $album_directory;

  $pichtml.='<table><tr>';
  $url = makeURL("",array("album"=>"$album","pic"=>$pic,"rotate"=>"90"));
  $pichtml = '<td><a href="'.$url.'"><img border="0" src="interface/gallery/rotate_ccw.png" alt="rotate counter clock wise"/></a></td>';

  $img = $img_src;
  if (validScaledExists($img)) {
    $img = getScaledURL($img);
  }

  $pichtml .= '<td>';
  $pichtml .= postpic_form($img,$img_src,$picname);

  if (file_exists($album_directory.'/'.$album.'/'.$pic.'.bak')){
    $url = makeURL("",array("album"=>"$album","pic"=>$pic,"filter"=>"undo"));
    $pichtml .= '<td><a href="'.$url.'"><img border="0" alt="undo" src="interface/gallery/undo.png" alt="undo"/></a></td>';
  }
  
  $url = makeURL("",array("album"=>"$album","pic"=>$pic,"filter"=>"grey"));
  $pichtml .= '<td><a href="'.$url.'"><img border="0" alt="greyscale" src="interface/gallery/bw.png" alt="black&mp;white" /></a></td>';
  $pichtml .= '</td>';
  $url = makeURL("",array("album"=>"$album","pic"=>$pic,"rotate"=>"270"));
  $pichtml .= '<td><a href="'.$url.'"><img border="0" src="interface/gallery/rotate_cw.png" alt="rotate clock wise" /></a></td></tr></table><br />';
  return $pichtml;

}


function upload_pic_form($album){

  $html .= '<form enctype="multipart/form-data" action="gallery.php" 
      method="POST">';
  $html .= '<input type="hidden" name="album" value="'.$album.'">';
  $html .= '<input name="file" size="10" type="file">';
  $html .= '<input name="upload" type="submit" value="upload">';
  $html .= '</form>';
  return $html;
}


function protect_album_form($album){

  $html .= '<form enctype="multipart/form-data" action="gallery.php" 
      method="POST">';
  $html .= '<input type="hidden" name="album" value="'.$album.'">';
  $html .= '<input name="protect" type="submit" value="set password">';
  $html .= '<input name="password" size="10" type="password">';
  $html .= '</form>';
  return $html;

}

// protect images with .htaccess from
// http://www.scriptygoddess.com/archives/2002/05/07/protect-your-images-with-htaccess/
//
// more about how to avoid hotlinking:
// http://altlab.com/htaccess_tutorial.html
// http://www.htmlbasix.com/disablehotlinking.shtml


function protect_album($album,$password){
  global $album_directory;
  global $data_directory;

  $albumdir = $album_directory.'/'.$album;
  $scaleddir = $data_directory.'/scaled/'.$album_directory.'/'.$album;
  $thumbsdir = $data_directory.'/thumbs/'.$album;

  if ($WRITE_HTACCESS){
    if ($fh = @fopen($thumbsdir.'/.htaccess','w+')){
      @flock( $fh, LOCK_EX );
      @fwrite($fh,"RewriteEngine on\n");
      @fwrite($fh,'RewriteCond %{HTTP_REFERER} !^$'."\n");
      @fwrite($fh,'RewriteCond %{HTTP_REFERER} !^http://(www\.)?');
      @fwrite($fh,$_SERVER['SERVER_NAME'].'(/)?.*$ [NC]'."\n");
      @fwrite($fh,'ReWriteRule .*\.(jpg|jpeg|gif|png)$  - [R,NC]'."\n");
      //    @fwrite($fh,'ReWriteRule .*\.(jpg|jpeg|gif|png)$ ');
      //    @fwrite($fh,'http://'.$_SERVER['SERVER_NAME'].'/'.$_SERVER['PHP_SELF']);
      //    @fwrite($fh,' [R,NC]'."\n");
      $lock = @flock( $fh, LOCK_UN );
      @fclose($fh);
    }
    @copy($thumbsdir.'/.htaccess',$scaleddir.'/.htaccess');
    @copy($thumbsdir.'/.htaccess',$albumdir.'/.htaccess');
  }
  if (!file_exists($thumbsdir.'/index.php')){
    if ($fh = @fopen($thumbsdir.'/index.php','w+')){
      @flock( $fh, LOCK_EX );
      @fwrite($fh,'<?php header("Location: ');
      @fwrite($fh,'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']);
      @fwrite($fh,'"); ?>');
      $lock = @flock( $fh, LOCK_UN );
      @fclose($fh);
      if (!@file_exists($scaleddir.'/index.php')){
	@copy($thumbsdir.'/index.php',$scaleddir.'/index.php');
      }
      if (!@file_exists($albumdir.'/index.php')){
	@copy($thumbsdir.'/index.php',$albumdir.'/index.php');
      }
    }
  }

  $dir = $data_directory.'/thumbs/'.$album;
  $crypted = crypt($password); 

  $str = "<?php \$album_password = '".$crypted."'; ?>\n";

  if (file_exists($dir.'/.passwd.php')){
    chmod($dir.'/.passwd.php',0644);
  }

  if ($fh = @fopen($dir.'/.passwd.php','w+')){
    @flock( $fh, LOCK_EX );
    $result = @fwrite( $fh, $str );
    $lock = @flock( $fh, LOCK_UN );
    @fclose( $fh );
    if (file_exists($dir.'/.passwd.php')){
      chmod($dir.'/.passwd.php',0444);
      return true;
    }
  }
  return false;
}


function release_album($album){
  global $album_directory;
  global $data_directory;

  $albumdir = $album_directory.'/'.$album;
  $scaleddir = $data_directory.'/scaled/'.$album_directory.'/'.$album;
  $thumbsdir = $data_directory.'/thumbs/'.$album;

  if (file_exists($thumbsdir.'/.passwd.php')){
    if (@unlink($thumbsdir.'/.passwd.php')){
      return true;
    }
    return false;
  }
  return true;
}



function create_album($root,$album){
  global $album_directory;
  if (!is_dir($album_directory.'/'.$root)){
    //    echo $album_directory.'/'.$root.' is no directory!<br />';
    return false;
  }
  if (file_exists($album_directory.'/'.$root.'/'.$album)){
    //    echo $album_directory.'/'.$root.'/'.$album.' exists already!<br />';
    return false;
  }
  if (is_virtual_album($root.'/'.$album)){
    //    echo $album_directory.'/'.$root.'/'.$album.' exists already!<br />';
    return false;
  }

  if (strlen($album)>50){
    echo 'album name "'.$album.'" is too long (max 50 characters)<br />';
    return false;
  }
  $album = str_replace(' ','_',$album);
  if (!preg_match('/^[a-zA-Z0-9\_\-]+$/',$album)){
    echo ("Album name '$album' not allowed!<br />Use the following characters only: [a-z0-9_- ]");
    return false;
  }

  if (!my_mkdir($album_directory.'/'.$root.'/'.$album,0755)){
    echo 'Cannot create directory '.$album_directory.'/'.$root.'/'.$album.'<br />';
    return false;
  }
  return true;
}






function add_to_virtual_album($album,$pic){
  $album_file = virtual_album_file($album);
  if ($fh = fopen($album_file, 'a')){
    fwrite($fh, $pic."\n");
    fclose($fh);
    return true;
  }
  return false;
}


function remove_from_virtual_album($album,$index,$pic){
  $pics = read_virtual_album($album);
  $album_file = virtual_album_file($album);

  // overwriting the old album final
  // this is a critical point
  // --> would not use in a multi-user environment
  // (assume that there is only one administrator logged in at a time)

  if ($fh = fopen($album_file,'w')){
    foreach ($pics as $i => $p){
       if (($i != $index) || ($p != $pic)){
	fwrite($fh,$p."\n");
      }
    }
    fclose($fh);
    return true;
  }
  return false;
}





function upload_picture(){
  global $album_directory;
  global $pic_extentions;

  $album = $_POST['album'];
  if (!is_dir($album_directory.'/'.$album)){
    echo $album_directory.'/'.$album. ' is no valid directory!<br />';
    return false;
  }
  if ( $_FILES['file']['error'] != 0 ) {
     echo "There is an error with your upload!<br />";
     return false;
  }
   $file = $_FILES['file']['name'];

   if (!preg_match($pic_extentions,$file)){
     echo "Couldn't recognize a valid file extension (".$pic_extentions.')<br />';
     return false;
   }

   /*
   if (getimagesize($_FILES['userfile']['tmp_name']) == FALSE){
     echo "This doesn't seem to be an image!<br />";
     return false;
   }
   */

   $dir = $album_directory.'/'.$album;
   $file = preg_replace('/[^a-zA-Z0-9\.\-\_]/','_',$file);
   if (file_exists($dir.'/'.$file)){
     $count=0;
     while (file_exists($dir.'/'."$count".$file)){
       $count++;
     }
     $uploadfile = $dir.'/'."$count".$file;
   }
   else{
     $uploadfile = $dir.'/'.$file;
   }

   if (! @move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile ) ) {
     echo "Couldn't move the file to ".$uploadfile.'<br />';
     return false;
   }
   //   echo 'Upload ok!<br />';
   return true;
}





function set_album_style_form($album,$pic=null){
  global $lang_string;

  $current = album_style($album);

  $html .= '<form enctype="multipart/form-data" action="gallery.php" 
      method="POST">';
  $html .= '<input type="hidden" name="album" value="'.$album.'">';
  if ($pic!=null){
    $html .= '<input type="hidden" name="pic" value="'.$pic.'">';
  }
  $html .= $lang_string['set_album_style'];
  $html .= '<select onchange="submit();" name="blog_album_style">';
  $styles = picture_page_styles();
  foreach ($styles as $style){
    if ($current==$style){
      $html .= '<option selected="1">'.$style.'</option>';
    }
    else{
      $html .= '<option>'.$style.'</option>';
    }
  }
  $html .= '</select>';
  //  $html .= '<input name="set_style" type="submit" value="style">';
  $html .= '</form>';
  return $html;

}


function set_album_style($album,$style){
  global $album_directory;
  global $data_directory;

  $stylefile = $data_directory.'/thumbs/'.$album.'.sty';

  if ($fh = @fopen($stylefile,'w+')){
    @flock( $fh, LOCK_EX );
    @fwrite($fh,$style);
    $lock = @flock( $fh, LOCK_UN );
    @fclose($fh);
    return true;
  }
  return false;
}



function set_album_description($album,$description){
  global $data_directory;

  $dir = $data_directory . '/thumbs/' . $album;

  if (!is_dir($dir)){
    global $album_directory;
    $dir = $album_directory . '/' . $album;
    if (!is_dir($dir)){return false;}
  }

  $file = $dir .'/description.txt';

  if ($fh = @fopen($file,'w+')){
    @flock( $fh, LOCK_EX );
    @fwrite($fh,$description);
    $lock = @flock( $fh, LOCK_UN );
    @fclose($fh);
    return true;
  }
  return false;
}


function pic_description_form($album,$pic,$description){
  global $lang_string;
    $html = '<form method="post">';
    $html .= '<input type="hidden" name="album" value="'.$album.'" />';
    $html .= '<input type="hidden" name="pic" value="'.$pic.'" />';
    //global $theme_vars;
    global $blog_config;
    $width = $blog_config['blog_max_pic_width'] - 100;
    $html .= $lang_string['pic_description'].'<br />';
    //$html .= '<textarea style="width: '.$theme_vars['max_image_width'];
    //$html .= 'px;" name="description" rows="2">';
    $html .= '<textarea style="width: '.$width;
    $html .= 'px;" name="description" rows="2">';
    $html .= $description;
    $html .= '</textarea><br />';
    $html .= '<input type="submit" name="change" value="';
    $html .= $lang_string['sb_edit'];
    $html .= '" />';
    $html .= '</form>';
    return $html;
}


function set_pic_description($album,$pic,$description){
  global $data_directory;

  $dir = $data_directory . '/thumbs/' . $album;

  if (!is_dir($dir)){
    global $album_directory;
    $dir = $album_directory . '/' . $album;
    if (!is_dir($dir)){return false;}
  }

  $file = $dir .'/'.$pic.'.txt';

  if ($fh = @fopen($file,'w+')){
    @flock( $fh, LOCK_EX );
    @fwrite($fh,$description);
    $lock = @flock( $fh, LOCK_UN );
    @fclose($fh);
    return true;
  }
  return false;
}



?>
