Returns content for all webspaces.
If a webspaceKey is given the $contents array will be set as children of this webspace.

@param MappingInterface $mapping
@param array $contents
@param string $locale
@param UserInterface $user

@return Content[]
540908
private function getWebspaceNodes(
        MappingInterface $mapping,
        array $contents,
        $locale,
        UserInterface $user
    ) {
        $webspaceManager = $this->get('sulu_core.webspace.webspace_manager');
        $sessionManager = $this->get('sulu.phpcr.session');

        $paths = [];
        $webspaces = [];
        /** @var Webspace $webspace */
        foreach ($webspaceManager->getWebspaceCollection() as $webspace) {
            if (null === $webspace->getLocalization($locale)) {
                continue;
            }

            $paths[] = $sessionManager->getContentPath($webspace->getKey());
            $webspaces[$webspace->getKey()] = $webspace;
        }

        return $this->getWebspaceNodesByPaths($paths, $locale, $mapping, $webspaces, $contents, $user);
    }
1095010
public function getTranslatedFields(?string $from, ?string $to, string $remoteServiceKey, Content $content): array
    {
        $posixFrom = null;
        if (null !== $from) {
            $this->guard->enforceSourceLanguageVersionExist($content, $from);
            $posixFrom = $this->localeConverter->convertToPOSIX($from);
        }
        $this->guard->enforceTargetLanguageExist($to);

        $sourceContent     = $this->guard->fetchContent($content, $from);
        $payload           = $this->encoder->encode($sourceContent);
        $posixTo           = $this->localeConverter->convertToPOSIX($to);
        $remoteService     = $this->clientProvider->get($remoteServiceKey);
        $translatedPayload = $remoteService->translate($payload, $posixFrom, $posixTo);

        return $this->encoder->decode($translatedPayload);
    }
999962
public function getMappingFor(string $tables, string $sourceLanguage, string $targetLanguage): MappingInterface
    {
        switch ($tables) {
            case 'tl_page':
                return $this->getPageMap($sourceLanguage, $targetLanguage);
            case 'tl_article':
                return $this->getArticleMap($sourceLanguage, $targetLanguage);
            case 'tl_article.tl_content':
                return $this->getArticleContentMap($sourceLanguage, $targetLanguage);
            default:
        }
        throw new \InvalidArgumentException('Unknown table ' . $tables);
    }
1143772
public function loadUserGroupsOfUser($userId, Request $request)
    {
        $offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
        $limit = $request->query->has('limit') ? (int)$request->query->get('limit') : 25;

        $user = $this->userService->loadUser($userId);
        $userGroups = $this->userService->loadUserGroupsOfUser(
            $user,
            $offset >= 0 ? $offset : 0,
            $limit >= 0 ? $limit : 25,
            Language::ALL
        );

        $restUserGroups = array();
        foreach ($userGroups as $userGroup) {
            $userGroupContentInfo = $userGroup->getVersionInfo()->getContentInfo();
            $userGroupLocation = $this->locationService->loadLocation($userGroupContentInfo->mainLocationId);
            $contentType = $this->contentTypeService->loadContentType($userGroupContentInfo->contentTypeId);

            $restUserGroups[] = new Values\RestUserGroup(
                $userGroup,
                $contentType,
                $userGroupContentInfo,
                $userGroupLocation,
                $this->contentService->loadRelations($userGroup->getVersionInfo())
            );
        }

        return new Values\CachedValue(
            new Values\UserGroupRefList($restUserGroups, $request->getPathInfo(), $userId),
            array('locationId' => $user->contentInfo->mainLocationId)
        );
    }
584700
public function data(DatatablesService $datatables_service, ServerRequestInterface $request, UserInterface $user): ResponseInterface
    {
        $installed_languages = [];
        foreach (I18N::installedLocales() as $installed_locale) {
            $installed_languages[$installed_locale->languageTag()] = $installed_locale->endonym();
        }

        $query = DB::table('user')
            ->leftJoin('user_setting AS us1', static function (JoinClause $join): void {
                $join
                    ->on('us1.user_id', '=', 'user.user_id')
                    ->where('us1.setting_name', '=', 'language');
            })
            ->leftJoin('user_setting AS us2', static function (JoinClause $join): void {
                $join
                    ->on('us2.user_id', '=', 'user.user_id')
                    ->where('us2.setting_name', '=', 'reg_timestamp');
            })
            ->leftJoin('user_setting AS us3', static function (JoinClause $join): void {
                $join
                    ->on('us3.user_id', '=', 'user.user_id')
                    ->where('us3.setting_name', '=', 'sessiontime');
            })
            ->leftJoin('user_setting AS us4', static function (JoinClause $join): void {
                $join
                    ->on('us4.user_id', '=', 'user.user_id')
                    ->where('us4.setting_name', '=', 'verified');
            })
            ->leftJoin('user_setting AS us5', static function (JoinClause $join): void {
                $join
                    ->on('us5.user_id', '=', 'user.user_id')
                    ->where('us5.setting_name', '=', 'verified_by_admin');
            })
            ->where('user.user_id', '>', '0')
            ->select([
                'user.user_id AS edit_menu', // Hidden column
                'user.user_id',
                'user_name',
                'real_name',
                'email',
                'us1.setting_value AS language',
                'us2.setting_value AS registered_at_sort', // Hidden column
                'us2.setting_value AS registered_at',
                'us3.setting_value AS active_at_sort', // Hidden column
                'us3.setting_value AS active_at',
                'us4.setting_value AS verified',
                'us5.setting_value AS verified_by_admin',
            ]);

        $search_columns = ['user_name', 'real_name', 'email'];
        $sort_columns   = [];

        $callback = static function (stdClass $row) use ($installed_languages, $user): array {
            if ($row->user_id !== $user->id()) {
                $admin_options = '<div class="dropdown-item"><a href="#" onclick="return masquerade(' . $row->user_id . ')">' . view('icons/user') . ' ' . I18N::translate('Masquerade as this user') . '</a></div>' . '<div class="dropdown-item"><a href="#" data-confirm="' . I18N::translate('Are you sure you want to delete “%s”?', e($row->user_name)) . '" onclick="delete_user(this.dataset.confirm, ' . $row->user_id . ');">' . view('icons/delete') . ' ' . I18N::translate('Delete') . '</a></div>';
            } else {
                // Do not delete ourself!
                $admin_options = '';
            }

            // Link to send email to other users.
            if ($row->user_id != $user->id()) {
                $row->email = '<a href="' . e(route('message', ['to' => $row->user_name])) . '">' . e($row->email) . '</a>';
            } else {
                $row->email = e($row->email);
            }

            $datum = [
                '<div class="dropdown"><button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" id="edit-user-button-' . $row->user_id . '" aria-haspopup="true" aria-expanded="false">' . view('icons/edit') . ' <span class="caret"></span></button><div class="dropdown-menu" aria-labelledby="edit-user-button-' . $row->user_id . '"><div class="dropdown-item"><a href="' . e(route('admin-users-edit', ['user_id' => $row->user_id])) . '">' . view('icons/edit') . ' ' . I18N::translate('Edit') . '</a></div><div class="divider"></div><div class="dropdown-item"><a href="' . e(route('user-page-user-edit', ['user_id' => $row->user_id])) . '">' . view('icons/block') . ' ' . I18N::translate('Change the blocks on this user’s “My page”') . '</a></div>' . $admin_options . '</div></div>',
                $row->user_id,
                '<span dir="auto">' . e($row->user_name) . '</span>',
                '<span dir="auto">' . e($row->real_name) . '</span>',
                $row->email,
                $installed_languages[$row->language] ?? $row->language,
                $row->registered_at,
                $row->registered_at ? view('components/datetime-diff', ['timestamp' => Carbon::createFromTimestamp((int) $row->registered_at)]) : '',
                $row->active_at,
                $row->active_at ? view('components/datetime-diff', ['timestamp' => Carbon::createFromTimestamp((int) $row->active_at)]) : I18N::translate('Never'),
                $row->verified ? I18N::translate('yes') : I18N::translate('no'),
                $row->verified_by_admin ? I18N::translate('yes') : I18N::translate('no'),
            ];

            // Highlight old registrations.
            if (date('U') - $datum[6] > 604800 && !$datum[10]) {
                $datum[7] = '<span class="text-danger">' . $datum[7] . '</span>';
            }

            return $datum;
        };

        return $datatables_service->handle($request, $query, $search_columns, $sort_columns, $callback);
    }
994917
public function mapContent(Content $content)
    {
        $locations = $this->locationHandler->loadLocationsByContent($content->versionInfo->contentInfo->id);
        $section = $this->sectionHandler->load($content->versionInfo->contentInfo->sectionId);
        $mainLocation = null;
        $locationDocuments = array();
        foreach ($locations as $location) {
            $locationDocuments[] = $this->mapContentLocation($location, $content);
        }

        // UserGroups and Users are Content, but permissions cascade is achieved through
        // Locations hierarchy. We index all ancestor Location Content ids of all
        // Locations of an owner.
        $ancestorLocationsContentIds = $this->getAncestorLocationsContentIds(
            $content->versionInfo->contentInfo->ownerId
        );
        // Add owner user id as it can also be considered as user group.
        $ancestorLocationsContentIds[] = $content->versionInfo->contentInfo->ownerId;

        $fields = array(
            new Field(
                'id',
                $content->versionInfo->contentInfo->id,
                new FieldType\IdentifierField()
            ),
            new Field(
                'type',
                $content->versionInfo->contentInfo->contentTypeId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'version',
                $content->versionInfo->versionNo,
                new FieldType\IdentifierField()
            ),
            new Field(
                'status',
                $content->versionInfo->status,
                new FieldType\IdentifierField()
            ),
            new Field(
                'name',
                $content->versionInfo->contentInfo->name,
                new FieldType\StringField()
            ),
            new Field(
                'creator',
                $content->versionInfo->creatorId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner',
                $content->versionInfo->contentInfo->ownerId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'owner_user_group',
                $ancestorLocationsContentIds,
                new FieldType\MultipleIdentifierField()
            ),
            new Field(
                'section',
                $content->versionInfo->contentInfo->sectionId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_identifier',
                $section->identifier,
                new FieldType\IdentifierField()
            ),
            new Field(
                'section_name',
                $section->name,
                new FieldType\StringField()
            ),
            new Field(
                'remote_id',
                $content->versionInfo->contentInfo->remoteId,
                new FieldType\IdentifierField()
            ),
            new Field(
                'modified',
                $content->versionInfo->contentInfo->modificationDate,
                new FieldType\DateField()
            ),
            new Field(
                'published',
                $content->versionInfo->contentInfo->publicationDate,
                new FieldType\DateField()
            ),
            new Field(
                'language_code',
                array_keys($content->versionInfo->names),
                new FieldType\MultipleStringField()
            ),
            new Field(
                'always_available',
                $content->versionInfo->contentInfo->alwaysAvailable,
                new FieldType\BooleanField()
            ),
            new Field(
                'locations',
                $locationDocuments,
                new FieldType\DocumentField()
            ),
        );

        $contentType = $this->contentTypeHandler->load($content->versionInfo->contentInfo->contentTypeId);
        $fields[] = new Field(
            'group',
            $contentType->groupIds,
            new FieldType\MultipleIdentifierField()
        );
        $fields[] = new Field(
            'fields',
            $this->mapFields($content, $contentType),
            new FieldType\DocumentField()
        );

        $fields[] = new Field(
            'object_state',
            $this->getObjectStateIds($content->versionInfo->contentInfo->id),
            new FieldType\MultipleIdentifierField()
        );

        $document = new Document(
            array(
                'id' => $content->versionInfo->contentInfo->id,
                'type' => 'content',
                'fields' => $fields,
            )
        );

        return $document;
    }
589905
public function findBySubject(ContentSubjectInterface $subject)
    {
        $content = $subject->getContent();

        if (null !== $content && property_exists($content, '__isInitialized__') && !$content->{'__isInitialized__'}) {
            $qb = $this->getQueryBuilder();
            $qb
                ->leftJoin('c.containers', 'container')
                ->leftJoin('container.rows', 'row')
                ->leftJoin('row.blocks', 'block')
                ->leftJoin('block.translations', 'block_t')
                ->select('PARTIAL c.{id}', 'container', 'row', 'block', 'block_t')
                ->andWhere($qb->expr()->eq('c.id', ':id'))
                ->getQuery()
                ->useQueryCache(true)
                // TODO ->useResultCache(true, 3600, Content::getEntityTagPrefix() . '[id:'.$id.']')
                ->setParameter('id', $content->getId())
                ->getOneOrNullResult();
        }

        return $content;
    }
655889
public function getChartAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
    {
        Auth::checkComponentAccess($this, 'chart', $tree, $user);

        $ajax  = (bool) $request->get('ajax');
        $scale = (int) $request->get('scale', self::SCALE_DEFAULT);
        $scale = min($scale, self::SCALE_MAX);
        $scale = max($scale, self::SCALE_MIN);

        $xrefs = $request->get('xrefs', []);

        // Find the requested individuals.
        $individuals = (new Collection($xrefs))
            ->unique()
            ->map(static function (string $xref) use ($tree): ?Individual {
                return Individual::getInstance($xref, $tree);
            })
            ->filter()
            ->filter(GedcomRecord::accessFilter());

        // Generate URLs omitting each xref.
        $remove_urls = [];

        foreach ($individuals as $exclude) {
            $xrefs_1 = $individuals
                ->filter(static function (Individual $individual) use ($exclude): bool {
                    return $individual->xref() !== $exclude->xref();
                })
                ->map(static function (Individual $individual): string {
                    return $individual->xref();
                });

            $remove_urls[$exclude->xref()] = route('module', [
                'module' => $this->name(),
                'action' => 'Chart',
                'ged'    => $tree->name(),
                'scale'  => $scale,
                'xrefs'  => $xrefs_1->all(),
            ]);
        }

        $individuals = array_map(static function (string $xref) use ($tree): ?Individual {
            return Individual::getInstance($xref, $tree);
        }, $xrefs);

        $individuals = array_filter($individuals, static function (?Individual $individual): bool {
            return $individual instanceof Individual && $individual->canShow();
        });

        if ($ajax) {
            return $this->chart($tree, $xrefs, $scale);
        }

        $ajax_url = route('module', [
            'ajax'   => true,
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
            'scale'  => $scale,
            'xrefs'  => $xrefs,
        ]);

        $reset_url = route('module', [
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
        ]);

        $zoom_in_url = route('module', [
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
            'scale'  => min(self::SCALE_MAX, $scale + (int) ($scale * 0.2 + 1)),
            'xrefs'  => $xrefs,
        ]);

        $zoom_out_url = route('module', [
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
            'scale'  => max(self::SCALE_MIN, $scale - (int) ($scale * 0.2 + 1)),
            'xrefs'  => $xrefs,
        ]);

        return $this->viewResponse('modules/timeline-chart/page', [
            'ajax_url'     => $ajax_url,
            'individuals'  => $individuals,
            'module_name'  => $this->name(),
            'remove_urls'  => $remove_urls,
            'reset_url'    => $reset_url,
            'title'        => $this->title(),
            'scale'        => $scale,
            'zoom_in_url'  => $zoom_in_url,
            'zoom_out_url' => $zoom_out_url,
        ]);
    }
1002946
private function getQueryBuilder($locale, $locales, UserInterface $user = null)
    {
        $queryBuilder = new QueryBuilder($this->qomFactory);

        $queryBuilder
            ->select('node', 'jcr:uuid', 'uuid')
            ->addSelect('node', $this->getPropertyName('nodeType', $locale), 'nodeType')
            ->addSelect('node', $this->getPropertyName('internal_link', $locale), 'internalLink')
            ->addSelect('node', $this->getPropertyName('state', $locale), 'state')
            ->addSelect('node', $this->getPropertyName('shadow-on', $locale), 'shadowOn')
            ->addSelect('node', $this->getPropertyName('shadow-base', $locale), 'shadowBase')
            ->addSelect('node', $this->propertyEncoder->systemName('order'), 'order')
            ->from($this->qomFactory->selector('node', 'nt:unstructured'))
            ->orderBy($this->qomFactory->propertyValue('node', 'sulu:order'));

        $this->appendSingleMapping($queryBuilder, 'template', $locales);
        $this->appendSingleMapping($queryBuilder, 'shadow-on', $locales);
        $this->appendSingleMapping($queryBuilder, 'state', $locales);

        if (null !== $user) {
            foreach ($user->getRoleObjects() as $role) {
                $queryBuilder->addSelect(
                    'node',
                    sprintf('sec:%s', 'role-' . $role->getId()),
                    sprintf('role%s', $role->getId())
                );
            }
        }

        return $queryBuilder;
    }
880456
protected function createContent($user, array $options, $property)
    {
        if (!$this->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            return null;
        }
        foreach ($user->getRoles() as $role) {
            if (preg_match('/ADMIN$/', $role)) {
                return $this->render([], [
                    'user' => $user,
                ]);
            }
        }

        return null;
    }
957911
public function getZfcUserMapper()
    {
        if (!$this->zfcUserMapper instanceof UserMapperInterface) {
            $this->setZfcUserMapper($this->getServiceLocator()->get('zfcuser_user_mapper'));
        }

        return $this->zfcUserMapper;
    }
1348779
protected function doMap(
        $source,
        $destination,
        MappingInterface $mapping,
        array $context = []
    ) {
        $propertyNames = $mapping->getTargetProperties($destination, $source);
        foreach ($propertyNames as $propertyName) {
            $mappingOperation = $mapping->getMappingOperationFor($propertyName);

            if ($mappingOperation instanceof MapperAwareOperation) {
                $mappingOperation->setMapper($this);
            }
            if ($mappingOperation instanceof ContextAwareOperation) {
                $mappingOperation->setContext($context);
            }

            $mappingOperation->mapProperty(
                $propertyName,
                $source,
                $destination
            );
        }

        return $destination;
    }
1007857
static protected function parseMapping($mapping, &$i = 0)
  {
    $output = array();
    $len = strlen($mapping);
    $i += 1;

    // {foo: bar, bar:foo, ...}
    while ($i < $len)
    {
      switch ($mapping[$i])
      {
        case ' ':
        case ',':
          ++$i;
          continue 2;
        case '}':
          return $output;
      }

      // key
      $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);

      // value
      $done = false;
      while ($i < $len)
      {
        switch ($mapping[$i])
        {
          case '[':
            // nested sequence
            $output[$key] = self::parseSequence($mapping, $i);
            $done = true;
            break;
          case '{':
            // nested mapping
            $output[$key] = self::parseMapping($mapping, $i);
            $done = true;
            break;
          case ':':
          case ' ':
            break;
          default:
            $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i);
            $done = true;
            --$i;
        }

        ++$i;

        if ($done)
        {
          continue 2;
        }
      }
    }

    throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping));
  }
838391
public function createContent( $contentType, $fields, $parentLocationId )
    {
        $repository = $this->getRepository();
        $languageCode = self::DEFAULT_LANGUAGE;

        $content = $this->getRepository()->sudo(
            function(Repository $repository) use ( $parentLocationId, $contentType, $fields, $languageCode )
            {
                $content = $this->createContentDraft($parentLocationId, $contentType, $fields, $languageCode);
                return $content = $repository->getContentService()->publishVersion($content->versionInfo);
            }
        );

        return $content->contentInfo->mainLocationId;
    }
674145
public function formatter(ResultSetInterface $resultSet, array $fields, RepositoryInterface $table, array $user) : array
    {
        $result = [];

        if ($resultSet->isEmpty()) {
            return $result;
        }

        $cakeView = new View();
        $registryAlias = $table->getRegistryAlias();
        $alias = $table->getAlias();

        foreach ($resultSet as $key => $entity) {
            foreach ($fields as $field) {
                list($tableName, $fieldName) = explode('.', $field);
                // current table field
                if ($alias === $tableName) {
                    $result[$key][$field] = $entity->get($fieldName);
                    continue;
                }

                if (!$entity->get('_matchingData')) {
                    continue;
                }

                if (!isset($entity->_matchingData[$tableName])) {
                    continue;
                }
                // associated table field
                $result[$key][$field] = $entity->_matchingData[$tableName]->get($fieldName);
            }

            $result[$key][static::MENU_PROPERTY_NAME] = $cakeView->element('Search.Menu/search-view-actions', [
                'entity' => $entity,
                'model' => $registryAlias,
                'user' => $user
            ]);
        }

        return $result;
    }
132207
public static function applyAppRoleMapByService($user, $serviceId)
    {
        $maps = AppRoleMap::whereServiceId($serviceId)->get();

        foreach ($maps as $map) {
            UserAppRole::whereUserId($user->id)->whereAppId($map->app_id)->delete();
            $userAppRoleData = [
                'user_id' => $user->id,
                'app_id'  => $map->app_id,
                'role_id' => $map->role_id
            ];

            UserAppRole::create($userAppRoleData);
        }
    }
1166865
public function getChartAction(ServerRequestInterface $request, Tree $tree, UserInterface $user): ResponseInterface
    {
        Auth::checkComponentAccess($this, 'chart', $tree, $user);

        $ajax      = (bool) $request->get('ajax');
        $xrefs     = (array) $request->get('xrefs', []);
        $addxref   = $request->get('addxref', '');
        $addfam    = (bool) $request->get('addfam', false);
        $placename = $request->get('placename', '');
        $start     = $request->get('start', '');
        $end       = $request->get('end', '');

        $place      = new Place($placename, $tree);
        $start_date = new Date($start);
        $end_date   = new Date($end);

        $xrefs = array_unique($xrefs);

        // Add an individual, and family members
        $individual = Individual::getInstance($addxref, $tree);
        if ($individual !== null) {
            $xrefs[] = $addxref;
            if ($addfam) {
                $xrefs = array_merge($xrefs, $this->closeFamily($individual));
            }
        }

        // Select by date and/or place.
        if ($start_date->isOK() && $end_date->isOK() && $placename !== '') {
            $date_xrefs  = $this->findIndividualsByDate($start_date, $end_date, $tree);
            $place_xrefs = $this->findIndividualsByPlace($place, $tree);
            $xrefs       = array_intersect($date_xrefs, $place_xrefs);
        } elseif ($start_date->isOK() && $end_date->isOK()) {
            $xrefs = $this->findIndividualsByDate($start_date, $end_date, $tree);
        } elseif ($placename !== '') {
            $xrefs = $this->findIndividualsByPlace($place, $tree);
        }

        // Filter duplicates and private individuals.
        $xrefs = array_unique($xrefs);
        $xrefs = array_filter($xrefs, static function (string $xref) use ($tree): bool {
            $individual = Individual::getInstance($xref, $tree);

            return $individual !== null && $individual->canShow();
        });

        if ($ajax) {
            $subtitle = $this->subtitle(count($xrefs), $start_date, $end_date, $placename);

            return $this->chart($tree, $xrefs, $subtitle);
        }

        $ajax_url = route('module', [
            'ajax'   => true,
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
            'xrefs'  => $xrefs,
        ]);

        $reset_url = route('module', [
            'module' => $this->name(),
            'action' => 'Chart',
            'ged'    => $tree->name(),
        ]);

        return $this->viewResponse('modules/lifespans-chart/page', [
            'ajax_url'    => $ajax_url,
            'module_name' => $this->name(),
            'reset_url'   => $reset_url,
            'title'       => $this->title(),
            'xrefs'       => $xrefs,
        ]);
    }