Helper function to download the file

@throws \Th\FileDownloader\Exceptions\DownloadException          Throw an error if it is not possible to download the file
163267
protected function downloadFile() {
        // if the file exists already, return out, file already was downloaded
        if (file_exists($this->downloadFilePath())) {
            return;
        }
        
        // download the file
        $file = file_get_contents($this->url());

        // if it was not possible to get the file content, throw a new error
        if ($file === false) {
            throw new \Th\FileDownloader\Exceptions\DownloadException(99);
        }

        // try writing the file to disk
        $downloadResult = file_put_contents($this->downloadFilePath(), $file);

        // if it is not possible to download the file, return
        if ($downloadResult === false) {
            throw new \Th\FileDownloader\Exceptions\DownloadException(99);
        }
    }
1216196
public function generate() {
        if (!$this->filePath) {
            throw new Exception('Trying to save file without path');
        }
        
        $tempDir = codemonkey_pathTempDir;
        
        $content = $this->generateCode();
        
        $this->checkIfTempFolderExists();
        $this->checkIfFoldersExist();
        
        try {
            $fp = fopen($tempDir.$this->filePath, 'w');
            fputs($fp, $content);
            fclose($fp);
            chmod($tempDir.$this->filePath, 0775);
        } catch (Exception $e) {
            echo "Could not generate file ".$this->filePath."<br />\n"
                    . $e->getMessage()."<br />\n";
        }
    }
833072
protected function downloadListBackup()
    {
        $backup_id = $this->getQuery('download');

        if (empty($backup_id)) {
            return null;
        }

        $this->controlAccess('backup_download');

        $backup = $this->backup->get($backup_id);

        if (!empty($backup['path'])) {
            $this->download(gplcart_file_absolute($backup['path']));
        }
    }
813917
public function download()
    {
        $download_path = parse_url($this->links['download_location'], PHP_URL_PATH);
        $download_query = parse_url($this->links['download_location'], PHP_URL_QUERY);
        $link = self::get($download_path . "?" . $download_query);
        $linkClass = \GuzzleHttp\json_decode($link->getBody());
        return $linkClass->url;
    }
772715
public function download()
    {
        try {
            $result = $this->getSoapClient()->DownloadImage(array(
                'filename' => basename($this->filename) ,
            ));

            return base64_decode($result->DownloadImageResult);
        } catch ( SoapException $e ) {
            throw new DownloadException('Error while downloading the image' , $e);
        }
    }
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;
    }
404034
public function download(){

        if (!$this->hasRequestParameter('uri')) {
            throw new common_exception_MissingParameter('uri', __METHOD__);
        }
        if (!$this->hasRequestParameter('stylesheetUri')) {
            throw new common_exception_MissingParameter('stylesheetUri', __METHOD__);
        }
        if (!$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter('lang', __METHOD__);
        }


        $item = new \core_kernel_classes_Resource($this->getRequestParameter('uri'));
        $lang = $this->getRequestParameter('lang');
        $styleSheet = $this->getRequestParameter('stylesheetUri');

        if (!\tao_helpers_File::securityCheck($styleSheet, true)) {
            throw new \common_exception_Error('invalid stylesheet path "'.$styleSheet.'"');
        }

        header('Set-Cookie: fileDownload=true');
        setcookie('fileDownload','true', 0, '/');
        header('Content-type: application/octet-stream');
        header(sprintf('Content-Disposition: attachment; filename=%s', basename($styleSheet)));
        echo CssHelper::downloadCssFile($item, $lang, $styleSheet);
    }
208620
public function load()
    {
        if (self::$json === null) {
            self::$json = array();
            if (!empty($this->extSettings['json'])) {
                $file = MaskUtility::getFileAbsFileName($this->extSettings['json']);
                if (file_exists($file)) {
                    self::$json = json_decode(file_get_contents($file), true);
                }
            }
        }
        return self::$json;
    }
61023
public function getFileContent()
    {
        $file = $this->getAttribute('file');
        if (empty($file) && !$this->getIsNewRecord()) {
            $file = $this->refreshFile();
        }

        if (empty($file)) {
            return null;
        } elseif ($file instanceof Download) {
            $fileSize = $file->getSize();
            return empty($fileSize) ? null : $file->toString();
        } elseif ($file instanceof UploadedFile) {
            return file_get_contents($file->tempName);
        } elseif (is_string($file)) {
            if (file_exists($file)) {
                return file_get_contents($file);
            }
            throw new InvalidParamException("File '{$file}' does not exist.");
        }

        throw new InvalidParamException('Unsupported type of "file" attribute.');
    }
247949
public function download($filename = '')
    {
        $filename = $this->formatFilename($filename);
        if ($this->content) {
            $this->printHeader();
            header("Content-Disposition: attachment; filename=\"" . $filename . "\";" );
            ob_clean();
            echo $this->content;
        } elseif ($this->path) {
            $fsize = filesize($this->path);
            $this->printHeader($fsize);
            header("Content-Disposition: attachment; filename=\"" . $filename . "\";" );
            ob_clean();
            readfile($this->path);
        }
    }
84823
public function start(): self
    {
        if (!$this->url) {
            throw new \RuntimeException("Please the property 'url' and 'saveAs'.", -1);
        }

        // default save to current dir.
        if (!$save = $this->saveAs) {
            $save = \getcwd() . '/' . \basename($this->url);
            // reset
            $this->saveAs = $save;
        }

        $ctx = \stream_context_create();

        // register stream notification callback
        \stream_context_set_params($ctx, [
            'notification' => [$this, 'progressShow']
        ]);

        Cli::write("Download: {$this->url}\nSave As: {$save}\n");

        $fp = \fopen($this->url, 'rb', false, $ctx);

        if (\is_resource($fp) && \file_put_contents($save, $fp)) {
            Cli::write("\nDone!");
        } else {
            $err = \error_get_last();
            Cli::stderr("\nErr.rrr..orr...\n {$err['message']}\n", true, -1);
        }

        // close resource
        if (\is_resource($fp)) {
            \fclose($fp);
        }

        $this->fileSize = null;
        return $this;
    }
1156886
public function download() {
        $filename = 'logs_' . userdate(time(), get_string('backupnameformat', 'langconfig'), 99, false);
        if ($this->course->id !== SITEID) {
            $courseshortname = format_string($this->course->shortname, true,
                    array('context' => context_course::instance($this->course->id)));
            $filename = clean_filename('logs_' . $courseshortname . '_' . userdate(time(),
                    get_string('backupnameformat', 'langconfig'), 99, false));
        }
        $this->tablelog->is_downloading($this->logformat, $filename);
        $this->tablelog->out($this->perpage, false);
    }
604193
public function download($url, callable $onComplete = null)
    {
        //first check if the function is called external
        if($this->isExternal())
        {
            $data = file_get_contents($url);
            //hold the process to simulate more to do ;-)
            sleep(3);
            echo "Downloaded: ".strlen($data).' bytes from url: '.$url.PHP_EOL;
            //return the data
            //parent thread can handle this if needed
            return $data;
        }
        else
        {
            //we are in the parent context
            //just redirect to the thread
            //we use async as we dont want to wait for the result
            //return the handle allow the caller to check result
            return $this->asyncCallOnChild(__FUNCTION__, array($url), $onComplete);
        }
    }
780256
public function downloadFile($uri)
    {
        $fileUtil = new FileUtil();
        $file = tempnam($fileUtil->getTempDirectory(), "bavdownload");
        $fp   = fopen($file, 'w');
        if (! ($file && $fp)) {
            throw new DownloaderException("Failed opening a temporary file");

        }
        curl_setopt($this->handle, CURLOPT_FILE, $fp);

        if (! $this->download($uri)) {
            fclose($fp);
            unlink($file);
            throw new DownloaderException(curl_error($this->handle), curl_errno($this->handle));

        }
        return $file;
    }
269478
protected function downloadToTmpFile()
    {
        $conn = $this->getFtpConnection();
        $file = $this->getFilename();
        $tmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . basename($file);

        $fileSize = $this->getSize();

        $mode = $this->getMode() ? constant('FTP_' . strtoupper($this->getMode())) : FTP_ASCII;

        $ret = ftp_nb_get($conn, $tmpFile, $file, $mode);
        $currentBytes = 0;
        while ($ret === FTP_MOREDATA) {
            $ret = ftp_nb_continue($conn);
            clearstatcache();
            $bytes = filesize($tmpFile);
            $diff = $bytes - $currentBytes;
            $currentBytes = $bytes;

            $this->eventDispatcher->dispatch(
                FeedEvents::FETCH_PROGRESS,
                new FetchProgressEvent($currentBytes, $diff, $fileSize)
            );
        }

        if ($ret !== FTP_FINISHED) {
            throw new TransportException(sprintf('Error downloading feed to %s', $tmpFile));
        }

        return $tmpFile;
    }
1173893
private function open()
  {
    // Used for trapping `fopen()` errors.
    $this->trappedErrorNumber = null;
    $this->trappedErrorString = null;

    $old = set_error_handler(array($this, 'trapError'));

    $needsChmod = !file_exists($this->file);
    $fh = fopen($this->file, 'a');

    restore_error_handler();

    // Handles trapped `fopen()` errors.
    if ($this->trappedErrorNumber) {
      throw new Exception(
          sprintf(
              "Logger Error: '%s'",
              $this->trappedErrorString
          ),
          $this->trappedErrorNumber
      );
    }

    if ($needsChmod) {
      @chmod($this->file, $this->mode & ~umask());
    }

    return $this->file = $fh;
  }
423897
protected function downloadFile()
    {
        $file_id = $this->getQuery('download');

        if (!empty($file_id)) {
            $file = $this->file->get($file_id);
            $this->download(gplcart_file_absolute($file['path']));
        }
    }