/*
Download and save attachment from DB
15109
function(options, filename){	    
	    Joi.assert(filename, Joi.string())
	    return new Promise(function(resolve, reject){

	        try{	            

	            var writestream = fs.createWriteStream(filename);
	            request(options).pipe(writestream);

	            writestream.on('finish', function(err){                 
	                if(err){
	                    reject({
	                        "path" : filename,
	                        "status" : false,
	                        "error": err
	                    });
	                }else{
	                    resolve({
	                        "path" : filename,
	                        "status" : true
	                    });
	                }
	            });

	        }catch(e){
	            reject(e);
	        }
	    });
	}
1080942
function downloadZip($fileName, $contentType = "application/zip")
    {
        if (!$this->isFinalized) {
            $this->finalize();
        }

        $headerFile = null;
        $headerLine = null;
        if (!headers_sent($headerFile, $headerLine)) {
            if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$fileName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
                if (ini_get('zlib.output_compression')) {
                    ini_set('zlib.output_compression', 'Off');
                }

                header("Pragma: public");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s T"));
                header("Expires: 0");
                header("Accept-Ranges: bytes");
                header("Connection: close");
                header("Content-Type: " . $contentType);
                header('Content-Disposition: attachment; filename="' . $fileName . '";');
                header("Content-Transfer-Encoding: binary");
                header("Content-Length: " . $this->getArchiveSize());

                if (!is_resource($this->zipFile)) {
                    echo $this->zipData;
                } else {
                    rewind($this->zipFile);

                    while (!feof($this->zipFile)) {
                        echo fread($this->zipFile, $this->streamChunkSize);
                    }
                }
            }
            return TRUE;
        }
        return FALSE;
    }
411300
function download(url) {
        var a = document.createElement('a');
        a.href = url;
        a.setAttribute('download', 'doc');
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
912426
function downloadArchive(id, call, options, done)
	{
		grunt.log.write('Downloading '.gray + id.yellow + ' ... '.gray);

		request(call, function(err, response, body)
		{
			if (err) return done(err);

			var result = JSON.parse(body);

			if (!result.success) 
			{
				return done(result.error + ' with game "' + id + '"');
			}

			if (options.json)
			{
				grunt.log.write('Writing json ... '.gray);

				var writeStream = fs.createWriteStream(path.join(options.dest, id + '.json'));
				writeStream.write(JSON.stringify(result.data, null, options.debug ? "\t":""));
				writeStream.end();
			}

			grunt.log.write('Installing ... '.gray);

			this.get(result.data.url).run(function(err, files)
			{
				if (err) 
				{
					return done('Unable to download archive for game "' + id + '"');
				}
				grunt.log.writeln('Done.'.green);
				done(null, files);
			});
		}
		.bind(this));
	}
113061
function downloadMap(map) {
    let data = map.exportAsJSON(),
        json = JSON.stringify(data),
        blob = new Blob([json], {type: "application/json"}),
        a = document.createElement("a");

    a.download = "example.json";
    a.href = URL.createObjectURL(blob);
    a.click();
}
605987
function downloadWithCache(url, dir, name) {
  const filePath = path.resolve(dir, name);
  const md5Name = name + '-sha1.txt';
  const mdFile = path.resolve(dir, md5Name);

  var downloadAndWriteSha1 = function(url, toBeHashed) {
    logger.info(`start to download: ${url}`);

    const result = requestSync('GET', url);

    fs.writeFileSync(filePath, result.getBody());
    fs.writeFileSync(mdFile, toBeHashed, {
      encoding: 'utf8',
      flag: 'w'
    });
    logger.info(`download success: ${filePath}`);
    return filePath;
  }

  if (_.isExistedFile(mdFile)) {
    const data = fs.readFileSync(mdFile, {
      encoding: 'utf8',
      flag: 'r'
    });
    logger.info(`get ${filePath} from cache`);
    logger.info(`sha:${data.trim()}`);
    return filePath;
  } else {
    const result = crypto.createHash('md5').update(url).digest('hex');
    try {
      return downloadAndWriteSha1(url, result);
    } catch (e) {
      console.log(e);
    }
  }
}
468328
function handleSafeToDownload() {
        var downloadFn = function () {
            if (isFirstIterationDownload()) {
                // For the first iteration of download, show download
                //status info in Status bar, and pass download to node
                UpdateStatus.showUpdateStatus("initial-download");
                postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, true);
            } else {
                /* For the retry iterations of download, modify the
                download status info in Status bar, and pass download to node */
                var attempt = (MAX_DOWNLOAD_ATTEMPTS - downloadAttemptsRemaining);
                if (attempt > 1) {
                    var info = attempt.toString() + "/5";
                    var status = {
                        target: "retry-download",
                        spans: [{
                            id: "attempt",
                            val: info
                        }]
                    };
                    UpdateStatus.modifyUpdateStatus(status);
                } else {
                    UpdateStatus.showUpdateStatus("retry-download");
                }
                postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, false);
            }

            --downloadAttemptsRemaining;
        };

        if(!isAutoUpdateInitiated) {
            isAutoUpdateInitiated = true;
            updateJsonHandler.refresh()
                .done(function() {
                    setUpdateStateInJSON('downloadCompleted', false)
                        .done(downloadFn);
                });
        } else {
            setUpdateStateInJSON('downloadCompleted', false)
                .done(downloadFn);
        }
    }
827596
function processFile(req, resp, next, downloads) {
    if (!downloads) {
        logMessage('no download directory');
        next();

        return;
    }

    let form = new formidable.IncomingForm();
    form.uploadDir = downloads;

    form.parse(req, function ee(err, _fields, files) {
        if (err) {
            logMessage(err);
        }

        resp.writeHead(200, {'content-type': 'text/html'});

        let file = files.file.path;
        logMessage(file);

        setTimeout(function yz() {
            fs.unlink(file, function zy(err) {
                if (err) {
                    logMessage(err);
                }
                else {
                    logMessage(file + ' deleted');
                }
            });
        }, 60000);

        let fileName = files.file.name;
        req.session.file = file;
        resp.end('<html><body><script>parent.amorphic.prepareFileUpload(\'package\');' +
            'parent.amorphic.uploadFunction.call(null, "' +  fileName + '"' + ')</script></body></html>');
    });
}
113016
private function download()
    {
        $file = (string) gps('file');

        try {
            $backups = $this->getBackups();
        } catch (Exception $e) {
        }

        if (empty($backups) || !isset($backups[$file])) {
            $this->browser(array(gTxt('rah_backup_can_not_download'), E_ERROR));
            return;
        }

        extract($backups[$file]);

        @ini_set('zlib.output_compression', 'Off');
        @set_time_limit(0);
        @ignore_user_abort(true);

        ob_clean();
        header('Content-Description: File Download');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.$name.'"; size="'.$size.'"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: private');
        header('Content-Length: '.$size);
        ob_flush();
        flush();

        if ($f = fopen($path, 'rb')) {
            while(!feof($f) && connection_status() == 0) {
                echo fread($f, 1024*64);
                ob_flush();
                flush();
            }

            fclose($f);
        }

        exit;
    }
693990
function db(objectName) {
    if (_.isBoolean(save.hasLoaded)) deasync.loopWhile(() => !save.hasLoaded);
    if (!_.has(objects, objectName)) objects[objectName] = {};
    return createMethods(objects[objectName], save.bind(null, objectName));
  }
723095
private function download()
    {
        header('Content-disposition: attachment; filename="'.$this->filename.'.'.$this->extension.'"');
        header('Content-type: application/octet-stream');
        
        readfile($this->filename.'.'.$this->extension);
    }
384035
function downloadCode(db, codePath) {
  return mkdir(codePath)
    .then(() => db.code.loadModules())
    .then((modules) => Promise.all(modules.map(module => downloadCodeModule(db, module, codePath))));
}
1344939
public function download(
        string $source,
        string $disk = null,
        string $customId = null,
        string $mimeType = null
    ): ?array {
        // TODO maybe we should add exceptions instead of returning null values?
        if ($customId) {
            if ($resource = $this->getRepository()->find($customId)) {
                return $resource->toArray();
            }
        }

        $fileName = $this->getFileName($source);

        if (!strlen($fileName)) {
            return null;
        }

        $this->createFolder('uploads/tmp', 'local');

        $destination = storage_path('app/uploads/tmp/' . $fileName);

        file_put_contents($destination, file_get_contents($source));

        if (filesize($destination) <= config('resources.max_checksum_size')) {
            $resource = $this->getRepository()->findOneBy(['checksum' => hash_file('sha256', $destination)]);

            if (!$this->allowDuplicates && $resource) {
                //If duplicate found deleting downloaded file
                unlink($destination);

                return $resource->toArray();
            }
        }

        if (!file_exists($destination)) {
            return null;
        }

        if (!$mimeType) {
            $mimeType = mime_content_type($destination);
        }

        $file = new UploadedFile($destination, $fileName, $mimeType, filesize($destination), null, true);

        return $this->upload($file, null, $disk, $customId);
    }
336574
public function downloadAction()
    {
        $model = $this->getModel();
        $model->applyRequest($this->getRequest());

        $fileData = $model->loadFirst();

        header('Content-Type: application/x-download');
        header('Content-Length: '.$fileData['size']);
        header('Content-Disposition: inline; filename="'.$fileData['filename'].'"');
        header('Pragma: public');

        echo $fileData['content'];
        exit();
    }
1069518
function insertHTTPFile( $object, $objectVersion, $objectLanguage,
                             $objectAttribute, $httpFile, $mimeData,
                             &$result )
    {
        $result = array( 'errors' => array(),
                         'require_storage' => false );
        $attributeID = $objectAttribute->attribute( 'id' );

        $binary = eZBinaryFile::fetch( $attributeID, $objectVersion );
        if ( $binary === null )
            $binary = eZBinaryFile::create( $attributeID, $objectVersion );

        $httpFile->setMimeType( $mimeData['name'] );

        $suffix = false;
        if ( isset( $mimeData['suffix'] ) )
            $suffix = $mimeData['suffix'];

        $db = eZDB::instance();
        $db->begin();

        if ( !$httpFile->store( "original", $suffix, false ) )
        {
            $result['errors'][] = array( 'description' => ezpI18n::tr( 'kernel/classes/datatypes/ezbinaryfile',
                                                        'Failed to store file %filename. Please contact the site administrator.', null,
                                                        array( '%filename' => $httpFile->attribute( "original_filename" ) ) ) );
            return false;
        }


        $filePath = $binary->attribute( 'filename' );

        $binary->setAttribute( "contentobject_attribute_id", $attributeID );
        $binary->setAttribute( "version", $objectVersion );
        $binary->setAttribute( "filename", basename( $httpFile->attribute( "filename" ) ) );
        $binary->setAttribute( "original_filename", $httpFile->attribute( "original_filename" ) );
        $binary->setAttribute( "mime_type", $mimeData['name'] );

        $binary->store();

        $filePath = $httpFile->attribute( 'filename' );
        $fileHandler = eZClusterFileHandler::instance();
        $fileHandler->fileStore( $filePath, 'binaryfile', true, $mimeData['name'] );
        $objectAttribute->setContent( $binary );

        $db->commit();

        $objectAttribute->setContent( $binary );

        return true;
    }
42479
function fetchData(token) {
    sdk.feed.startpage(token).then(function(stream) {
        return stream.messages.map(function(message) {
            return message.attachments.filter(function(attachment) {
                return attachment.type === 'IMAGE';
            });
        });
    }).then(function(imageAttachmentArrays) {
        return imageAttachmentArrays.reduce(function(prev, cur) {
            return prev.concat(cur);
        }, []);
    }).then(function(imageAttachments) {
        imageAttachments.forEach(function(attachment) {
            var file_name = attachment.url.split('/').reverse()[0];
            request('https://' + sdk.config.domain + attachment.url)
                .pipe(fs.createWriteStream(file_name))
                .on('finish', function() {
                    console.log('saved attachment ' + file_name);
                });
        });
    }).catch(function(err) {
        console.log('Error:', err);
    });
}
227683
public static function download($name = null, $contentLength = 0)
    {
        if ($name) {
            $name = '; filename="' . strtr($name, '"', '-') . '"';
        } else {
            $name = '';
        }

        self::putHeader('Content-Transfer-Encoding', 'Binary');
        self::putHeader('Content-Disposition', 'attachment' . $name);

        if ($contentLength > 0) {
            self::putHeader('Content-Length', $contentLength);
        }
    }