visual studio - C# Uploading image to Cheverto's upload.php -
i have c# application takes screenshots , creates image files. can't seem find out how create uploading method file path passed using cheverto's upload.php. cheverto image gallery system.
here there api: https://chevereto.com/docs/api-v1
here upload.php stored on server: https://pastebin.com/bu4ejavx
<?php namespace chv; use g, exception; class upload { // filename => name.ext // file => /full/path/to/name.ext // name => name public $source; public $uploaded; // sets type of resource being uploaded public function settype($type) { $this->type = $type; } // set source public function setsource($source) { $this->source = $source; $this->type = g\is_url($this->source) ? 'url' : 'file'; } // set destination public function setdestination($destination) { $this->destination = g\forward_slash($destination); } // set storage public function setstorageid($storage_id) { $this->storage_id = is_numeric($storage_id) ? $storage_id : null; } // set file basename public function setfilename($name) { $this->name = $name; } // set options public function setoptions($options) { $this->options = $options; } // set individual option public function setoption($key, $value) { $this->options[$key] = $value; } // default options public static function getdefaultoptions() { return array( 'max_size' => g\get_bytes('2 mb'), // should 'max_filesize' 'filenaming' => 'original', 'exif' => true, 'allowed_formats' => self::getavailableimageformats(), // array ); } /** * thing * @exeption 4xx */ public function exec() { // merge options $this->options = array_merge(self::getdefaultoptions(), (array) $this->options); $this->validateinput(); // exception 1 $this->fetchsource(); // exception 2 $this->validatesourcefile(); // exception 3 if(!is_array($this->options['allowed_formats'])) { $this->options['allowed_formats'] = explode(',', $this->options['allowed_formats']); } // save source name $this->source_name = g\get_filename_without_extension($this->type == "url" ? $this->source : $this->source["name"]); // set file extension $this->extension = $this->source_image_fileinfo["extension"]; // workaround $name if(!$this->name) { $this->name = $this->source_name; } // fix conflicting starting dots (some apache installs) $this->name = ltrim($this->name, '.'); // fix file extension if(g\get_file_extension($this->name) == $this->extension) { $this->name = g\get_filename_without_extension($this->name); } // set fixed filename $this->fixed_filename = preg_replace('/(.*)\.(th|md|original|lg)\.([\w]+)$/', '$1.$3', $this->name . '.' . $this->extension); // workaround jpeg exif data if($this->extension == 'jpg' , array_key_exists('exif', $this->options)) { $this->source_image_exif = null; if($this->options['exif']) { // fetch jpeg exif data (when available) if(function_exists('exif_read_data')) { $this->source_image_exif = @exif_read_data($this->downstream); if($this->source_image_exif) { $this->source_image_exif['filename'] = $this->source_filename; } } } else { // remove jpeg exif data $img = imagecreatefromjpeg($this->downstream); if($img) { imagejpeg($img, $this->downstream, 90); imagedestroy($img); } } } /* * set uploaded_file * local storage uploads allocated @ target destination * external storage allocated temp directory */ $this->uploaded_file = g\name_unique_file($this->destination, $this->options['filenaming'], $this->fixed_filename); $this->source = [ 'filename' => $this->source_filename, // file.ext 'name' => $this->source_name, // file 'image_exif' => $this->source_image_exif, // exif-data array 'fileinfo' => g\get_image_fileinfo($this->downstream), // fileinfo array ]; // fix image orientation if($this->source_image_exif , $this->source_image_exif["orientation"]) { $this->fiximageorientation($this->downstream, $this->source_image_exif); } $uploaded = @rename($this->downstream, $this->uploaded_file); @unlink($this->downstream); if(file_exists($this->downstream)) { error_log("warning: temp file " . $this->downstream . "wasn't removed."); } if(!$uploaded) { throw new uploadexception("can't move temp file destination", 400); } // php environments if(!$this->storage_id) { @chmod($this->uploaded_file, 0644); } $this->uploaded = array( 'file' => $this->uploaded_file, 'filename' => g\get_filename($this->uploaded_file), 'name' => g\get_filename_without_extension($this->uploaded_file), 'fileinfo' => g\get_image_fileinfo($this->uploaded_file) ); } // available (supported) extensions public static function getavailableimageformats() { $formats = settings::get('upload_available_image_formats'); return explode(',', $formats); } // failover since v3.8.12 public static function getenabledimageformats() { return image::getenabledimageformats(); } /** * validate_input aka "first stage validation" * checks valid input source data * @exception 1xx */ protected function validateinput() { $check_missing = ["type", "source", "destination"]; missing_values_to_exception($this, "chv\uploadexception", $check_missing, 100); // validate $type if(!preg_match("/^(url|file)$/", $this->type)) { throw new uploadexception('invalid $type "'.$this->type.'"', 110); } // handle flood $flood = self::handleflood(); if($flood) { throw new uploadexception(strtr('flood detected. can upload %limit% images per %time%', ['%limit%' => $flood['limit'], '%time%' => $flood['by']]), 130); } // validate $source if($this->type == 'file') { if(count($this->source) < 5) { // valid $_files ? throw new uploadexception("invalid file source", 120); } } else if($this->type == "url") { if(!g\is_image_url($this->source) && !g\is_url($this->source)) { throw new uploadexception("invalid image url", 122); } } // validate $destination if(!is_dir($this->destination)) { // try create missing directory $base_dir = g\add_ending_slash(g_root_path . explode('/', preg_replace('#'.g_root_path.'#', '', $this->destination, 1))[0]); $base_perms = fileperms($base_dir); $old_umask = umask(0); $make_destination = mkdir($this->destination, $base_perms, true); chmod($this->destination, $base_perms); umask($old_umask); if(!$make_destination) { throw new uploadexception('$destination '.$this->destination.' not dir', 130); } } // can read $destination dir? if(!is_readable($this->destination)) { throw new uploadexception("can't read target destination dir", 131); } // can write $destination dir? if(!is_writable($this->destination)) { throw new uploadexception("can't write target destination dir", 132); } // fix $destination trailing $this->destination = g\add_ending_slash($this->destination); } /** * fetch $source file * @exception 2xx */ protected function fetchsource() { // set downstream file $this->downstream = @tempnam(sys_get_temp_dir(), 'chvtemp'); if(!$this->downstream || !@is_writable($this->downstream)) { $this->downstream = @tempnam($this->destination, 'chvtemp'); if(!$this->downstream) { throw new uploadexception("can't tempnam", 200); } } if($this->type == 'file') { if($this->source['error'] !== upload_err_ok) { switch($this->source['error']) { case upload_err_ini_size: // 1 throw new uploadexception('file big', 201); break; case upload_err_form_size: // 2 throw new uploadexception('file exceeds form max size', 201); break; case upload_err_partial: // 3 throw new uploadexception('file partially uploaded', 201); break; case upload_err_no_file: // 4 throw new uploadexception('no file uploaded', 201); break; case upload_err_no_tmp_dir: // 5 throw new uploadexception('missing temp folder', 201); break; case upload_err_cant_write: // 6 throw new uploadexception('system write error', 201); break; case upload_err_extension: // 7 throw new uploadexception('the upload stopped', 201); break; } } if(!@rename($this->source['tmp_name'], $this->downstream)) { throw new uploadexception("can't move temp file target upload dir", 203); } } else if($this->type == "url") { try { g\fetch_url($this->source, $this->downstream); } catch(exception $e) { throw new uploadexception($e->getmessage(), 202); } } $this->source_filename = basename($this->type == "file" ? $this->source["name"] : $this->source); } protected function fiximageorientation($image_filename, $exif) { if($exif['orientation'] == 1) return; switch($this->extension) { case 'jpg': $image = imagecreatefromjpeg($image_filename); break; } switch($exif['orientation']) { case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, -90, 0); break; case 8: $image = imagerotate($image, 90, 0); break; } imagejpeg($image, $image_filename, 90); } /** * validate_source_file aka "second stage validation" * checks valid input source data * @exception 3xx */ protected function validatesourcefile() { // nothing here if(!file_exists($this->downstream)) { throw new uploadexception("can't fetch target upload source (downstream)", 300); } $this->source_image_fileinfo = g\get_image_fileinfo($this->downstream); // file info? if(!$this->source_image_fileinfo) { throw new uploadexception("can't target upload source info", 310); } // valid image fileinto? if($this->source_image_fileinfo['width'] == '' || $this->source_image_fileinfo['height'] == '') { throw new uploadexception("invalid image", 311); } // available image format? if(!in_array($this->source_image_fileinfo['extension'], self::getavailableimageformats())) { throw new uploadexception("unavailable image format", 313); } // enabled image format? if(!in_array($this->source_image_fileinfo['extension'], $this->options['allowed_formats'])) { throw new uploadexception(sprintf("disabled image format (%s)", $this->source_image_fileinfo['extension']), 314); } // mime if(!$this->isvalidimagemime($this->source_image_fileinfo["mime"])) { throw new uploadexception("invalid image mimetype", 312); } // size if(!$this->options['max_size']) { $this->options['max_size'] = self::getdefaultoptions()['max_size']; } if($this->source_image_fileinfo["size"] > $this->options["max_size"]) { throw new uploadexception("file big - max " . g\format_bytes($this->options["max_size"]), 313); } // bmp? if($this->source_image_fileinfo['extension'] == 'bmp') { $this->imageconvert = new imageconvert($this->downstream, "png", $this->downstream); $this->downstream = $this->imageconvert->out; $this->source_image_fileinfo = g\get_image_fileinfo($this->downstream); } } // handle flood uploads protected static function handleflood() { $logged_user = login::getuser(); if(!getsetting('flood_uploads_protection') || $logged_user['is_admin']) { return false; } $flood_limit = []; foreach(['minute', 'hour', 'day', 'week', 'month'] $v) { $flood_limit[$v] = getsetting('flood_uploads_' . $v); } try { $db = db::getinstance(); $flood_db = $db->queryfetchsingle( "select count(if(image_date_gmt >= date_sub(utc_timestamp(), interval 1 minute), 1, null)) minute, count(if(image_date_gmt >= date_sub(utc_timestamp(), interval 1 hour), 1, null)) hour, count(if(image_date_gmt >= date_sub(utc_timestamp(), interval 1 day), 1, null)) day, count(if(image_date_gmt >= date_sub(utc_timestamp(), interval 1 week), 1, null)) week, count(if(image_date_gmt >= date_sub(utc_timestamp(), interval 1 month), 1, null)) month ".db::gettable('images')." image_uploader_ip='".g\get_client_ip()."' , image_date_gmt >= date_sub(utc_timestamp(), interval 1 month)"); } catch(exception $e) {} // silence $is_flood = false; $flood_by = ''; foreach(['minute', 'hour', 'day', 'week', 'month'] $v) { if($flood_limit[$v] > 0 , $flood_db[$v] >= $flood_limit[$v]) { $flood_by = $v; $is_flood = true; break; } } if($is_flood) { if(getsetting('flood_uploads_notify') , !$_session['flood_uploads_notify'][$flood_by]) { try { $message = strtr('flooding ip <a href="'.g\get_base_url('search/images/?q=ip:%ip').'">%ip</a>', ['%ip' => g\get_client_ip()]) . '<br>'; if($logged_user) { $message .= 'user <a href="'.$logged_user['url'].'">'.$logged_user['name'].'</a><br>'; } $message .= '<br>'; $message .= '<b>uploads per time period</b>'."<br>"; $message .= 'minute: '.$flood_db['minute']."<br>"; $message .= 'hour: '.$flood_db['hour']."<br>"; $message .= 'week: '.$flood_db['day']."<br>"; $message .= 'month: '.$flood_db['week']."<br>"; system_notification_email(['subject' => 'flood report ip '. g\get_client_ip(), 'message' => $message]); $_session['flood_uploads_notify'][$flood_by] = true; } catch(exception $e) {} // silence } return ['flood' => true, 'limit' => $flood_limit[$flood_by], 'count' => $flood_db[$flood_by], 'by' => $flood_by]; } return false; } protected function isvalidimagemime($mime) { return preg_match("@image/(gif|pjpeg|jpeg|png|x-png|bmp|x-ms-bmp|x-windows-bmp)$@", $mime); } protected function isvalidnamingoption($string) { return in_array($string, array("mixed", "random", "original")); } } class uploadexception extends exception {}
thank or guidance!
Comments
Post a Comment