Serialize the user picture.

@param User $user

@return array|null
436880
private function serializePicture(User $user)
    {
        if (!empty($user->getPicture())) {
            /** @var PublicFile $file */
            $file = $this->om
                ->getRepository(PublicFile::class)
                ->findOneBy(['url' => $user->getPicture()]);

            if ($file) {
                return $this->fileSerializer->serialize($file);
            }
        }

        return null;
    }
30305
public static function getProfileOfUser($user){
        $profiles = $user->get_profiles_list();
        if (count($profiles) === 0 || $profiles[0]->isAnonymous()) {
            return null;
        } else {
            return $profiles[0];
        }
    }
261128
public function getQbLastByUser(User $user)
    {
        $qb = $this->createQueryBuilder('d')
            ->where('d.createdBy = :user1 OR d.updatedBy = :user2')
            ->orderBy('d.updatedAt', 'desc')
            ->setParameters(
                [
                    'user1' => $user,
                    'user2' => $user,
                ]
            );

        return $qb;
    }
734482
public function getParticipant(User $user)
    {
        foreach ($this->getParticipants() as $participant) {
            if ($participant->getUser()->getId() == $user->getId()) {
                return $participant;
            }
        }

        throw new NotFoundHttpException('Participant not found' . $user->getEmail());
    }
914801
public function user($user = null)
    {
        if ($user !== null) {
            $this->user = $user;
        }

        return $this->user;
    }
70283
public function getLastPinsFromUser($user)
  {
    $pins = array();
    libxml_use_internal_errors(true);
    $xml = @simplexml_load_file('https://www.pinterest.com/'.$user.'/feed.rss');
    if($xml !== false) {
      for($i = 0; $i < 50; $i++) {
        if(!isset($xml->channel->item[$i])) {
          break;
        }
        $datas = array();
        $tags = array();
        preg_match ('/<img src=\"(?<media>.+?)\"><\/a><\/p><p>(?<text>.+?)<\/p>/', $xml->channel->item[$i]->description, $datas);
        preg_match_all('/(?<=#)\w+/', $datas['text'], $tags);
        $pins[] = array(
          'url'       => $xml->channel->item[$i]->link->asXML(),
          'media'     => $datas['media'],
          'text'      => $datas['text'],
          'tags'      => $tags[0],
          'timestamp' => strtotime($xml->channel->item[$i]->pubDate)
        );
      }
      return $pins;
    } else {
      $error = libxml_get_last_error();
      return $this->debug_mode && $error ? $error->message : null;
    }
  }
960467
private function update_picture($user) {
        global $CFG, $DB, $USER;

        require_once($CFG->libdir . '/filelib.php');
        require_once($CFG->libdir . '/gdlib.php');
        require_once($CFG->dirroot . '/user/lib.php');

        $fs = get_file_storage();
        $userid = $user->id;
        if (!empty($user->picture)) {
            return false;
        }
        if (!empty($CFG->enablegravatar)) {
            return false;
        }

        $picture = $this->get_static_user_picture();
        if (empty($picture)) {
            return false;
        }

        $context = \context_user::instance($userid, MUST_EXIST);
        $fs->delete_area_files($context->id, 'user', 'newicon');

        $filerecord = array(
            'contextid' => $context->id,
            'component' => 'user',
            'filearea' => 'newicon',
            'itemid' => 0,
            'filepath' => '/',
            'filename' => 'image'
        );

        try {
            $fs->create_file_from_string($filerecord, $picture);
        } catch (\file_exception $e) {
            return get_string($e->errorcode, $e->module, $e->a);
        }

        $iconfile = $fs->get_area_files($context->id, 'user', 'newicon', false, 'itemid', false);

        // There should only be one.
        $iconfile = reset($iconfile);

        // Something went wrong while creating temp file - remove the uploaded file.
        if (!$iconfile = $iconfile->copy_content_to_temp()) {
            $fs->delete_area_files($context->id, 'user', 'newicon');
            return false;
        }

        // Copy file to temporary location and the send it for processing icon.
        $newpicture = (int) process_new_icon($context, 'user', 'icon', 0, $iconfile);
        // Delete temporary file.
        @unlink($iconfile);
        // Remove uploaded file.
        $fs->delete_area_files($context->id, 'user', 'newicon');
        // Set the user's picture.
        $updateuser = new stdClass();
        $updateuser->id = $userid;
        $updateuser->picture = $newpicture;
        $USER->picture = $newpicture;
        user_update_user($updateuser);
        return true;
    }
1173382
public function persistUser(User $user)
    {
        $this->objectManager->persist($user);
        $this->objectManager->flush();

        return $user;
    }
490137
public function serializeToString(User $user)
    {
        $serializedUser = $this->serialize($user);

        foreach ($serializedUser as $key => $value) {
            $serializedUser[$key] = base64_encode($value);
        }

        return base64_encode(json_encode($serializedUser));
    }
689104
private function loadAllUserGroupsIdsOfUser(User $user): array
    {
        $allUserGroups = [];
        $offset = 0;

        do {
            $userGroups = $this->userService->loadUserGroupsOfUser($user, $offset, self::USER_GROUPS_LIMIT);
            foreach ($userGroups as $userGroup) {
                $allUserGroups[] = $userGroup->contentInfo->id;
            }
            $offset += self::USER_GROUPS_LIMIT;
        } while (\count($userGroups) === self::USER_GROUPS_LIMIT);

        return $allUserGroups;
    }
329159
protected function mapUserToObject(array $user)
    {
        return new User([
            'id' => $this->arrayItem($user, 'open_id'),
            'nickname' => $this->arrayItem($user, 'nick'),
            'name' => $this->arrayItem($user, 'nick'),
            'avatar' => $this->arrayItem($user, 'avatar'),
        ]);
    }
1310189
protected function mapUserToObject(array $user)
    {
        return new User([
            'id' => $this->openId,
            'unionid' => $this->unionId,
            'nickname' => $this->arrayItem($user, 'nickname'),
            'name' => $this->arrayItem($user, 'nickname'),
            'email' => $this->arrayItem($user, 'email'),
            'avatar' => $this->arrayItem($user, 'figureurl_qq_2'),
        ]);
    }
314511
public function loadUser(User $user)
    {
        // Guests do not have a user id. So do not try to load data for guests.
        if ($user->isGuest()) {
            return;
        }

        $this->db->qb([
            'table' => $this->table,
            'field' => [
                'username',
                'display_name',
                'state'
            ],
            'filter' => 'id_user=:id_user',
            'params' => [
                ':id_user' => $user->getId()
            ]
        ]);

        $data = $this->db->single();

        if (!empty($data)) {

            $user->setUsername($data['username']);

            // Use username as display_name when there is no display_name for this user
            $user->setDisplayName(empty($data['display_name']) ? $data['username'] : $data['display_name']);

            // Load the groups the user is in
            $this->db->qb([
                'table' => 'core_users_groups',
                'fields' => 'id_group',
                'filter' => 'id_user=:id_user',
                'params' => [
                    ':id_user' => $user->getId()
                ]
            ]);

            $groups = $this->db->column();

            if (!empty($groups)) {

                $user->groups->set($groups);

                // Create a prepared string and param array to use in query
                $prepared = $this->db->prepareArrayQuery('group', $groups);

                // Get and return the permissions
                $this->db->qb([
                    'table' => 'core_groups_permissions',
                    'fields' => [
                        'storage',
                        'permission'
                    ],
                    'method' => 'SELECT DISTINCT',
                    'filter' => 'id_group IN (' . $prepared['sql'] . ')',
                    'params' => $prepared['values']
                ]);

                $permissions = $this->db->all();

                foreach ($permissions as $perm) {

                    if (!array_key_exists($perm['storage'], $user->permissions)) {
                        $user->permissions[$perm['storage']] = new UserPermissions();
                    }

                    $user->permissions[$perm['storage']]->add($perm['permission']);
                }

                // Is the user an admin?
                if (!empty($user->permissions['Core']->allowedTo('admin'))) {
                    $user->setAdmin(true);
                }
            }
        }
    }
662610
public function encode(Model $user)
    {
        /** @var User $user */

        $secret = str_random();
        $token  = json_encode([
            self::KEY_USER_ID => $user->getKey(),
            self::KEY_SECRET  => $secret,
        ]);

        $user->{User::FIELD_API_TOKEN} = $secret;
        $user->saveOrFail();

        return $token;
    }
1164735
public function getRegistrationSummary(User $user = null)
    {
        $data = $userData = [];

        // Gets user data
        if (null !== $user) {
            $userData = $this->repository->getRegistrationsSummaryForUser($user);
        }

        foreach ($this->appbox->get_databoxes() as $databox) {
            $data[$databox->get_sbas_id()] = [
                // Registrations on databox by type
                'registrations' => [
                    'by-type' => [
                        'inactive'  => [],
                        'accepted'  => [],
                        'in-time'   => [],
                        'out-dated' => [],
                        'pending'   => [],
                        'rejected'  => [],
                    ]
                ],
                // Registration configuration on databox and collections that belong to the databox
                'config' => [
                    'db-name'       => $databox->get_dbname(),
                    'cgu'           => $databox->get_cgus(),
                    'can-register'  => $databox->isRegistrationEnabled(),
                    // Configuration on collection
                    'collections'   => [],
                ]
            ];

            foreach ($databox->get_collections() as $collection) {
                // Sets collection info
                $data[$databox->get_sbas_id()]['config']['collections'][$collection->get_base_id()] = $this->getCollectionSummary($collection, $userData);
                // Sets registration by type
                if (null !== $registration = $this->getUserCollectionRegistration($collection, $userData)) {
                    $data[$databox->get_sbas_id()]['registrations']['by-type'][$registration['type']][] = $registration;
                }
            }
        }

        return $data;
    }
936332
public function restore(User $user)
    {
        $this->authorize(UsersPolicy::PERMISSION_UPDATE);

        try {
            $user->restore();

            $message = $this->transNotification('restored', ['name' => $user->full_name], $user->toArray());

            return $this->jsonResponseSuccess(compact('message'));
        }
        catch (\Exception $e) {
            return $this->jsonResponseError(['message' => $e->getMessage()], 500);
        }
    }
2397
private function serializePublic(User $user)
    {
        $settingsProfile = $this->facetManager->getVisiblePublicPreference();
        $publicUser = [];

        foreach ($settingsProfile as $property => $isViewable) {
            if ($isViewable || $user === $this->tokenStorage->getToken()->getUser()) {
                switch ($property) {
                    case 'baseData':
                        $publicUser['lastName'] = $user->getLastName();
                        $publicUser['firstName'] = $user->getFirstName();
                        $publicUser['fullName'] = $user->getFirstName().' '.$user->getLastName();
                        $publicUser['username'] = $user->getUsername();
                        $publicUser['picture'] = $user->getPicture();
                        $publicUser['description'] = $user->getDescription();
                        break;
                    case 'email':
                        $publicUser['mail'] = $user->getEmail();
                        break;
                    case 'phone':
                        $publicUser['phone'] = $user->getPhone();
                        break;
                    case 'sendMail':
                        $publicUser['mail'] = $user->getEmail();
                        $publicUser['allowSendMail'] = true;
                        break;
                    case 'sendMessage':
                        $publicUser['allowSendMessage'] = true;
                        $publicUser['id'] = $user->getId();
                        break;
                }
            }
        }

        $publicUser['groups'] = [];
        //this should be protected by the visiblePublicPreference but it's not yet the case
        foreach ($user->getGroups() as $group) {
            $publicUser['groups'][] = ['name' => $group->getName(), 'id' => $group->getId()];
        }

        return $publicUser;
    }