Move temporary files into a valid folder

@param string $content
@param string $destFolder
@param array $tmpFiles
@return string Updated html content with new urls
179946
public static function moveTemporaryUploads($content, $destFolder, &$tmpFiles)
    {
        $replace = [];

        $folder = Folder::find_or_make($destFolder);

        /* @var $file File */
        foreach ($tmpFiles as $file) {

            // Keep a copy of the old url to remplace with a new one in the html content
            $oldURL = $file->getURL();

            $name = pathinfo($file->Name, PATHINFO_FILENAME);
            $ext = pathinfo($file->Name, PATHINFO_EXTENSION);

            $file->Name = $name . '_' . time() . '.' . $ext;
            $file->ParentID = $folder->ID;
            $file->write();

            $replace[$oldURL] = $file->getURL();
        }

        $content = str_replace(array_keys($replace), array_values($replace), $content);

        return $content;
    }
466069
public function makeTempFile( $prefix = '', $content = '' ) {
		$fileName = $prefix . $this->getRandomHexString();
		$filePath = $this->path . DIRECTORY_SEPARATOR . $fileName;
		$ok = file_put_contents( $filePath, $content );
		if ( $ok === false ) {
			throw new GpgLibException( "Could not create temporary file at $filePath" );
		}
		return $filePath;
	}
779226
public function setTmpFile($tmp_file)
  {
    //Check if writable
    $fp = @fopen($tmp_file, "w");
    
    if (!$fp)
    {
      return false;
    }
    else
    {
      fclose($fp);
      $this->tmpFile = $tmp_file;
      return true;
    }
  }
375893
public function load($tmpFile, $folderPath = false) {
				
		if(!$folderPath) $folderPath = Config::inst()->get('Upload', 'uploads_folder');
		
		// @TODO This puts a HUGE limitation on files especially when lots
		// have been uploaded.
		$base = Director::baseFolder();
		$parentFolder = Folder::find_or_make($folderPath);

		// Generate default filename
        $fileArray = explode('/', $tmpFile);
        $fileName = $fileArray[(count($fileArray)-1)];
		$nameFilter = FileNameFilter::create();
		$file = $nameFilter->filter($fileName);
		$fileName = basename($file);

		$relativeFilePath = ASSETS_DIR . "/" . $folderPath . "/$fileName";
		
		// if filename already exists, version the filename (e.g. test.gif to test1.gif)
		while(file_exists("$base/$relativeFilePath")) {
			$i = isset($i) ? ($i+1) : 2;
			$oldFilePath = $relativeFilePath;
			// make sure archives retain valid extensions
			if(substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.gz')) == '.tar.gz' ||
				substr($relativeFilePath, strlen($relativeFilePath) - strlen('.tar.bz2')) == '.tar.bz2') {
					$relativeFilePath = preg_replace('/[0-9]*(\.tar\.[^.]+$)/', $i . '\\1', $relativeFilePath);
			} else if (strpos($relativeFilePath, '.') !== false) {
				$relativeFilePath = preg_replace('/[0-9]*(\.[^.]+$)/', $i . '\\1', $relativeFilePath);
			} else if (strpos($relativeFilePath, '_') !== false) {
				$relativeFilePath = preg_replace('/_([^_]+$)/', '_'.$i, $relativeFilePath);
			} else {
				$relativeFilePath .= '_'.$i;
			}
			if($oldFilePath == $relativeFilePath && $i > 2) {
				user_error("Couldn't fix $relativeFilePath with $i tries", E_USER_ERROR);
			}
		}
		
		if(file_exists($tmpFile) && copy($tmpFile, $base."/".$relativeFilePath)) {
			$this->owner->ParentID = $parentFolder->ID;
			// This is to prevent it from trying to rename the file
			$this->owner->Name = basename($relativeFilePath);
			$this->owner->write();
			return true;
		} else {
			return false;
		}
	}
942466
public static function detect_format($tempdir) {
        $filepath = make_backup_temp_directory($tempdir, false);
        if (!is_dir($filepath)) {
            throw new convert_helper_exception('tmp_backup_directory_not_found', $filepath);
        }
        $manifest = cc2moodle::get_manifest($filepath);
        if (!empty($manifest)) {
            // Looks promising, lets load some information.
            $handle = fopen($manifest, 'r');
            $xml_snippet = fread($handle, 1024);
            fclose($handle);

            // Check if it has the required strings.

            $xml_snippet = strtolower($xml_snippet);
            $xml_snippet = preg_replace('/\s*/m', '', $xml_snippet);
            $xml_snippet = str_replace("'", '', $xml_snippet);
            $xml_snippet = str_replace('"', '', $xml_snippet);

            $search_string = "xmlns=http://www.imsglobal.org/xsd/imscc/imscp_v1p1";
            if (strpos($xml_snippet, $search_string) !== false) {
                return backup::FORMAT_IMSCC1;
            }
        }

        return null;
    }
896182
private function createTmpFile($content)
    {
        $tmp_dir = sys_get_temp_dir().'/__tintin';

        if (!is_dir($tmp_dir)) {
            mkdir($tmp_dir, 0777);
        }

        $file = $tmp_dir.'/'.md5(microtime(true)).'.php';

        file_put_contents($file, $content);

        return $file;
    }
88234
public function setTmpPath($tmpPath = '')
    {
        if (empty($tmpPath)) {
            $tmpPath = __DIR__ . '/../storage/tmp/';
        }
        $this->tmpPath = $tmpPath;

        return $this;
    }
1076533
public function createTmpDir(Filesystem $fm)
    {
        $tmp_dir = $this->getFileManager()->getUploadPath() . FileManager::DS . "." . strtotime("now");
        $fm->mkdir($tmp_dir);

        return $tmp_dir;
    }
505189
public static function detect_moodle2_format($tempdir) {
        $dirpath = make_backup_temp_directory($tempdir, false);
        if (!is_dir($dirpath)) {
            throw new convert_helper_exception('tmp_backup_directory_not_found', $dirpath);
        }

        $filepath = $dirpath . '/moodle_backup.xml';
        if (!file_exists($filepath)) {
            return false;
        }

        $handle     = fopen($filepath, 'r');
        $firstchars = fread($handle, 200);
        $status     = fclose($handle);

        if (strpos($firstchars,'<?xml version="1.0" encoding="UTF-8"?>') !== false and
            strpos($firstchars,'<moodle_backup>') !== false and
            strpos($firstchars,'<information>') !== false) {
                return true;
        }

        return false;
    }
1183243
protected function toMarkdown($content)
    {
        $tmpfname = tempnam(sys_get_temp_dir(), 'fillet'); // good
        file_put_contents($tmpfname, $content);
        $cmd = $this->config['pandoc']['bin'] . ' --no-wrap -f html -t markdown ' . $tmpfname;
        $content = shell_exec($cmd);
        unlink($tmpfname);
        return $content;
    }
756876
protected function copyFile($srcFilePath, $destFilePath)
    {
        $fileBody = file_get_contents($srcFilePath); // original

        if (empty($this->uploadsDirectCopy)) {
            // preparate image to remove injected code, etc
            $imagine = Image::getImagine();
            try {
                $image = $imagine->open($srcFilePath);
                $fileBody = $image->get($this->_format, []); // preprocessed image
            } catch (Exception $ex) {
              //$this->errmsg = Yii::t($this->tc, "Uploaded file '{file}' not an image", ['file' => $srcFilePath]);
                $this->errmsg = $ex->getMessage();
                Yii::error($this->errmsg);
                //return false;

                // show instead of return error
                //$fileBody = @file_get_contents($this->badImage);
                $image = $imagine->open($this->badImage);
                $fileBody = $image->get($this->_format, []);
            }
        }

        $destDir = dirname($destFilePath);
        if (!is_dir($destDir) && !@FileHelper::createDirectory($destDir)) {
         //$this->errmsg = Yii::t($this->tc, "Can't create destination folder '{dir}'", ['dir' => $destDir]);
           $this->errmsg = "Can't create destination folder '$destDir'";
           Yii::error($this->errmsg);
           return false;
        }

        $result = @file_put_contents($destFilePath, $fileBody, LOCK_EX);
        if ($result === false) {
         //$this->errmsg = Yii::t($this->tc, "Fail in file_put_contents('{from}', '...')", ['from' => $destFilePath]);
           $this->errmsg = "Fail in file_put_contents('$destFilePath', '...')";
           Yii::error($this->errmsg);
        }
        return $result;
    }
854339
public function decompress($content)
    {
        $archive = $this->getArchive();
        if (empty($archive) || !file_exists($archive)) {
            throw new Exception\RuntimeException('Tar Archive not found');
        }

        $archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));
        $archive = new Archive_Tar($archive, $this->getMode());
        $target  = $this->getTarget();
        if (!is_dir($target)) {
            $target = dirname($target) . DIRECTORY_SEPARATOR;
        }

        $result = $archive->extract($target);
        if ($result === false) {
            throw new Exception\RuntimeException('Error while extracting the Tar archive');
        }

        return $target;
    }
73804
protected function copyTemplateDirectoryAndGetPath(
        string $templatePath,
        string $destPath
    ): string {
        return $this->pathHelper->copyTemplateDirectoryAndGetPath(
            $this->pathToProjectRoot,
            $templatePath,
            $destPath
        );
    }
687006
public function dumpFile($filename, $content)
    {
        $dir = dirname($filename);

        if (!is_dir($dir)) {
            $this->mkdir($dir);
        }

        if (!is_writable($dir)) {
            throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir);
        }

        // Will create a temp file with 0600 access rights
        // when the filesystem supports chmod.
        $tmpFile = $this->tempnam($dir, basename($filename));

        if (false === @file_put_contents($tmpFile, $content)) {
            throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename);
        }

        @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask());

        $this->rename($tmpFile, $filename, true);
    }
398486
private function cleanTmp()
    {
        $directories = File::directories(tmpPath());
        foreach($directories as $directory){
            File::deleteDirectory($directory);
        }

        return $this;
    }
901117
private function createTempFile($name, $content)
    {
        $tempDir  = \sys_get_temp_dir();
        $fileName = \md5($name);
        $filePath = $tempDir . DIRECTORY_SEPARATOR . 'phpcq-author-validation' . DIRECTORY_SEPARATOR . $fileName;

        if (\file_exists($filePath)) {
            return $filePath;
        }

        if (!\file_exists(\dirname($filePath)) && !\mkdir($concurrentDirectory = \dirname($filePath))
            && !is_dir(
                $concurrentDirectory
            )) {
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
        }

        $file = \fopen($filePath, 'wb');

        \fwrite($file, $content);

        return $filePath;
    }
1231456
private function prepareTmpDir()
    {
        $tempDir = $this->file->get(self::SETTING_DESTINATION_DIR) . DIRECTORY_SEPARATOR . uniqid('install-');

        // If the temporary folder could not be created, error out.
        // @codingStandardsIgnoreStart - we silence on purpose here as we create an exception on error.
        if (!@mkdir($tempDir, 0700)) {
        // @codingStandardsIgnoreEnd
            throw new \RuntimeException('Could not create the temporary directory');
        }

        $this->tempDir = $tempDir;
    }