Delete old avatar image from disk if it has been changed

@param User $user
@param PreUpdateEventArgs $event
185946
public function preUpdate(User $user, PreUpdateEventArgs $event)
    {
        if ($event->hasChangedField('avatarImage')) {
            $oldAvatarImage = $event->getOldValue('avatarImage');
            if (!empty($oldAvatarImage)) {
                $this->userService->deleteAvatar($oldAvatarImage);
            }
        }
    }
1296049
public static function user_deleted(\core\event\user_deleted $event) {
        $userid = $event->objectid;
        subscription_manager::delete_user_subscriptions($userid);
    }
701028
public function removeUser(User $user)
    {
        if ($this->users->contains($user)) {
            $this->users->removeElement($user);
        }

        return $this;
    }
382642
private function cleanSettings(User $user)
    {
        foreach ($user->getNotificationSettings() as $userNotificationSetting) {
            $this->objectManager->remove($userNotificationSetting);
        }

        $user->getNotificationSettings()->clear();

        foreach ($user->getSettings() as $userSetting) {
            $this->objectManager->remove($userSetting);
        }

        $user->getSettings()->clear();
    }
249054
private function cleanUserSessions(User $user)
    {
        $sessions = $this->objectManager->getRepository('Phraseanet:Session')
            ->findByUser(['user' => $user]);

        foreach ($sessions as $session) {
            $this->objectManager->remove($session);
        }
    }
680412
public function logout(Event $event, array $user)
    {
        $controller = $this->_registry->getController();
        if (empty($controller->Cookie)) {
            $controller->loadComponent('Cookie');
        }
        $controller->Cookie->delete('User.Cookie');
    }
508318
public function updateInfo(array $data, $user)
    {
        $this->getEventManager()->trigger(__FUNCTION__.'.pre', $this, array('user' => $user, 'data' => $data));

        $form  = $this->getServiceManager()->get('playgrounduser_change_info_form');
        $form->get('dob')->setOptions(array('format' => 'Y-m-d'));
        $form->bind($user);

        $data['id'] = $user->getId();
        $avatarPath = $this->getOptions()->getAvatarPath() . DIRECTORY_SEPARATOR;
        if (!is_dir($avatarPath)) {
            mkdir($avatarPath, 0777, true);
        }
        $avatarUrl = $this->getOptions()->getAvatarUrl() . '/';

        // If avatar is set, I prepend the url path to the image
        $fileName = null;
        if (isset($data['avatar'])) {
            $fileName = $data['avatar'];
            $data['avatar'] = $avatarUrl . $fileName;
        }

        if (!isset($data['username']) || $data['username'] == '') {
            if(isset($data['firstname']) && isset($data['lastname'])) {
                $data['username'] = ucfirst($data['firstname']) . " " . substr(ucfirst($data['lastname']), 0, 1);
            }
        }

        // Convert birth date format
        if (isset($data['dob']) && $data['dob']) {
            $tmpDate = \DateTime::createFromFormat('d/m/Y', $data['dob']);
            $data['dob'] = $tmpDate->format('Y-m-d');
        }

        $form->setData($data);

        $filter = $user->getInputFilter();
        $filter->remove('password');
        $filter->remove('passwordVerify');
        $form->setInputFilter($filter);

        if (!$form->isValid()) {
            if (isset($data['dob']) && $data['dob']) {
                $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['dob']);
                $data['dob'] = $tmpDate->format('d/m/Y');
                $form->setData(array('dob' => $data['dob']));
            }

            return false;
        }

        if ($fileName) {
            $adapter = new \Zend\File\Transfer\Adapter\Http();
            $size = new Size(array('max'=>'500kb'));
            $adapter->setValidators(array($size), $fileName);

            if (!$adapter->isValid()) {
                $dataError = $adapter->getMessages();
                if (isset($dataError['fileSizeTooBig'])) {
                    $dataError['fileSizeTooBig'] = 'Votre fichier dépasse le poids autorisé';
                }
                $error = array();
                foreach ($dataError as $key => $row) {
                    $error[] = $row;
                }
                if (isset($data['dob']) && $data['dob']) {
                    $tmpDate = \DateTime::createFromFormat('Y-m-d', $data['dob']);
                    $data['dob'] = $tmpDate->format('d/m/Y');
                    $form->setData(array('dob' => $data['dob']));
                }
                $form->setMessages(array('avatar'=>$error ));
            } else {
                $adapter->setDestination($avatarPath);
                if ($adapter->receive()) {
                    $user->setAvatar($avatarUrl . $adapter->getFileName(null, false));
                    $user = $this->getUserMapper()->update($user);
                    $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'data' => $data));

                    return $user;
                }
            }
        } else {
            $user = $this->getUserMapper()->update($user);
            $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'data' => $data));

            return $user;
        }

        return false;
    }
76027
public function RemovePicture($UserReference = '', $Username = '', $TransientKey = '') {
      $this->Permission('Garden.SignIn.Allow');
      $Session = Gdn::Session();
      if (!$Session->IsValid())
         $this->Form->AddError('You must be authenticated in order to use this form.');
      
      // Get user data & another permission check
      $this->GetUserInfo($UserReference, $Username, '', TRUE);
      $RedirectUrl = UserUrl($this->User, '', 'picture');
      if ($Session->ValidateTransientKey($TransientKey)
         && is_object($this->User)
         && (
            $this->User->UserID == $Session->UserID
            || $Session->CheckPermission('Garden.Users.Edit')
         )
      ) {
         // Do removal, set message, redirect
         Gdn::UserModel()->RemovePicture($this->User->UserID);
         $this->InformMessage(T('Your picture has been removed.'));
      }
      if ($this->_DeliveryType == DELIVERY_TYPE_ALL) {
          Redirect($RedirectUrl);
      } else {
         $this->ControllerName = 'Home';
         $this->View = 'FileNotFound';
         $this->RedirectUrl = Url($RedirectUrl);
         $this->Render();
      }
   }
783915
public function onStorageEventPreDelete(StorageEvent $event)
    {
        /** @var Entity\Users $userEntity */
        $userEntity = $event->getContent();
        if (!$userEntity instanceof Entity\Users) {
            return;
        }

        $this->deleteAuthtokens($userEntity);
        $this->deleteSessions($userEntity);
    }
1304246
public function delete(UserStructure $user)
    {
        $event = new Event\Delete();
        $event->setUser($user);
        $this->getEventManager()->trigger($event);
        return $event->getResult();  
    }
746410
public function remove(User $user)
    {
        $this->entityManager->remove($user);
        $this->entityManager->flush($user);
    }
1074293
public function beforeUpdate()
    {
        // prevent save empty image name value and also for correct remove old image
        $this->owner->setAttribute($this->imageAttribute, $this->owner->getOldAttribute($this->imageAttribute));
    }
1181406
public function updateAction(User $user)
    {
        $this->userService->updateUser($user);
        $this->addFlashMessage('Your user has been updated.', 'User updated', Message::SEVERITY_OK);
        $this->redirect('edit');
    }
1143911
public function onKernelView(GetResponseForControllerResultEvent $event): void
    {
        $request = $event->getRequest();
        if (!RequestAttributesExtractor::extractAttributes($request)) {
            return;
        }

        $user = $event->getControllerResult();
        if (!$user instanceof UserInterface || $request->isMethodSafe(false)) {
            return;
        }

        if ('DELETE' === $request->getMethod()) {
            $this->userManager->deleteUser($user);
            $event->setControllerResult(null);
        } else {
            $this->userManager->updateUser($user);
        }
    }
1051186
public function onBeforeDeleteUser(UserEvent $event)
    {
        $user = $event->getUser();

        $locks = $this->entityManager->getRepository('PhlexibleElementBundle:ElementLock')
            ->findBy(['userId' => $user->getId()]);

        foreach ($locks as $lock) {
            $this->entityManager->remove($lock);
        }
    }
1245226
public function deleteUser(User $user)
    {

        /* When the api will identify a user, please uncomment this
        if ($this->container->get('security.token_storage')->getToken()->getUser()->getId() === $user->getId()) {
            throw new \Exception('A user cannot delete himself');
        }*/
        $userRole = $this->roleManager->getUserRoleByUser($user);

        //soft delete~
        $user->setMail('mail#' . $user->getId());
        $user->setFirstName('firstname#' . $user->getId());
        $user->setLastName('lastname#' . $user->getId());
        $user->setPlainPassword(uniqid());
        $user->setUsername('username#' . $user->getId());
        $user->setPublicUrl('removed#' . $user->getId());
        $user->setAdministrativeCode('code#' . $user->getId());
        $user->setIsEnabled(false);

        // keeping the user's workspace with its original code
        // would prevent creating a user with the same username
        // todo: workspace deletion should be an option
        $ws = $user->getPersonalWorkspace();

        if ($ws) {
            $ws->setCode($ws->getCode() . '#deleted_user#' . $user->getId());
            $ws->setDisplayable(false);
            $this->objectManager->persist($ws);
        }

        if ($userRole) {
            $this->objectManager->remove($userRole);
        }
        $this->objectManager->persist($user);
        $this->objectManager->flush();

        $this->strictEventDispatcher->dispatch('claroline_users_delete', 'GenericDatas', array(array($user)));
        $this->strictEventDispatcher->dispatch('log', 'Log\LogUserDelete', array($user));
        $this->strictEventDispatcher->dispatch('delete_user', 'DeleteUser', array($user));
    }
639055
private function cleanAuthProvider(User $user)
    {
        $providers = $this->objectManager->getRepository('Phraseanet:UsrAuthProvider')
            ->findBy(['user' => $user]);

        foreach ($providers as $provider) {
            $this->objectManager->remove($provider);
        }
    }