Example #1
3
 function show()
 {
     $folder = 'tmp/';
     if (isset($_REQUEST['qqfile'])) {
         $file = $_REQUEST['qqfile'];
         $path = $folder . $file;
         $input = fopen("php://input", "r");
         $temp = tmpfile();
         $realSize = stream_copy_to_stream($input, $temp);
         fclose($input);
         if ($realSize != $_SERVER["CONTENT_LENGTH"]) {
             die("{'error':'size error'}");
         }
         if (is_writable($folder)) {
             $target = fopen($path, 'w');
             fseek($temp, 0, SEEK_SET);
             stream_copy_to_stream($temp, $target);
             fclose($target);
             echo "{success:true, target:'{$file}'}";
         } else {
             die("{'error':'not writable: {$path}'}");
         }
     } else {
         $file = $_FILES['qqfile']['name'];
         $path = $folder . $file;
         if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)) {
             die("{'error':'permission denied'}");
         }
         echo "{success:true, target:'{$file}'}";
     }
 }
Example #2
0
 /**
  * Reports a single spam message.
  *
  * @param string $message  Message content.
  *
  * @return boolean  False on error, true on success.
  */
 protected function _report($message)
 {
     /* Use a pipe to write the message contents. This should be secure. */
     $proc = proc_open($this->_binary, array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
     if (!is_resource($proc)) {
         $this->_logger->err(sprintf('Cannot open spam reporting program: %s', $proc));
         return false;
     }
     if (is_resource($message)) {
         rewind($message);
         stream_copy_to_stream($message, $pipes[0]);
     } else {
         fwrite($pipes[0], $message);
     }
     fclose($pipes[0]);
     $stderr = '';
     while (!feof($pipes[2])) {
         $stderr .= fgets($pipes[2]);
     }
     fclose($pipes[2]);
     proc_close($proc);
     if (!empty($stderr)) {
         $this->_logger->err(sprintf('Error reporting spam: %s', $stderr));
         return false;
     }
     return true;
 }
Example #3
0
 /**
  * Copies a file or directory.
  * @return void
  * @throws Nette\IOException
  */
 public static function copy($source, $dest, $overwrite = TRUE)
 {
     if (stream_is_local($source) && !file_exists($source)) {
         throw new Nette\IOException("File or directory '{$source}' not found.");
     } elseif (!$overwrite && file_exists($dest)) {
         throw new Nette\InvalidStateException("File or directory '{$dest}' already exists.");
     } elseif (is_dir($source)) {
         static::createDir($dest);
         foreach (new \FilesystemIterator($dest) as $item) {
             static::delete($item);
         }
         foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) {
             if ($item->isDir()) {
                 static::createDir($dest . '/' . $iterator->getSubPathName());
             } else {
                 static::copy($item, $dest . '/' . $iterator->getSubPathName());
             }
         }
     } else {
         static::createDir(dirname($dest));
         if (@stream_copy_to_stream(fopen($source, 'r'), fopen($dest, 'w')) === FALSE) {
             // @ is escalated to exception
             throw new Nette\IOException("Unable to copy file '{$source}' to '{$dest}'.");
         }
     }
 }
Example #4
0
function extendfile($path, $len, $maxlen)
{
    $currlen = 0;
    if (file_exists($path)) {
        $currlen = filesize($path);
    }
    if ($currlen < $maxlen) {
        $err = createdirs($path, 0);
        if ($err != 0) {
            return $err;
        }
        $zero = fopen('/dev/zero', 'r');
        if (!$zero) {
            return 2;
        }
        $dest = fopen($path, 'a');
        if (!$dest) {
            return 2;
        }
        stream_copy_to_stream($zero, $dest, min($len, $maxlen - $currlen));
        fclose($zero);
        fclose($dest);
    }
    return 0;
}
Example #5
0
 public static function handleUpload()
 {
     echo "0\n";
     //register_shutdown_function(array('cc_Ajax_Upload', 'shutdown'));
     echo "1\n";
     $headers = getallheaders();
     if (!(isset($headers['Content-Type'], $headers['Content-Length'], $headers['X-File-Size'], $headers['X-File-Name']) && $headers['Content-Length'] === $headers['X-File-Size'])) {
         exit('Error');
     }
     echo "A\n";
     $maxSize = 80 * 1024 * 1024;
     if (false === (self::$tmpfile = tempnam('tmp', 'upload_'))) {
         exit(json_encode(array('status' => 'error', 'filename' => 'temp file not possible')));
     }
     echo "A\n";
     $fho = fopen(self::$tmpfile, 'w');
     $fhi = fopen('php://input', 'r');
     $tooBig = $maxSize <= stream_copy_to_stream($fhi, $fho, $maxSize);
     echo "A\n";
     if ($tooBig) {
         exit(json_encode(array('status' => 'error', 'filename' => 'upload too big')));
     }
     echo "A\n";
     exit(json_encode(array('status' => 'success', 'filename' => $headers['X-File-Name'])));
 }
Example #6
0
 public function combineChunks($uploadDirectory)
 {
     $uuid = $_POST['qquuid'];
     $name = $this->getName();
     $targetFolder = $this->chunksFolder . DIRECTORY_SEPARATOR . $uuid;
     $totalParts = isset($_REQUEST['qqtotalparts']) ? (int) $_REQUEST['qqtotalparts'] : 1;
     $target = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
     $this->uploadName = $name;
     if (!file_exists($target)) {
         mkdir(dirname($target));
     }
     $target = fopen($target, 'wb');
     for ($i = 0; $i < $totalParts; $i++) {
         $chunk = fopen($targetFolder . DIRECTORY_SEPARATOR . $i, "rb");
         stream_copy_to_stream($chunk, $target);
         fclose($chunk);
     }
     // Success
     fclose($target);
     for ($i = 0; $i < $totalParts; $i++) {
         unlink($targetFolder . DIRECTORY_SEPARATOR . $i);
     }
     rmdir($targetFolder);
     return array("success" => true, "uuid" => $uuid);
 }
Example #7
0
 /**
  * @param string $path
  */
 public function copyContentsToFile($path)
 {
     $fp = fopen($path, 'w');
     $this->seek(0);
     stream_copy_to_stream($this->phpStream, $fp);
     fclose($fp);
 }
Example #8
0
 function save($path)
 {
     $input = fopen("php://input", "r");
     $temp = tmpfile();
     $realSize = stream_copy_to_stream($input, $temp);
     fclose($input);
     if ($realSize != $this->getSize()) {
         return false;
     }
     /////////////////////////////////////////////////////
     $target = fopen(JPATH_SITE . "/tmp/" . basename($path), "w");
     fseek($temp, 0, SEEK_SET);
     stream_copy_to_stream($temp, $target);
     fclose($target);
     $extension = explode(".", $path);
     $extension_file = $extension[count($extension) - 1];
     if ($extension_file == 'jpg' || $extension_file == 'jpeg' || $extension_file == 'png' || $extension_file == 'gif' || $extension_file == 'JPG' || $extension_file == 'JPEG' || $extension_file == 'PNG' || $extension_file == 'GIF') {
         $image_size = getimagesize(JPATH_SITE . "/tmp/" . basename($path));
     }
     if (isset($image_size) && $image_size === FALSE) {
         unlink(JPATH_SITE . "/tmp/" . basename($path));
         return false;
     }
     unlink(JPATH_SITE . "/tmp/" . basename($path));
     /////////////////////////////////////////////////////
     $target = fopen($path, "w");
     fseek($temp, 0, SEEK_SET);
     stream_copy_to_stream($temp, $target);
     fclose($target);
     return true;
 }
 /**
  * Copies and transforms a file.
  *
  * This method only copies the file if the origin file is newer than the target file.
  *
  * By default, if the target already exists, it is not overridden.
  *
  * @param string  $originFile The original filename
  * @param string  $targetFile The target filename
  * @param boolean $override   Whether to override an existing file or not
  *
  * @throws IOException When copy fails
  */
 public function copy($originFile, $targetFile, $override = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new IOException(sprintf('Failed to copy %s because file does not exist', $originFile));
     }
     $this->mkdir(dirname($targetFile));
     if (!$override && is_file($targetFile)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     } else {
         $doCopy = true;
     }
     if (!$doCopy) {
         return;
     }
     $event = new FileCopyEvent($originFile, $targetFile);
     $event = $this->event_dispatcher->dispatch(FilesystemEvents::COPY, $event);
     $originFile = $event->getSource();
     $targetFile = $event->getTarget();
     if ($event->isModified()) {
         file_put_contents($targetFile, $event->getContent());
         return;
     }
     // No listeners modified the file, so just copy it (original behaviour & code)
     // https://bugs.php.net/bug.php?id=64634
     $source = fopen($originFile, 'r');
     $target = fopen($targetFile, 'w+');
     stream_copy_to_stream($source, $target);
     fclose($source);
     fclose($target);
     unset($source, $target);
     if (!is_file($targetFile)) {
         throw new IOException(sprintf('Failed to copy %s to %s', $originFile, $targetFile));
     }
 }
function localhost($r, $w)
{
    echo "<p>Read <b>{$r}</b>, Write <b>{$w}</b>\n";
    $fr = @fopen("http://www.google.com/", $r);
    if ($fr === false) {
        die('NO NETWORK CONNECTION!');
    }
    $fw = fopen("stream_copy_to_stream_{$r}_{$w}.txt", $w);
    echo "\n\nCOPIED: <b>" . stream_copy_to_stream($fr, $fw) . "</b>\n";
    fclose($fr);
    fclose($fw);
    /*
    $f = fopen("stream_copy_to_stream_${r}_${w}.txt", "rb");
     while (false !== ($c = fgetc($f)))
     {
     $c = (string)$c;
     //echo ord($c);
       if ($c == "\n") echo "[\\n]\n";
       else if ($c == "\r") echo "[\\r]\r";
       else if ($c == "<") echo "&lt;";
       else if ($c == ">") echo "&gt;";
       else echo $c;
     }
     fclose($f);
    */
    unlink("stream_copy_to_stream_{$r}_{$w}.txt");
}
Example #11
0
 function conf__formulario(toba_ei_formulario $form)
 {
     if ($this->s__mostrar == 1) {
         // si presiono el boton alta entonces muestra el formulario para dar de alta un nuevo registro
         $this->dep('formulario')->descolapsar();
         $form->ef('nro_norma')->set_obligatorio('true');
         $form->ef('tipo_norma')->set_obligatorio('true');
         $form->ef('emite_norma')->set_obligatorio('true');
         $form->ef('fecha')->set_obligatorio('true');
     } else {
         $this->dep('formulario')->colapsar();
     }
     if ($this->dep('datos')->esta_cargada()) {
         $datos = $this->dep('datos')->tabla('norma')->get();
         $fp_imagen = $this->dep('datos')->tabla('norma')->get_blob('pdf');
         if (isset($fp_imagen)) {
             $temp_nombre = md5(uniqid(time())) . '.pdf';
             $temp_archivo = toba::proyecto()->get_www_temp($temp_nombre);
             $temp_fp = fopen($temp_archivo['path'], 'w');
             stream_copy_to_stream($fp_imagen, $temp_fp);
             fclose($temp_fp);
             $tamano = round(filesize($temp_archivo['path']) / 1024);
             $datos['imagen_vista_previa'] = "<a target='_blank' href='{$temp_archivo['url']}' >norma</a>";
             $datos['pdf'] = 'tamano: ' . $tamano . ' KB';
         } else {
             $datos['pdf'] = null;
         }
         return $datos;
     }
 }
Example #12
0
 /**
  * Copies a file.
  *
  * This method only copies the file if the origin file is newer than the target file.
  *
  * By default, if the target already exists, it is not overridden.
  *
  * @param string  $originFile The original filename
  * @param string  $targetFile The target filename
  * @param bool    $override   Whether to override an existing file or not
  *
  * @throws FileNotFoundException    When originFile doesn't exist
  * @throws IOException              When copy fails
  */
 public function copy($originFile, $targetFile, $override = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
     }
     $this->mkdir(dirname($targetFile));
     if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     } else {
         $doCopy = true;
     }
     if ($doCopy) {
         // https://bugs.php.net/bug.php?id=64634
         if (false === ($source = @fopen($originFile, 'r'))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
         }
         if (false === ($target = @fopen($targetFile, 'w'))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
         }
         stream_copy_to_stream($source, $target);
         fclose($source);
         fclose($target);
         unset($source, $target);
         if (!is_file($targetFile)) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
         }
     }
 }
Example #13
0
 /**
  * Copies a file.
  *
  * This method only copies the file if the origin file is newer than the target file.
  *
  * By default, if the target already exists, it is not overridden.
  *
  * @param string  $originFile The original filename
  * @param string  $targetFile The target filename
  * @param bool    $override   Whether to override an existing file or not
  *
  * @throws IOException When copy fails
  */
 public function copy($originFile, $targetFile, $override = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new IOException(sprintf('Failed to copy %s because file not exists', $originFile));
     }
     $this->mkdir(dirname($targetFile));
     if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     } else {
         $doCopy = true;
     }
     if ($doCopy) {
         // https://bugs.php.net/bug.php?id=64634
         $source = fopen($originFile, 'r');
         // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
         $target = fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true))));
         stream_copy_to_stream($source, $target);
         fclose($source);
         fclose($target);
         unset($source, $target);
         if (!is_file($targetFile)) {
             throw new IOException(sprintf('Failed to copy %s to %s', $originFile, $targetFile));
         }
     }
 }
 protected function ajaxProcess()
 {
     $upload_path = $this->_getUploadPath();
     $newFilename = $this->_getNewFilename();
     $newFile = $upload_path . DIRECTORY_SEPARATOR . $newFilename;
     $input = fopen("php://input", "r");
     $temp_path = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . "tmp";
     if (!is_writable($temp_path)) {
         mkdir("{$temp_path}", 0777);
     }
     $tempFilename = tempnam($temp_path, 'temp_');
     $tempfile = fopen($tempFilename, 'w');
     $filesize = stream_copy_to_stream($input, $tempfile);
     fclose($tempfile);
     fclose($input);
     $filename = $this->options['file'];
     $file = array('name' => "{$filename}", 'tmp_name' => "{$tempFilename}");
     ApuImageCropper::getInstance()->crop($file, $newFilename, $this->options['context']);
     if (rename($tempFilename, $newFile)) {
         $this->uploadedFilename = $newFilename;
         $this->uploadedFilesize = $filesize;
         $this->_setOptions();
         $this->save();
     } else {
         $this->response = '{ "error" => "An error has occurred while trying to upload your image!", "e_id" : "' . $e_id . '" }';
     }
 }
Example #15
0
 /**
  * Save the file to the specified path
  * @return boolean TRUE on success
  */
 function save($path)
 {
     $input = fopen("php://input", "r");
     $temp = tmpfile();
     if (!$temp) {
         $temp = fopen("php://temp", "wb");
     }
     if (!$input || !$temp) {
         if ($input) {
             fclose($input);
         }
         return false;
     }
     $realSize = stream_copy_to_stream($input, $temp);
     fclose($input);
     if ($realSize != $this->getSize()) {
         return false;
     }
     $target = fopen($path, "w");
     if (!$target) {
         return false;
     }
     fseek($temp, 0, SEEK_SET);
     stream_copy_to_stream($temp, $target);
     fclose($target);
     return true;
 }
Example #16
0
 /**
  * Write a new file using a stream.
  *
  * @param string $path
  * @param resource $resource
  * @param Config $config
  * @return array|false
  */
 public function writeStream($path, $resource, Config $config)
 {
     $fullPath = $this->applyPathPrefix($path);
     $stream = $this->share->write($fullPath);
     stream_copy_to_stream($resource, $stream);
     return fclose($stream) ? compact('path') : false;
 }
Example #17
0
 /**
  * Save the file to the specified path
  * @return boolean TRUE on success
  */
 function save($path, $filename)
 {
     $input = fopen("php://input", "r");
     $temp = tmpfile();
     $realSize = stream_copy_to_stream($input, $temp);
     fclose($input);
     if ($realSize != $this->getSize()) {
         return false;
     }
     $target = fopen($path, "w");
     fseek($temp, 0, SEEK_SET);
     stream_copy_to_stream($temp, $target);
     fclose($target);
     //insert data into attachment table
     if (!class_exists('VmConfig')) {
         require JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart' . DS . 'helpers' . DS . 'config.php';
     }
     $thumb_width = VmConfig::loadConfig()->get('img_width');
     $user_s =& JFactory::getUser();
     $user_id = $user_s->id;
     $product_vm_id = JRequest::getInt('virtuemart_product_id');
     $database =& JFactory::getDBO();
     $gallery = new stdClass();
     $gallery->id = 0;
     $gallery->virtuemart_user_id = $user_id;
     $gallery->virtuemart_product_id = $product_vm_id;
     $gallery->file_name = $filename;
     $gallery->created_on = date('Y-m-d,H:m:s');
     if (!$database->insertObject('#__virtuemart_product_attachments', $gallery, 'id')) {
         echo $database->stderr();
         return false;
     }
     // end of insert data
     return true;
 }
 public function createFile($name, $data = null)
 {
     try {
         access::required("view", $this->item);
         access::required("add", $this->item);
     } catch (Kohana_404_Exception $e) {
         throw new Sabre_DAV_Exception_Forbidden("Access denied");
     }
     if (substr($name, 0, 1) == ".") {
         return true;
     }
     try {
         $tempfile = tempnam(TMPPATH, "dav");
         $target = fopen($tempfile, "wb");
         stream_copy_to_stream($data, $target);
         fclose($target);
         $item = ORM::factory("item");
         $item->name = $name;
         $item->title = item::convert_filename_to_title($item->name);
         $item->description = "";
         $item->parent_id = $this->item->id;
         $item->set_data_file($tempfile);
         $item->type = "photo";
         $item->save();
     } catch (Exception $e) {
         unlink($tempfile);
         throw $e;
     }
 }
 /**
  * Creates a new file in the directory
  *
  * Data will either be supplied as a stream resource, or in certain cases
  * as a string. Keep in mind that you may have to support either.
  *
  * After succesful creation of the file, you may choose to return the ETag
  * of the new file here.
  *
  * The returned ETag must be surrounded by double-quotes (The quotes should
  * be part of the actual string).
  *
  * If you cannot accurately determine the ETag, you should not return it.
  * If you don't store the file exactly as-is (you're transforming it
  * somehow) you should also not return an ETag.
  *
  * This means that if a subsequent GET to this new file does not exactly
  * return the same contents of what was submitted here, you are strongly
  * recommended to omit the ETag.
  *
  * @param string $name Name of the file
  * @param resource|string $data Initial payload
  * @return null|string
  */
 public function createFile($name, $data = null)
 {
     try {
         $name = ltrim($name, "/");
         AJXP_Logger::debug("CREATE FILE {$name}");
         AJXP_Controller::findActionAndApply("mkfile", array("dir" => $this->path, "filename" => $name), array());
         if ($data != null && is_file($this->getUrl() . "/" . $name)) {
             $p = $this->path . "/" . $name;
             $this->getAccessDriver()->nodeWillChange($p, intval($_SERVER["CONTENT_LENGTH"]));
             //AJXP_Logger::debug("Should now copy stream or string in ".$this->getUrl()."/".$name);
             if (is_resource($data)) {
                 $stream = fopen($this->getUrl() . "/" . $name, "w");
                 stream_copy_to_stream($data, $stream);
                 fclose($stream);
             } else {
                 if (is_string($data)) {
                     file_put_contents($data, $this->getUrl() . "/" . $name);
                 }
             }
             $toto = null;
             $this->getAccessDriver()->nodeChanged($toto, $p);
         }
         $node = new AJXP_Sabre_NodeLeaf($this->path . "/" . $name, $this->repository, $this->getAccessDriver());
         if (isset($this->children)) {
             $this->children = null;
         }
         return $node->getETag();
     } catch (Exception $e) {
         AJXP_Logger::debug("Error " . $e->getMessage(), $e->getTraceAsString());
         return null;
     }
 }
Example #20
0
 public function saveMusic($songs)
 {
     //exit();
     foreach ($songs as $singer => $album) {
         /*
          * enabled arg contains checkbox value from modal dialog
          */
         if ($album['enabled'] === false) {
             continue;
         }
         $folder = $this->destination() . '/' . self::stripPluses($singer);
         if (!is_dir($folder)) {
             mkdir($folder, 0774);
         }
         foreach ($album['music'] as $composition) {
             if ($composition['enabled'] === false) {
                 continue;
             }
             $file = $folder . '/' . self::stripPluses($composition['song']) . '.mp3';
             $link = $composition['link'];
             if (!is_file($file)) {
                 stream_copy_to_stream(fopen($link, 'r'), fopen($file, 'w'));
             }
         }
     }
     return true;
 }
 public function update()
 {
     /** @var $helper Sandfox_GeoIP_Helper_Data */
     $helper = Mage::helper('geoip');
     $ret = array('status' => 'error');
     if ($permissions_error = $this->checkFilePermissions()) {
         $ret['message'] = $permissions_error;
     } else {
         $remote_file_size = $helper->getSize($this->remote_archive);
         if ($remote_file_size < 100000) {
             $ret['message'] = $helper->__('You are banned from downloading the file. Please try again in several hours.');
         } else {
             /** @var $_session Mage_Core_Model_Session */
             $_session = Mage::getSingleton('core/session');
             $_session->setData('_geoip_file_size', $remote_file_size);
             $src = fopen($this->remote_archive, 'r');
             $target = fopen($this->local_archive, 'w');
             stream_copy_to_stream($src, $target);
             fclose($target);
             if (filesize($this->local_archive)) {
                 if ($helper->unGZip($this->local_archive, $this->local_file)) {
                     $ret['status'] = 'success';
                     $format = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
                     $ret['date'] = Mage::app()->getLocale()->date(filemtime($this->local_file))->toString($format);
                 } else {
                     $ret['message'] = $helper->__('UnGzipping failed');
                 }
             } else {
                 $ret['message'] = $helper->__('Download failed.');
             }
         }
     }
     echo json_encode($ret);
 }
Example #22
0
 public function store($handle)
 {
     if ($this->storeCopyFromStream) {
         stream_copy_to_stream($this->storeCopyFromStream, $handle);
     }
     return true;
 }
Example #23
0
 public function getProperDimensionsPictureUrl($yahooId, $pictureUrl)
 {
     $pictureUrl = str_replace('_normal', '', $pictureUrl);
     $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'le' . '/' . 'sociallogin' . '/' . 'yahoo' . '/' . $yahooId;
     $filename = Mage::getBaseDir(Mage_Core_Model_Store::URL_TYPE_MEDIA) . DS . 'le' . DS . 'sociallogin' . DS . 'yahoo' . DS . $yahooId;
     $directory = dirname($filename);
     if (!file_exists($directory) || !is_dir($directory)) {
         if (!@mkdir($directory, 0777, true)) {
             return null;
         }
     }
     if (!file_exists($filename) || file_exists($filename) && time() - filemtime($filename) >= 3600) {
         $client = new Zend_Http_Client($pictureUrl);
         $client->setStream();
         $response = $client->request('GET');
         stream_copy_to_stream($response->getStream(), fopen($filename, 'w'));
         $imageObj = new Varien_Image($filename);
         $imageObj->constrainOnly(true);
         $imageObj->keepAspectRatio(true);
         $imageObj->keepFrame(false);
         $imageObj->resize(150, 150);
         $imageObj->save($filename);
     }
     return $url;
 }
 public function combineChunks($uploadDirectory, $name = null)
 {
     $uuid = $_POST['qquuid'];
     if ($name === null) {
         $name = $this->getName();
     }
     $targetFolder = $this->chunksFolder . DIRECTORY_SEPARATOR . $uuid;
     $totalParts = isset($_REQUEST['qqtotalparts']) ? (int) $_REQUEST['qqtotalparts'] : 1;
     $targetPath = join(DIRECTORY_SEPARATOR, array($uploadDirectory, $uuid, $name));
     $this->uploadName = $name;
     if (!file_exists($targetPath)) {
         mkdir(dirname($targetPath), 0777, true);
     }
     $target = fopen($targetPath, 'wb');
     for ($i = 0; $i < $totalParts; $i++) {
         $chunk = fopen($targetFolder . DIRECTORY_SEPARATOR . $i, "rb");
         stream_copy_to_stream($chunk, $target);
         fclose($chunk);
     }
     // Success
     fclose($target);
     for ($i = 0; $i < $totalParts; $i++) {
         unlink($targetFolder . DIRECTORY_SEPARATOR . $i);
     }
     rmdir($targetFolder);
     if (!is_null($this->sizeLimit) && filesize($targetPath) > $this->sizeLimit) {
         unlink($targetPath);
         http_response_code(413);
         return array("success" => false, "uuid" => $uuid, "preventRetry" => true);
     }
     return array("success" => true, "uuid" => $uuid);
 }
 /**
  * Create a new RequestBody.
  */
 public function __construct()
 {
     $stream = fopen('php://temp', 'w+');
     stream_copy_to_stream(fopen('php://input', 'r'), $stream);
     rewind($stream);
     parent::__construct($stream);
 }
Example #26
0
 public function emit($cycle, $r = null)
 {
     $writer = $cycle->writer() ? $cycle->writer() : $cycle();
     if ($r) {
         if (is_callable($r)) {
             $r = $r();
         }
         if (is_resource($r) and get_resource_type($r) == 'stream') {
             //flush header
             $writer();
             $stream = $cycle->response()->getBody()->detach();
             stream_copy_to_stream($r, $stream);
             $cycle->response()->getBody()->attach($stream);
         } elseif (is_array($r) or $r instanceof \Traversable or $r instanceof \Generator) {
             foreach ($r as $part) {
                 $writer($part);
             }
         } else {
             $writer((string) $r);
         }
     } else {
         //flush if not
         $writer();
     }
 }
Example #27
0
 /**
  * Sends the HTTP response back to a HTTP client.
  *
  * This calls php's header() function and streams the body to php://output.
  *
  * @param ResponseInterface $response
  * @return void
  */
 static function sendResponse(ResponseInterface $response)
 {
     header('HTTP/' . $response->getHttpVersion() . ' ' . $response->getStatus() . ' ' . $response->getStatusText());
     foreach ($response->getHeaders() as $key => $value) {
         foreach ($value as $k => $v) {
             if ($k === 0) {
                 header($key . ': ' . $v);
             } else {
                 header($key . ': ' . $v, false);
             }
         }
     }
     $body = $response->getBody();
     if (is_null($body)) {
         return;
     }
     $contentLength = $response->getHeader('Content-Length');
     if ($contentLength !== null) {
         $output = fopen('php://output', 'wb');
         if (is_resource($body) && get_resource_type($body) == 'stream') {
             stream_copy_to_stream($body, $output, $contentLength);
         } else {
             fwrite($output, $body, $contentLength);
         }
     } else {
         file_put_contents('php://output', $body);
     }
     if (is_resource($body)) {
         fclose($body);
     }
 }
Example #28
0
 /**
  * Copies a file.
  *
  * This method only copies the file if the origin file is newer than the target file.
  *
  * By default, if the target already exists, it is not overridden.
  *
  * @param string $originFile The original filename
  * @param string $targetFile The target filename
  * @param bool   $override   Whether to override an existing file or not
  *
  * @throws FileNotFoundException When originFile doesn't exist
  * @throws IOException           When copy fails
  */
 public function copy($originFile, $targetFile, $override = false)
 {
     if (stream_is_local($originFile) && !is_file($originFile)) {
         throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile);
     }
     $this->mkdir(dirname($targetFile));
     if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) {
         $doCopy = filemtime($originFile) > filemtime($targetFile);
     } else {
         $doCopy = true;
     }
     if ($doCopy) {
         // https://bugs.php.net/bug.php?id=64634
         if (false === ($source = @fopen($originFile, 'r'))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile);
         }
         // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default
         if (false === ($target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))))) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile);
         }
         $bytesCopied = stream_copy_to_stream($source, $target);
         fclose($source);
         fclose($target);
         unset($source, $target);
         if (!is_file($targetFile)) {
             throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile);
         }
         if (stream_is_local($originFile) && $bytesCopied !== filesize($originFile)) {
             throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s %g bytes copied".', $originFile, $targetFile, $bytesCopied), 0, null, $originFile);
         }
     }
 }
Example #29
0
 /**
  * Get a content of the uploaded file
  *
  * @return string|array Content OR array with errors
  */
 function get_content()
 {
     $input = fopen('php://input', 'rb');
     $temp_file_name = '';
     $temp = open_temp_file($temp_file_name);
     if (is_string($temp)) {
         // Error on create a temp file
         return array('text' => $temp, 'status' => 'error');
     }
     stream_copy_to_stream($input, $temp);
     fclose($input);
     fseek($temp, 0, SEEK_SET);
     $contents = '';
     load_funcs('tools/model/_system.funcs.php');
     $memory_limit = system_check_memory_limit();
     while (!feof($temp)) {
         $curr_mem_usage = memory_get_usage(true);
         if ($memory_limit - $curr_mem_usage < 8192) {
             // Don't try to load the next portion of image into the memory because it would cause 'Allowed memory size exhausted' error
             fclose($temp);
             return array('text' => T_('The server (PHP script) has not enough available memory to receive this large file!'), 'status' => 'error');
         }
         $contents .= fread($temp, 8192);
     }
     fclose($temp);
     if (!empty($temp_file_name)) {
         // Unlink the temp file
         @unlink($temp_file_name);
     }
     return $contents;
 }
Example #30
-2
 public static function upload_large($file, $options = array())
 {
     $src = fopen($file, 'r');
     $temp_file_name = tempnam(sys_get_temp_dir(), 'cldupload.' + pathinfo($file, PATHINFO_EXTENSION));
     $upload = $upload_id = NULL;
     $public_id = \Cloudinary::option_get($upload, "public_id");
     $index = 1;
     while (!feof($src)) {
         $dest = fopen($temp_file_name, 'w');
         stream_copy_to_stream($src, $dest, 20000000);
         fclose($dest);
         try {
             $upload = Uploader::upload_large_part($temp_file_name, array_merge($options, array("public_id" => $public_id, "upload_id" => $upload_id, "part_number" => $index, "final" => feof($src))));
         } catch (\Exception $e) {
             unlink($temp_file_name);
             fclose($src);
             throw $e;
         }
         $upload_id = \Cloudinary::option_get($upload, "upload_id");
         $public_id = \Cloudinary::option_get($upload, "public_id");
         $index += 1;
     }
     unlink($temp_file_name);
     fclose($src);
     return $upload;
 }