Rename a file

@param LibraryType   $library     Library object
@param DirectoryItem $dirItem     Directory item to rename
@param string        $newFilename New file name

@return bool
@throws \GuzzleHttp\Exception\GuzzleException
188829
public function rename(LibraryType $library, DirectoryItem $dirItem, string $newFilename): bool
    {
        $filePath = $dirItem->dir . $dirItem->name;

        if (empty($filePath)) {
            throw new \InvalidArgumentException('Invalid file path: must not be empty');
        }

        if (empty($newFilename) || strpos($newFilename, '/') === 0) {
            throw new \InvalidArgumentException('Invalid new file name: length must be >0 and must not start with /');
        }

        $uri = sprintf(
            '%s/repos/%s/file/?p=%s',
            $this->clipUri($this->client->getConfig('base_uri')),
            $library->id,
            $this->urlEncodePath($filePath)
        );

        $response = $this->client->request(
            'POST',
            $uri,
            [
                'headers'   => ['Accept' => 'application/json'],
                'multipart' => [
                    [
                        'name'     => 'operation',
                        'contents' => 'rename',
                    ],
                    [
                        'name'     => 'newname',
                        'contents' => $newFilename,
                    ],
                ],
            ]
        );

        $success = $response->getStatusCode() === 200;

        if ($success) {
            $dirItem->name = $newFilename;
        }

        return $success;
    }
789080
public static function rename(String $oldName, String $newName) : Bool
    {
        $oldName = Info::rpath($oldName);

        if( ! file_exists($oldName) )
        {
            throw new Exception\FileNotFoundException(NULL, $oldName);
        }

        return rename($oldName, $newName);
    }
720007
public function iStartCreatingNew(string $newItemType, ?string $containerItem = null): void
    {
        if (!array_key_exists($newItemType, $this->itemCreateMapping)) {
            throw new \InvalidArgumentException(sprintf('Unrecognized item type name: %s', $newItemType));
        }
        PageObjectFactory::createPage($this->utilityContext, $this->itemCreateMapping[$newItemType], $containerItem)
            ->startCreatingItem();
    }
131565
public function rename($dn, $newRdn, $newParent, $deleteOldRdn = false)
    {
        if ($this->suppressErrors) {
            return @ldap_rename($this->getConnection(), $dn, $newRdn, $newParent, $deleteOldRdn);
        }

        return ldap_rename($this->getConnection(), $dn, $newRdn, $newParent, $deleteOldRdn);
    }
939331
function renameFile (oldFile, newFile) {
    if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; }

    let item = fileRegistry[oldFile];

    item.file = newFile;

    fileRegistry[newFile] = item;

    delete fileRegistry[oldFile];
}
1365687
public function renameFile($name, $newName)
    {
        foreach ($this->getAllFields() as $field) {
            $path = $this->getFilePath($field, $name);
            $newPath = $this->getFilePath($field, $newName);
            if (file_exists($newPath)) {
                throw new \Exception("File {$newName} already exists");
            }
            rename($path, $newPath);
        }
        if ($name == $this->owner->getAttribute($this->fileField)
            && ($files = $this->getFileList())
        ) {
            $this->owner->updateAttributes([$this->fileField => $newName]);
        }
        return true;
    }
391547
public function renameFile($fileIndex, $newFileName)
    {
        foreach ($this->lines as $line) {
            $line->renameFile($fileIndex, $newFileName);
        }
    }
501767
public function getFileDetail(LibraryType $library, string $remoteFilePath): DirectoryItem
    {
        $url = $this->client->getConfig('base_uri')
            . '/repos/'
            . $library->id
            . '/file/detail/'
            . '?p=' . $this->urlEncodePath($remoteFilePath);

        $response = $this->client->request('GET', $url);

        $json = json_decode((string)$response->getBody());

        return (new DirectoryItem)->fromJson($json);
    }
366209
public static function rename_dir($path, $new_path, $source_area = null, $target_area = null)
	{
		return static::rename($path, $new_path, $source_area, $target_area);
	}
655864
public function renameFolderInFileSystem(Folder $folder, Folder $newFolder)
	{
		// rename folder in both file storages
		$externalPath = $this->getExternalPath();
		$internalPath = $this->getInternalPath();

		foreach (array($externalPath, $internalPath) as $basePath) {

			$oldFullPath = $basePath . $folder->getPath(DIRECTORY_SEPARATOR, true);
			$newFullPath = $basePath . $newFolder->getPath(DIRECTORY_SEPARATOR, true);

			// Should not happen
			if ($oldFullPath === $newFullPath) {
				continue;
			}

			if (is_dir($oldFullPath)) {

				$result = rename($oldFullPath, $newFullPath);

				if ( ! $result) {
					throw new Exception\RuntimeException("Failed to rename folder from '$oldFullPath' to '$newFullPath'");
				}
			} else {
				$this->container->getLogger()->warn("Folder '$oldFullPath' missing in filesystem on rename");
				$this->createFolderInFileSystem($basePath, $newFolder);
			}
		}
	}
719761
public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
        global $USER;
        $fs = get_file_storage();
        $user_context = context_user::instance($USER->id);
        if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
            if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
                // Remember original file source field.
                $source = @unserialize($file->get_source());
                // Remember the original sortorder.
                $sortorder = $file->get_sortorder();
                if ($tempfile->is_external_file()) {
                    // New file is a reference. Check that existing file does not have any other files referencing to it
                    if (isset($source->original) && $fs->search_references_count($source->original)) {
                        return (object)array('error' => get_string('errordoublereference', 'repository'));
                    }
                }
                // delete existing file to release filename
                $file->delete();
                // create new file
                $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
                // Preserve original file location (stored in source field) for handling references
                if (isset($source->original)) {
                    if (!($newfilesource = @unserialize($newfile->get_source()))) {
                        $newfilesource = new stdClass();
                    }
                    $newfilesource->original = $source->original;
                    $newfile->set_source(serialize($newfilesource));
                }
                $newfile->set_sortorder($sortorder);
                // remove temp file
                $tempfile->delete();
                return true;
            }
        }
        return false;
    }
328094
public function rename($nameold,$namenew,$path){
        if($this->validNameFile($nameold,false) && $this->validNameFile($namenew,false)){
            $fullpath = $this->getFullPath().$path;
            $nameold = $this->clearNameFile($nameold);
            $namenew = $this->clearNameFile($namenew);

            $file = new Filesystem;
            if($file->exists($fullpath.$nameold)){
                if( $this->config['debug'] ) $this->_log('$fullpath.$nameold - '.$fullpath.$nameold);
                if(is_dir($fullpath.$nameold)){
                    $namenew = $this->sanitizeNameFolder($namenew);
                    if($file->exists($fullpath.$namenew)==false){
                        $file->rename($fullpath.$nameold,$fullpath.$namenew);
                        $result = array("query"=>"BE_RENAME_MODIFIED","params"=>array());
                        $this->setInfo(array("msg"=>$result,"data"=>array("namefile" => $namenew )));

                    }else{
                        $result = array("query"=>"BE_RENAME_EXISTED","params"=>array());
                        $this->setInfo(array("msg"=>$result,"status"=>0));
                    }
                }elseif(is_file($fullpath.$nameold)){
                    if($this->validExt($nameold)){
                        $extold = $this->getExtension($nameold);
                        $namenew = $namenew.'.'.$extold;
                        if($file->exists($fullpath.$namenew)==false){
                            $file2 = new \SplFileInfo($fullpath.$nameold);
                            if(in_array($file2->getExtension(), $this->config['images']['images_ext'])){
                                $filename = $file2->getFilename();
                                foreach ($this->config['images']['resize'] as $key => $value) {
                                    $image_info = $this->imageSizeName($path,$filename,$value);
                                    $filename_old = $image_info['name'];
                                    $fullpaththumb_name = $this->getFullPath().'/'.$this->config['folder_thumb'].$path.$filename_old;
                                    $file->remove($fullpaththumb_name);
                                }
                            }
                            $file->rename($fullpath.$nameold,$fullpath.$namenew);
                            $file3 = new \SplFileInfo($fullpath.$namenew);
                            $this->createThumb($file3,$path);
                            $result = array("query"=>"BE_RENAME_MODIFIED","params"=>array());
                            $this->setInfo(array("msg"=>$result,"data"=>array("namefile" => $namenew )));
                        }else{
                            $result = array("query"=>"BE_RENAME_EXISTED","params"=>array());
                            $this->setInfo(array("msg"=>$result,"status"=>0));
                        }
                    }else{
                        $result = array("query"=>"BE_RENAME_FILENAME_NOT_VALID","params"=>array());
                        $this->setInfo(array("msg"=>$result, "status"=>0));
                    }
                }
            }else{
                $result = array("query"=>"BE_RENAME_NOT_EXISTS","params"=>array());
                $this->setInfo(array("msg"=>$result, "status"=>0));
            }
        }else{
           $result = array("query"=>"BE_RENAME_FILENAME_NOT_VALID","params"=>array());
           $this->setInfo(array("msg"=>$result, "status"=>0));
       }
   }
912902
protected function renameFile($path, $newName)
    {
        $newPath = pathinfo($path, PATHINFO_DIRNAME) . '/' . $newName;

        try {
            $success = rename($path, $newPath);

            // @codeCoverageIgnoreStart
        } catch (\Exception $e) {
            throw new CouldNotRetrieveRemoteFileException("Failed to rename '{$path}' to '{$newName}'", $e->getCode(), $e);
            // @codeCoverageIgnoreEnd
        }

        // @codeCoverageIgnoreStart
        if ( ! $success) {
            throw new CouldNotRetrieveRemoteFileException("Failed to rename '{$path}' to '{$newName}'");
        }
        // @codeCoverageIgnoreEnd

        return $newPath;
    }
1212862
public function rename($oldName, $newName)
    {
        if (null !== $this->collection->get($newName)) {
            throw new RuntimeException(
                sprintf(
                    'Could not rename toggle %1$s to %2$s, a toggle with name %2$s already exists',
                    $oldName,
                    $newName
                )
            );
        }

        $currentToggle = $this->collection->get($oldName);

        if (null === $currentToggle) {
            throw new RuntimeException(
                sprintf(
                    'Could not rename toggle %1$s to %2$s, toggle with name %1$s does not exists',
                    $oldName,
                    $newName
                )
            );
        }

        $currentToggle->rename($newName);

        if (false === $this->add($currentToggle)) {
            throw new RuntimeException(
                sprintf(
                    'Failed to rename toggle %1$s to %2$s, an error occurred when saving toggle with new name',
                    $oldName,
                    $newName
                )
            );
        }

        return $this->remove($oldName);
    }
604289
public function rename($oldName, $newName)
    {
        if (! ftp_rename($this->session, $oldName, $newName)) {
            throw new \RuntimeException('Name can not be changed');
        }
        return true;
    }
94034
public function renameFile($fileIndex, $newFileName)
    {
        $fileIndex = (int)$fileIndex;
        foreach ($this->positions as $position) {
            $source = $position->source;
            if ($source->fileIndex === $fileIndex) {
                $source->fileName = $newFileName;
            }
        }
    }
61462
public function unstar(LibraryType $library, DirectoryItem $dirItem): bool
    {
        $uri = sprintf(
            '%s/?repo_id=%s&p=%s',
            $this->resourceUri,
            $library->id,
            $dirItem->path
        );

        $response = $this->client->request('DELETE', $uri);

        return $response->getStatusCode() === 200;
    }