@@ -28,33 +28,33 @@ |
||
28 | 28 | * @since 26.0.0 |
29 | 29 | */ |
30 | 30 | interface IDiscoverableReferenceProvider extends IReferenceProvider { |
31 | - /** |
|
32 | - * @return string Unique id that identifies the reference provider |
|
33 | - * @since 26.0.0 |
|
34 | - */ |
|
35 | - public function getId(): string; |
|
31 | + /** |
|
32 | + * @return string Unique id that identifies the reference provider |
|
33 | + * @since 26.0.0 |
|
34 | + */ |
|
35 | + public function getId(): string; |
|
36 | 36 | |
37 | - /** |
|
38 | - * @return string User facing title of the widget |
|
39 | - * @since 26.0.0 |
|
40 | - */ |
|
41 | - public function getTitle(): string; |
|
37 | + /** |
|
38 | + * @return string User facing title of the widget |
|
39 | + * @since 26.0.0 |
|
40 | + */ |
|
41 | + public function getTitle(): string; |
|
42 | 42 | |
43 | - /** |
|
44 | - * @return int Initial order for reference provider sorting |
|
45 | - * @since 26.0.0 |
|
46 | - */ |
|
47 | - public function getOrder(): int; |
|
43 | + /** |
|
44 | + * @return int Initial order for reference provider sorting |
|
45 | + * @since 26.0.0 |
|
46 | + */ |
|
47 | + public function getOrder(): int; |
|
48 | 48 | |
49 | - /** |
|
50 | - * @return string url to an icon that can be displayed next to the reference provider title |
|
51 | - * @since 26.0.0 |
|
52 | - */ |
|
53 | - public function getIconUrl(): string; |
|
49 | + /** |
|
50 | + * @return string url to an icon that can be displayed next to the reference provider title |
|
51 | + * @since 26.0.0 |
|
52 | + */ |
|
53 | + public function getIconUrl(): string; |
|
54 | 54 | |
55 | - /** |
|
56 | - * @return array representation of the provider |
|
57 | - * @since 26.0.0 |
|
58 | - */ |
|
59 | - public function jsonSerialize(): array; |
|
55 | + /** |
|
56 | + * @return array representation of the provider |
|
57 | + * @since 26.0.0 |
|
58 | + */ |
|
59 | + public function jsonSerialize(): array; |
|
60 | 60 | } |
@@ -28,71 +28,71 @@ |
||
28 | 28 | * @since 25.0.0 |
29 | 29 | */ |
30 | 30 | interface IReferenceManager { |
31 | - /** |
|
32 | - * Return all reference identifiers within a string as an array |
|
33 | - * |
|
34 | - * @return string[] Array of found references (urls) |
|
35 | - * @since 25.0.0 |
|
36 | - */ |
|
37 | - public function extractReferences(string $text): array; |
|
31 | + /** |
|
32 | + * Return all reference identifiers within a string as an array |
|
33 | + * |
|
34 | + * @return string[] Array of found references (urls) |
|
35 | + * @since 25.0.0 |
|
36 | + */ |
|
37 | + public function extractReferences(string $text): array; |
|
38 | 38 | |
39 | - /** |
|
40 | - * Resolve a given reference id to its metadata with all available providers |
|
41 | - * |
|
42 | - * This method has a fallback to always provide the open graph metadata, |
|
43 | - * but may still return null in case this is disabled or the fetching fails |
|
44 | - * |
|
45 | - * @since 25.0.0 |
|
46 | - */ |
|
47 | - public function resolveReference(string $referenceId): ?IReference; |
|
39 | + /** |
|
40 | + * Resolve a given reference id to its metadata with all available providers |
|
41 | + * |
|
42 | + * This method has a fallback to always provide the open graph metadata, |
|
43 | + * but may still return null in case this is disabled or the fetching fails |
|
44 | + * |
|
45 | + * @since 25.0.0 |
|
46 | + */ |
|
47 | + public function resolveReference(string $referenceId): ?IReference; |
|
48 | 48 | |
49 | - /** |
|
50 | - * Get a reference by its cache key |
|
51 | - * |
|
52 | - * @since 25.0.0 |
|
53 | - */ |
|
54 | - public function getReferenceByCacheKey(string $cacheKey): ?IReference; |
|
49 | + /** |
|
50 | + * Get a reference by its cache key |
|
51 | + * |
|
52 | + * @since 25.0.0 |
|
53 | + */ |
|
54 | + public function getReferenceByCacheKey(string $cacheKey): ?IReference; |
|
55 | 55 | |
56 | - /** |
|
57 | - * Explicitly get a reference from the cache to avoid heavy fetches for cases |
|
58 | - * the cache can then be filled with a separate request from the frontend |
|
59 | - * |
|
60 | - * @since 25.0.0 |
|
61 | - */ |
|
62 | - public function getReferenceFromCache(string $referenceId): ?IReference; |
|
56 | + /** |
|
57 | + * Explicitly get a reference from the cache to avoid heavy fetches for cases |
|
58 | + * the cache can then be filled with a separate request from the frontend |
|
59 | + * |
|
60 | + * @since 25.0.0 |
|
61 | + */ |
|
62 | + public function getReferenceFromCache(string $referenceId): ?IReference; |
|
63 | 63 | |
64 | - /** |
|
65 | - * Invalidate all cache entries with a prefix or just one if the cache key is provided |
|
66 | - * |
|
67 | - * @since 25.0.0 |
|
68 | - */ |
|
69 | - public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void; |
|
64 | + /** |
|
65 | + * Invalidate all cache entries with a prefix or just one if the cache key is provided |
|
66 | + * |
|
67 | + * @since 25.0.0 |
|
68 | + */ |
|
69 | + public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void; |
|
70 | 70 | |
71 | - /** |
|
72 | - * Get information on discoverable reference providers (id, title, icon and order) |
|
73 | - * If the provider is searchable, also get the list of supported unified search providers |
|
74 | - * |
|
75 | - * @return IDiscoverableReferenceProvider[] |
|
76 | - * @since 26.0.0 |
|
77 | - */ |
|
78 | - public function getDiscoverableProviders(): array; |
|
71 | + /** |
|
72 | + * Get information on discoverable reference providers (id, title, icon and order) |
|
73 | + * If the provider is searchable, also get the list of supported unified search providers |
|
74 | + * |
|
75 | + * @return IDiscoverableReferenceProvider[] |
|
76 | + * @since 26.0.0 |
|
77 | + */ |
|
78 | + public function getDiscoverableProviders(): array; |
|
79 | 79 | |
80 | - /** |
|
81 | - * Update or set the last used timestamp for a provider |
|
82 | - * |
|
83 | - * @param string $userId |
|
84 | - * @param string $providerId |
|
85 | - * @param int|null $timestamp use current timestamp if null |
|
86 | - * @return bool |
|
87 | - * @since 26.0.0 |
|
88 | - */ |
|
89 | - public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool; |
|
80 | + /** |
|
81 | + * Update or set the last used timestamp for a provider |
|
82 | + * |
|
83 | + * @param string $userId |
|
84 | + * @param string $providerId |
|
85 | + * @param int|null $timestamp use current timestamp if null |
|
86 | + * @return bool |
|
87 | + * @since 26.0.0 |
|
88 | + */ |
|
89 | + public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool; |
|
90 | 90 | |
91 | - /** |
|
92 | - * Get all known last used timestamps for reference providers |
|
93 | - * |
|
94 | - * @return int[] |
|
95 | - * @since 26.0.0 |
|
96 | - */ |
|
97 | - public function getUserProviderTimestamps(): array; |
|
91 | + /** |
|
92 | + * Get all known last used timestamps for reference providers |
|
93 | + * |
|
94 | + * @return int[] |
|
95 | + * @since 26.0.0 |
|
96 | + */ |
|
97 | + public function getUserProviderTimestamps(): array; |
|
98 | 98 | } |
@@ -30,19 +30,19 @@ |
||
30 | 30 | * @since 26.0.0 |
31 | 31 | */ |
32 | 32 | abstract class ADiscoverableReferenceProvider implements IDiscoverableReferenceProvider, JsonSerializable { |
33 | - /** |
|
34 | - * @since 26.0.0 |
|
35 | - */ |
|
36 | - public function jsonSerialize(): array { |
|
37 | - $json = [ |
|
38 | - 'id' => $this->getId(), |
|
39 | - 'title' => $this->getTitle(), |
|
40 | - 'icon_url' => $this->getIconUrl(), |
|
41 | - 'order' => $this->getOrder(), |
|
42 | - ]; |
|
43 | - if ($this instanceof ISearchableReferenceProvider) { |
|
44 | - $json['search_providers_ids'] = $this->getSupportedSearchProviderIds(); |
|
45 | - } |
|
46 | - return $json; |
|
47 | - } |
|
33 | + /** |
|
34 | + * @since 26.0.0 |
|
35 | + */ |
|
36 | + public function jsonSerialize(): array { |
|
37 | + $json = [ |
|
38 | + 'id' => $this->getId(), |
|
39 | + 'title' => $this->getTitle(), |
|
40 | + 'icon_url' => $this->getIconUrl(), |
|
41 | + 'order' => $this->getOrder(), |
|
42 | + ]; |
|
43 | + if ($this instanceof ISearchableReferenceProvider) { |
|
44 | + $json['search_providers_ids'] = $this->getSupportedSearchProviderIds(); |
|
45 | + } |
|
46 | + return $json; |
|
47 | + } |
|
48 | 48 | } |
@@ -28,9 +28,9 @@ |
||
28 | 28 | * @since 26.0.0 |
29 | 29 | */ |
30 | 30 | interface ISearchableReferenceProvider extends IDiscoverableReferenceProvider { |
31 | - /** |
|
32 | - * @return string[] list of search provider IDs that can be used by the vue-richtext picker |
|
33 | - * @since 26.0.0 |
|
34 | - */ |
|
35 | - public function getSupportedSearchProviderIds(): array; |
|
31 | + /** |
|
32 | + * @return string[] list of search provider IDs that can be used by the vue-richtext picker |
|
33 | + * @since 26.0.0 |
|
34 | + */ |
|
35 | + public function getSupportedSearchProviderIds(): array; |
|
36 | 36 | } |
@@ -34,33 +34,33 @@ |
||
34 | 34 | |
35 | 35 | /** @template-implements IEventListener<Event|RenderReferenceEvent> */ |
36 | 36 | class RenderReferenceEventListener implements IEventListener { |
37 | - private IReferenceManager $manager; |
|
38 | - private IInitialStateService $initialStateService; |
|
37 | + private IReferenceManager $manager; |
|
38 | + private IInitialStateService $initialStateService; |
|
39 | 39 | |
40 | - public function __construct(IReferenceManager $manager, IInitialStateService $initialStateService) { |
|
41 | - $this->manager = $manager; |
|
42 | - $this->initialStateService = $initialStateService; |
|
43 | - } |
|
40 | + public function __construct(IReferenceManager $manager, IInitialStateService $initialStateService) { |
|
41 | + $this->manager = $manager; |
|
42 | + $this->initialStateService = $initialStateService; |
|
43 | + } |
|
44 | 44 | |
45 | - public static function register(IEventDispatcher $eventDispatcher): void { |
|
46 | - $eventDispatcher->addServiceListener(RenderReferenceEvent::class, RenderReferenceEventListener::class); |
|
47 | - } |
|
45 | + public static function register(IEventDispatcher $eventDispatcher): void { |
|
46 | + $eventDispatcher->addServiceListener(RenderReferenceEvent::class, RenderReferenceEventListener::class); |
|
47 | + } |
|
48 | 48 | |
49 | - /** |
|
50 | - * @inheritDoc |
|
51 | - */ |
|
52 | - public function handle(Event $event): void { |
|
53 | - if (!($event instanceof RenderReferenceEvent)) { |
|
54 | - return; |
|
55 | - } |
|
49 | + /** |
|
50 | + * @inheritDoc |
|
51 | + */ |
|
52 | + public function handle(Event $event): void { |
|
53 | + if (!($event instanceof RenderReferenceEvent)) { |
|
54 | + return; |
|
55 | + } |
|
56 | 56 | |
57 | - $providers = $this->manager->getDiscoverableProviders(); |
|
58 | - $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
59 | - return $provider->jsonSerialize(); |
|
60 | - }, $providers); |
|
61 | - $this->initialStateService->provideInitialState('core', 'reference-provider-list', $jsonProviders); |
|
57 | + $providers = $this->manager->getDiscoverableProviders(); |
|
58 | + $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
59 | + return $provider->jsonSerialize(); |
|
60 | + }, $providers); |
|
61 | + $this->initialStateService->provideInitialState('core', 'reference-provider-list', $jsonProviders); |
|
62 | 62 | |
63 | - $timestamps = $this->manager->getUserProviderTimestamps(); |
|
64 | - $this->initialStateService->provideInitialState('core', 'reference-provider-timestamps', $timestamps); |
|
65 | - } |
|
63 | + $timestamps = $this->manager->getUserProviderTimestamps(); |
|
64 | + $this->initialStateService->provideInitialState('core', 'reference-provider-timestamps', $timestamps); |
|
65 | + } |
|
66 | 66 | } |
@@ -55,7 +55,7 @@ |
||
55 | 55 | } |
56 | 56 | |
57 | 57 | $providers = $this->manager->getDiscoverableProviders(); |
58 | - $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
58 | + $jsonProviders = array_map(static function(IDiscoverableReferenceProvider $provider) { |
|
59 | 59 | return $provider->jsonSerialize(); |
60 | 60 | }, $providers); |
61 | 61 | $this->initialStateService->provideInitialState('core', 'reference-provider-list', $jsonProviders); |
@@ -34,30 +34,30 @@ |
||
34 | 34 | |
35 | 35 | /** @template-implements IEventListener<Event|NodeDeletedEvent|ShareDeletedEvent|ShareCreatedEvent> */ |
36 | 36 | class FileReferenceEventListener implements IEventListener { |
37 | - private IReferenceManager $manager; |
|
37 | + private IReferenceManager $manager; |
|
38 | 38 | |
39 | - public function __construct(IReferenceManager $manager) { |
|
40 | - $this->manager = $manager; |
|
41 | - } |
|
39 | + public function __construct(IReferenceManager $manager) { |
|
40 | + $this->manager = $manager; |
|
41 | + } |
|
42 | 42 | |
43 | - public static function register(IEventDispatcher $eventDispatcher): void { |
|
44 | - $eventDispatcher->addServiceListener(NodeDeletedEvent::class, FileReferenceEventListener::class); |
|
45 | - $eventDispatcher->addServiceListener(ShareDeletedEvent::class, FileReferenceEventListener::class); |
|
46 | - $eventDispatcher->addServiceListener(ShareCreatedEvent::class, FileReferenceEventListener::class); |
|
47 | - } |
|
43 | + public static function register(IEventDispatcher $eventDispatcher): void { |
|
44 | + $eventDispatcher->addServiceListener(NodeDeletedEvent::class, FileReferenceEventListener::class); |
|
45 | + $eventDispatcher->addServiceListener(ShareDeletedEvent::class, FileReferenceEventListener::class); |
|
46 | + $eventDispatcher->addServiceListener(ShareCreatedEvent::class, FileReferenceEventListener::class); |
|
47 | + } |
|
48 | 48 | |
49 | - /** |
|
50 | - * @inheritDoc |
|
51 | - */ |
|
52 | - public function handle(Event $event): void { |
|
53 | - if ($event instanceof NodeDeletedEvent) { |
|
54 | - $this->manager->invalidateCache((string)$event->getNode()->getId()); |
|
55 | - } |
|
56 | - if ($event instanceof ShareDeletedEvent) { |
|
57 | - $this->manager->invalidateCache((string)$event->getShare()->getNodeId()); |
|
58 | - } |
|
59 | - if ($event instanceof ShareCreatedEvent) { |
|
60 | - $this->manager->invalidateCache((string)$event->getShare()->getNodeId()); |
|
61 | - } |
|
62 | - } |
|
49 | + /** |
|
50 | + * @inheritDoc |
|
51 | + */ |
|
52 | + public function handle(Event $event): void { |
|
53 | + if ($event instanceof NodeDeletedEvent) { |
|
54 | + $this->manager->invalidateCache((string)$event->getNode()->getId()); |
|
55 | + } |
|
56 | + if ($event instanceof ShareDeletedEvent) { |
|
57 | + $this->manager->invalidateCache((string)$event->getShare()->getNodeId()); |
|
58 | + } |
|
59 | + if ($event instanceof ShareCreatedEvent) { |
|
60 | + $this->manager->invalidateCache((string)$event->getShare()->getNodeId()); |
|
61 | + } |
|
62 | + } |
|
63 | 63 | } |
@@ -41,244 +41,244 @@ |
||
41 | 41 | use Throwable; |
42 | 42 | |
43 | 43 | class ReferenceManager implements IReferenceManager { |
44 | - public const CACHE_TTL = 3600; |
|
45 | - |
|
46 | - /** @var IReferenceProvider[]|null */ |
|
47 | - private ?array $providers = null; |
|
48 | - private ICache $cache; |
|
49 | - private Coordinator $coordinator; |
|
50 | - private ContainerInterface $container; |
|
51 | - private LinkReferenceProvider $linkReferenceProvider; |
|
52 | - private LoggerInterface $logger; |
|
53 | - private IConfig $config; |
|
54 | - private IUserSession $userSession; |
|
55 | - |
|
56 | - public function __construct(LinkReferenceProvider $linkReferenceProvider, |
|
57 | - ICacheFactory $cacheFactory, |
|
58 | - Coordinator $coordinator, |
|
59 | - ContainerInterface $container, |
|
60 | - LoggerInterface $logger, |
|
61 | - IConfig $config, |
|
62 | - IUserSession $userSession) { |
|
63 | - $this->linkReferenceProvider = $linkReferenceProvider; |
|
64 | - $this->cache = $cacheFactory->createDistributed('reference'); |
|
65 | - $this->coordinator = $coordinator; |
|
66 | - $this->container = $container; |
|
67 | - $this->logger = $logger; |
|
68 | - $this->config = $config; |
|
69 | - $this->userSession = $userSession; |
|
70 | - } |
|
71 | - |
|
72 | - /** |
|
73 | - * Extract a list of URLs from a text |
|
74 | - * |
|
75 | - * @param string $text |
|
76 | - * @return string[] |
|
77 | - */ |
|
78 | - public function extractReferences(string $text): array { |
|
79 | - preg_match_all(IURLGenerator::URL_REGEX, $text, $matches); |
|
80 | - $references = $matches[0] ?? []; |
|
81 | - return array_map(function ($reference) { |
|
82 | - return trim($reference); |
|
83 | - }, $references); |
|
84 | - } |
|
85 | - |
|
86 | - /** |
|
87 | - * Try to get a cached reference object from a reference string |
|
88 | - * |
|
89 | - * @param string $referenceId |
|
90 | - * @return IReference|null |
|
91 | - */ |
|
92 | - public function getReferenceFromCache(string $referenceId): ?IReference { |
|
93 | - $matchedProvider = $this->getMatchedProvider($referenceId); |
|
94 | - |
|
95 | - if ($matchedProvider === null) { |
|
96 | - return null; |
|
97 | - } |
|
98 | - |
|
99 | - $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId); |
|
100 | - return $this->getReferenceByCacheKey($cacheKey); |
|
101 | - } |
|
102 | - |
|
103 | - /** |
|
104 | - * Try to get a cached reference object from a full cache key |
|
105 | - * |
|
106 | - * @param string $cacheKey |
|
107 | - * @return IReference|null |
|
108 | - */ |
|
109 | - public function getReferenceByCacheKey(string $cacheKey): ?IReference { |
|
110 | - $cached = $this->cache->get($cacheKey); |
|
111 | - if ($cached) { |
|
112 | - return Reference::fromCache($cached); |
|
113 | - } |
|
114 | - |
|
115 | - return null; |
|
116 | - } |
|
117 | - |
|
118 | - /** |
|
119 | - * Get a reference object from a reference string with a matching provider |
|
120 | - * Use a cached reference if possible |
|
121 | - * |
|
122 | - * @param string $referenceId |
|
123 | - * @return IReference|null |
|
124 | - */ |
|
125 | - public function resolveReference(string $referenceId): ?IReference { |
|
126 | - $matchedProvider = $this->getMatchedProvider($referenceId); |
|
127 | - |
|
128 | - if ($matchedProvider === null) { |
|
129 | - return null; |
|
130 | - } |
|
131 | - |
|
132 | - $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId); |
|
133 | - $cached = $this->cache->get($cacheKey); |
|
134 | - if ($cached) { |
|
135 | - return Reference::fromCache($cached); |
|
136 | - } |
|
137 | - |
|
138 | - $reference = $matchedProvider->resolveReference($referenceId); |
|
139 | - if ($reference) { |
|
140 | - $this->cache->set($cacheKey, Reference::toCache($reference), self::CACHE_TTL); |
|
141 | - return $reference; |
|
142 | - } |
|
143 | - |
|
144 | - return null; |
|
145 | - } |
|
146 | - |
|
147 | - /** |
|
148 | - * Try to match a reference string with all the registered providers |
|
149 | - * Fallback to the link reference provider (using OpenGraph) |
|
150 | - * |
|
151 | - * @param string $referenceId |
|
152 | - * @return IReferenceProvider|null the first matching provider |
|
153 | - */ |
|
154 | - private function getMatchedProvider(string $referenceId): ?IReferenceProvider { |
|
155 | - $matchedProvider = null; |
|
156 | - foreach ($this->getProviders() as $provider) { |
|
157 | - $matchedProvider = $provider->matchReference($referenceId) ? $provider : null; |
|
158 | - if ($matchedProvider !== null) { |
|
159 | - break; |
|
160 | - } |
|
161 | - } |
|
162 | - |
|
163 | - if ($matchedProvider === null && $this->linkReferenceProvider->matchReference($referenceId)) { |
|
164 | - $matchedProvider = $this->linkReferenceProvider; |
|
165 | - } |
|
166 | - |
|
167 | - return $matchedProvider; |
|
168 | - } |
|
169 | - |
|
170 | - /** |
|
171 | - * Get a hashed full cache key from a key and prefix given by a provider |
|
172 | - * |
|
173 | - * @param IReferenceProvider $provider |
|
174 | - * @param string $referenceId |
|
175 | - * @return string |
|
176 | - */ |
|
177 | - private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string { |
|
178 | - $cacheKey = $provider->getCacheKey($referenceId); |
|
179 | - return md5($provider->getCachePrefix($referenceId)) . ( |
|
180 | - $cacheKey !== null ? ('-' . md5($cacheKey)) : '' |
|
181 | - ); |
|
182 | - } |
|
183 | - |
|
184 | - /** |
|
185 | - * Remove a specific cache entry from its key+prefix |
|
186 | - * |
|
187 | - * @param string $cachePrefix |
|
188 | - * @param string|null $cacheKey |
|
189 | - * @return void |
|
190 | - */ |
|
191 | - public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void { |
|
192 | - if ($cacheKey === null) { |
|
193 | - $this->cache->clear(md5($cachePrefix)); |
|
194 | - return; |
|
195 | - } |
|
196 | - |
|
197 | - $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey)); |
|
198 | - } |
|
199 | - |
|
200 | - /** |
|
201 | - * @return IReferenceProvider[] |
|
202 | - */ |
|
203 | - public function getProviders(): array { |
|
204 | - if ($this->providers === null) { |
|
205 | - $context = $this->coordinator->getRegistrationContext(); |
|
206 | - if ($context === null) { |
|
207 | - return []; |
|
208 | - } |
|
209 | - |
|
210 | - $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider { |
|
211 | - try { |
|
212 | - /** @var IReferenceProvider $provider */ |
|
213 | - $provider = $this->container->get($registration->getService()); |
|
214 | - } catch (Throwable $e) { |
|
215 | - $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [ |
|
216 | - 'exception' => $e, |
|
217 | - ]); |
|
218 | - return null; |
|
219 | - } |
|
220 | - |
|
221 | - return $provider; |
|
222 | - }, $context->getReferenceProviders())); |
|
223 | - |
|
224 | - $this->providers[] = $this->container->get(FileReferenceProvider::class); |
|
225 | - } |
|
226 | - |
|
227 | - return $this->providers; |
|
228 | - } |
|
229 | - |
|
230 | - /** |
|
231 | - * @inheritDoc |
|
232 | - */ |
|
233 | - public function getDiscoverableProviders(): array { |
|
234 | - // preserve 0 based index to avoid returning an object in data responses |
|
235 | - return array_values( |
|
236 | - array_filter($this->getProviders(), static function (IReferenceProvider $provider) { |
|
237 | - return $provider instanceof IDiscoverableReferenceProvider; |
|
238 | - }) |
|
239 | - ); |
|
240 | - } |
|
241 | - |
|
242 | - /** |
|
243 | - * @inheritDoc |
|
244 | - */ |
|
245 | - public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool { |
|
246 | - $providers = $this->getDiscoverableProviders(); |
|
247 | - $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) { |
|
248 | - return $provider->getId() === $providerId; |
|
249 | - }); |
|
250 | - if (!empty($matchingProviders)) { |
|
251 | - if ($timestamp === null) { |
|
252 | - $timestamp = time(); |
|
253 | - } |
|
254 | - |
|
255 | - $configKey = 'provider-last-use_' . $providerId; |
|
256 | - $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp); |
|
257 | - return true; |
|
258 | - } |
|
259 | - return false; |
|
260 | - } |
|
261 | - |
|
262 | - /** |
|
263 | - * @inheritDoc |
|
264 | - */ |
|
265 | - public function getUserProviderTimestamps(): array { |
|
266 | - $user = $this->userSession->getUser(); |
|
267 | - if ($user === null) { |
|
268 | - return []; |
|
269 | - } |
|
270 | - $userId = $user->getUID(); |
|
271 | - $keys = $this->config->getUserKeys($userId, 'references'); |
|
272 | - $prefix = 'provider-last-use_'; |
|
273 | - $keys = array_filter($keys, static function (string $key) use ($prefix) { |
|
274 | - return str_starts_with($key, $prefix); |
|
275 | - }); |
|
276 | - $timestamps = []; |
|
277 | - foreach ($keys as $key) { |
|
278 | - $providerId = substr($key, strlen($prefix)); |
|
279 | - $timestamp = (int) $this->config->getUserValue($userId, 'references', $key); |
|
280 | - $timestamps[$providerId] = $timestamp; |
|
281 | - } |
|
282 | - return $timestamps; |
|
283 | - } |
|
44 | + public const CACHE_TTL = 3600; |
|
45 | + |
|
46 | + /** @var IReferenceProvider[]|null */ |
|
47 | + private ?array $providers = null; |
|
48 | + private ICache $cache; |
|
49 | + private Coordinator $coordinator; |
|
50 | + private ContainerInterface $container; |
|
51 | + private LinkReferenceProvider $linkReferenceProvider; |
|
52 | + private LoggerInterface $logger; |
|
53 | + private IConfig $config; |
|
54 | + private IUserSession $userSession; |
|
55 | + |
|
56 | + public function __construct(LinkReferenceProvider $linkReferenceProvider, |
|
57 | + ICacheFactory $cacheFactory, |
|
58 | + Coordinator $coordinator, |
|
59 | + ContainerInterface $container, |
|
60 | + LoggerInterface $logger, |
|
61 | + IConfig $config, |
|
62 | + IUserSession $userSession) { |
|
63 | + $this->linkReferenceProvider = $linkReferenceProvider; |
|
64 | + $this->cache = $cacheFactory->createDistributed('reference'); |
|
65 | + $this->coordinator = $coordinator; |
|
66 | + $this->container = $container; |
|
67 | + $this->logger = $logger; |
|
68 | + $this->config = $config; |
|
69 | + $this->userSession = $userSession; |
|
70 | + } |
|
71 | + |
|
72 | + /** |
|
73 | + * Extract a list of URLs from a text |
|
74 | + * |
|
75 | + * @param string $text |
|
76 | + * @return string[] |
|
77 | + */ |
|
78 | + public function extractReferences(string $text): array { |
|
79 | + preg_match_all(IURLGenerator::URL_REGEX, $text, $matches); |
|
80 | + $references = $matches[0] ?? []; |
|
81 | + return array_map(function ($reference) { |
|
82 | + return trim($reference); |
|
83 | + }, $references); |
|
84 | + } |
|
85 | + |
|
86 | + /** |
|
87 | + * Try to get a cached reference object from a reference string |
|
88 | + * |
|
89 | + * @param string $referenceId |
|
90 | + * @return IReference|null |
|
91 | + */ |
|
92 | + public function getReferenceFromCache(string $referenceId): ?IReference { |
|
93 | + $matchedProvider = $this->getMatchedProvider($referenceId); |
|
94 | + |
|
95 | + if ($matchedProvider === null) { |
|
96 | + return null; |
|
97 | + } |
|
98 | + |
|
99 | + $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId); |
|
100 | + return $this->getReferenceByCacheKey($cacheKey); |
|
101 | + } |
|
102 | + |
|
103 | + /** |
|
104 | + * Try to get a cached reference object from a full cache key |
|
105 | + * |
|
106 | + * @param string $cacheKey |
|
107 | + * @return IReference|null |
|
108 | + */ |
|
109 | + public function getReferenceByCacheKey(string $cacheKey): ?IReference { |
|
110 | + $cached = $this->cache->get($cacheKey); |
|
111 | + if ($cached) { |
|
112 | + return Reference::fromCache($cached); |
|
113 | + } |
|
114 | + |
|
115 | + return null; |
|
116 | + } |
|
117 | + |
|
118 | + /** |
|
119 | + * Get a reference object from a reference string with a matching provider |
|
120 | + * Use a cached reference if possible |
|
121 | + * |
|
122 | + * @param string $referenceId |
|
123 | + * @return IReference|null |
|
124 | + */ |
|
125 | + public function resolveReference(string $referenceId): ?IReference { |
|
126 | + $matchedProvider = $this->getMatchedProvider($referenceId); |
|
127 | + |
|
128 | + if ($matchedProvider === null) { |
|
129 | + return null; |
|
130 | + } |
|
131 | + |
|
132 | + $cacheKey = $this->getFullCacheKey($matchedProvider, $referenceId); |
|
133 | + $cached = $this->cache->get($cacheKey); |
|
134 | + if ($cached) { |
|
135 | + return Reference::fromCache($cached); |
|
136 | + } |
|
137 | + |
|
138 | + $reference = $matchedProvider->resolveReference($referenceId); |
|
139 | + if ($reference) { |
|
140 | + $this->cache->set($cacheKey, Reference::toCache($reference), self::CACHE_TTL); |
|
141 | + return $reference; |
|
142 | + } |
|
143 | + |
|
144 | + return null; |
|
145 | + } |
|
146 | + |
|
147 | + /** |
|
148 | + * Try to match a reference string with all the registered providers |
|
149 | + * Fallback to the link reference provider (using OpenGraph) |
|
150 | + * |
|
151 | + * @param string $referenceId |
|
152 | + * @return IReferenceProvider|null the first matching provider |
|
153 | + */ |
|
154 | + private function getMatchedProvider(string $referenceId): ?IReferenceProvider { |
|
155 | + $matchedProvider = null; |
|
156 | + foreach ($this->getProviders() as $provider) { |
|
157 | + $matchedProvider = $provider->matchReference($referenceId) ? $provider : null; |
|
158 | + if ($matchedProvider !== null) { |
|
159 | + break; |
|
160 | + } |
|
161 | + } |
|
162 | + |
|
163 | + if ($matchedProvider === null && $this->linkReferenceProvider->matchReference($referenceId)) { |
|
164 | + $matchedProvider = $this->linkReferenceProvider; |
|
165 | + } |
|
166 | + |
|
167 | + return $matchedProvider; |
|
168 | + } |
|
169 | + |
|
170 | + /** |
|
171 | + * Get a hashed full cache key from a key and prefix given by a provider |
|
172 | + * |
|
173 | + * @param IReferenceProvider $provider |
|
174 | + * @param string $referenceId |
|
175 | + * @return string |
|
176 | + */ |
|
177 | + private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string { |
|
178 | + $cacheKey = $provider->getCacheKey($referenceId); |
|
179 | + return md5($provider->getCachePrefix($referenceId)) . ( |
|
180 | + $cacheKey !== null ? ('-' . md5($cacheKey)) : '' |
|
181 | + ); |
|
182 | + } |
|
183 | + |
|
184 | + /** |
|
185 | + * Remove a specific cache entry from its key+prefix |
|
186 | + * |
|
187 | + * @param string $cachePrefix |
|
188 | + * @param string|null $cacheKey |
|
189 | + * @return void |
|
190 | + */ |
|
191 | + public function invalidateCache(string $cachePrefix, ?string $cacheKey = null): void { |
|
192 | + if ($cacheKey === null) { |
|
193 | + $this->cache->clear(md5($cachePrefix)); |
|
194 | + return; |
|
195 | + } |
|
196 | + |
|
197 | + $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey)); |
|
198 | + } |
|
199 | + |
|
200 | + /** |
|
201 | + * @return IReferenceProvider[] |
|
202 | + */ |
|
203 | + public function getProviders(): array { |
|
204 | + if ($this->providers === null) { |
|
205 | + $context = $this->coordinator->getRegistrationContext(); |
|
206 | + if ($context === null) { |
|
207 | + return []; |
|
208 | + } |
|
209 | + |
|
210 | + $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider { |
|
211 | + try { |
|
212 | + /** @var IReferenceProvider $provider */ |
|
213 | + $provider = $this->container->get($registration->getService()); |
|
214 | + } catch (Throwable $e) { |
|
215 | + $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [ |
|
216 | + 'exception' => $e, |
|
217 | + ]); |
|
218 | + return null; |
|
219 | + } |
|
220 | + |
|
221 | + return $provider; |
|
222 | + }, $context->getReferenceProviders())); |
|
223 | + |
|
224 | + $this->providers[] = $this->container->get(FileReferenceProvider::class); |
|
225 | + } |
|
226 | + |
|
227 | + return $this->providers; |
|
228 | + } |
|
229 | + |
|
230 | + /** |
|
231 | + * @inheritDoc |
|
232 | + */ |
|
233 | + public function getDiscoverableProviders(): array { |
|
234 | + // preserve 0 based index to avoid returning an object in data responses |
|
235 | + return array_values( |
|
236 | + array_filter($this->getProviders(), static function (IReferenceProvider $provider) { |
|
237 | + return $provider instanceof IDiscoverableReferenceProvider; |
|
238 | + }) |
|
239 | + ); |
|
240 | + } |
|
241 | + |
|
242 | + /** |
|
243 | + * @inheritDoc |
|
244 | + */ |
|
245 | + public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool { |
|
246 | + $providers = $this->getDiscoverableProviders(); |
|
247 | + $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) { |
|
248 | + return $provider->getId() === $providerId; |
|
249 | + }); |
|
250 | + if (!empty($matchingProviders)) { |
|
251 | + if ($timestamp === null) { |
|
252 | + $timestamp = time(); |
|
253 | + } |
|
254 | + |
|
255 | + $configKey = 'provider-last-use_' . $providerId; |
|
256 | + $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp); |
|
257 | + return true; |
|
258 | + } |
|
259 | + return false; |
|
260 | + } |
|
261 | + |
|
262 | + /** |
|
263 | + * @inheritDoc |
|
264 | + */ |
|
265 | + public function getUserProviderTimestamps(): array { |
|
266 | + $user = $this->userSession->getUser(); |
|
267 | + if ($user === null) { |
|
268 | + return []; |
|
269 | + } |
|
270 | + $userId = $user->getUID(); |
|
271 | + $keys = $this->config->getUserKeys($userId, 'references'); |
|
272 | + $prefix = 'provider-last-use_'; |
|
273 | + $keys = array_filter($keys, static function (string $key) use ($prefix) { |
|
274 | + return str_starts_with($key, $prefix); |
|
275 | + }); |
|
276 | + $timestamps = []; |
|
277 | + foreach ($keys as $key) { |
|
278 | + $providerId = substr($key, strlen($prefix)); |
|
279 | + $timestamp = (int) $this->config->getUserValue($userId, 'references', $key); |
|
280 | + $timestamps[$providerId] = $timestamp; |
|
281 | + } |
|
282 | + return $timestamps; |
|
283 | + } |
|
284 | 284 | } |
@@ -78,7 +78,7 @@ discard block |
||
78 | 78 | public function extractReferences(string $text): array { |
79 | 79 | preg_match_all(IURLGenerator::URL_REGEX, $text, $matches); |
80 | 80 | $references = $matches[0] ?? []; |
81 | - return array_map(function ($reference) { |
|
81 | + return array_map(function($reference) { |
|
82 | 82 | return trim($reference); |
83 | 83 | }, $references); |
84 | 84 | } |
@@ -176,8 +176,8 @@ discard block |
||
176 | 176 | */ |
177 | 177 | private function getFullCacheKey(IReferenceProvider $provider, string $referenceId): string { |
178 | 178 | $cacheKey = $provider->getCacheKey($referenceId); |
179 | - return md5($provider->getCachePrefix($referenceId)) . ( |
|
180 | - $cacheKey !== null ? ('-' . md5($cacheKey)) : '' |
|
179 | + return md5($provider->getCachePrefix($referenceId)).( |
|
180 | + $cacheKey !== null ? ('-'.md5($cacheKey)) : '' |
|
181 | 181 | ); |
182 | 182 | } |
183 | 183 | |
@@ -194,7 +194,7 @@ discard block |
||
194 | 194 | return; |
195 | 195 | } |
196 | 196 | |
197 | - $this->cache->remove(md5($cachePrefix) . '-' . md5($cacheKey)); |
|
197 | + $this->cache->remove(md5($cachePrefix).'-'.md5($cacheKey)); |
|
198 | 198 | } |
199 | 199 | |
200 | 200 | /** |
@@ -207,12 +207,12 @@ discard block |
||
207 | 207 | return []; |
208 | 208 | } |
209 | 209 | |
210 | - $this->providers = array_filter(array_map(function ($registration): ?IReferenceProvider { |
|
210 | + $this->providers = array_filter(array_map(function($registration): ?IReferenceProvider { |
|
211 | 211 | try { |
212 | 212 | /** @var IReferenceProvider $provider */ |
213 | 213 | $provider = $this->container->get($registration->getService()); |
214 | 214 | } catch (Throwable $e) { |
215 | - $this->logger->error('Could not load reference provider ' . $registration->getService() . ': ' . $e->getMessage(), [ |
|
215 | + $this->logger->error('Could not load reference provider '.$registration->getService().': '.$e->getMessage(), [ |
|
216 | 216 | 'exception' => $e, |
217 | 217 | ]); |
218 | 218 | return null; |
@@ -233,7 +233,7 @@ discard block |
||
233 | 233 | public function getDiscoverableProviders(): array { |
234 | 234 | // preserve 0 based index to avoid returning an object in data responses |
235 | 235 | return array_values( |
236 | - array_filter($this->getProviders(), static function (IReferenceProvider $provider) { |
|
236 | + array_filter($this->getProviders(), static function(IReferenceProvider $provider) { |
|
237 | 237 | return $provider instanceof IDiscoverableReferenceProvider; |
238 | 238 | }) |
239 | 239 | ); |
@@ -244,7 +244,7 @@ discard block |
||
244 | 244 | */ |
245 | 245 | public function touchProvider(string $userId, string $providerId, ?int $timestamp = null): bool { |
246 | 246 | $providers = $this->getDiscoverableProviders(); |
247 | - $matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) { |
|
247 | + $matchingProviders = array_filter($providers, static function(IDiscoverableReferenceProvider $provider) use ($providerId) { |
|
248 | 248 | return $provider->getId() === $providerId; |
249 | 249 | }); |
250 | 250 | if (!empty($matchingProviders)) { |
@@ -252,7 +252,7 @@ discard block |
||
252 | 252 | $timestamp = time(); |
253 | 253 | } |
254 | 254 | |
255 | - $configKey = 'provider-last-use_' . $providerId; |
|
255 | + $configKey = 'provider-last-use_'.$providerId; |
|
256 | 256 | $this->config->setUserValue($userId, 'references', $configKey, (string) $timestamp); |
257 | 257 | return true; |
258 | 258 | } |
@@ -270,7 +270,7 @@ discard block |
||
270 | 270 | $userId = $user->getUID(); |
271 | 271 | $keys = $this->config->getUserKeys($userId, 'references'); |
272 | 272 | $prefix = 'provider-last-use_'; |
273 | - $keys = array_filter($keys, static function (string $key) use ($prefix) { |
|
273 | + $keys = array_filter($keys, static function(string $key) use ($prefix) { |
|
274 | 274 | return str_starts_with($key, $prefix); |
275 | 275 | }); |
276 | 276 | $timestamps = []; |
@@ -90,1068 +90,1068 @@ |
||
90 | 90 | * OC_autoload! |
91 | 91 | */ |
92 | 92 | class OC { |
93 | - /** |
|
94 | - * Associative array for autoloading. classname => filename |
|
95 | - */ |
|
96 | - public static array $CLASSPATH = []; |
|
97 | - /** |
|
98 | - * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
99 | - */ |
|
100 | - public static string $SERVERROOT = ''; |
|
101 | - /** |
|
102 | - * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
103 | - */ |
|
104 | - private static string $SUBURI = ''; |
|
105 | - /** |
|
106 | - * the Nextcloud root path for http requests (e.g. nextcloud/) |
|
107 | - */ |
|
108 | - public static string $WEBROOT = ''; |
|
109 | - /** |
|
110 | - * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
111 | - * web path in 'url' |
|
112 | - */ |
|
113 | - public static array $APPSROOTS = []; |
|
114 | - |
|
115 | - public static string $configDir; |
|
116 | - |
|
117 | - /** |
|
118 | - * requested app |
|
119 | - */ |
|
120 | - public static string $REQUESTEDAPP = ''; |
|
121 | - |
|
122 | - /** |
|
123 | - * check if Nextcloud runs in cli mode |
|
124 | - */ |
|
125 | - public static bool $CLI = false; |
|
126 | - |
|
127 | - public static \OC\Autoloader $loader; |
|
128 | - |
|
129 | - public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
130 | - |
|
131 | - public static \OC\Server $server; |
|
132 | - |
|
133 | - private static \OC\Config $config; |
|
134 | - |
|
135 | - /** |
|
136 | - * @throws \RuntimeException when the 3rdparty directory is missing or |
|
137 | - * the app path list is empty or contains an invalid path |
|
138 | - */ |
|
139 | - public static function initPaths(): void { |
|
140 | - if (defined('PHPUNIT_CONFIG_DIR')) { |
|
141 | - self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
142 | - } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
143 | - self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
144 | - } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
145 | - self::$configDir = rtrim($dir, '/') . '/'; |
|
146 | - } else { |
|
147 | - self::$configDir = OC::$SERVERROOT . '/config/'; |
|
148 | - } |
|
149 | - self::$config = new \OC\Config(self::$configDir); |
|
150 | - |
|
151 | - OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT))); |
|
152 | - /** |
|
153 | - * FIXME: The following lines are required because we can't yet instantiate |
|
154 | - * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
155 | - */ |
|
156 | - $params = [ |
|
157 | - 'server' => [ |
|
158 | - 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
159 | - 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
160 | - ], |
|
161 | - ]; |
|
162 | - $fakeRequest = new \OC\AppFramework\Http\Request( |
|
163 | - $params, |
|
164 | - new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
165 | - new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
166 | - ); |
|
167 | - $scriptName = $fakeRequest->getScriptName(); |
|
168 | - if (substr($scriptName, -1) == '/') { |
|
169 | - $scriptName .= 'index.php'; |
|
170 | - //make sure suburi follows the same rules as scriptName |
|
171 | - if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
172 | - if (substr(OC::$SUBURI, -1) != '/') { |
|
173 | - OC::$SUBURI = OC::$SUBURI . '/'; |
|
174 | - } |
|
175 | - OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
176 | - } |
|
177 | - } |
|
178 | - |
|
179 | - |
|
180 | - if (OC::$CLI) { |
|
181 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
182 | - } else { |
|
183 | - if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
184 | - OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
185 | - |
|
186 | - if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
187 | - OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
188 | - } |
|
189 | - } else { |
|
190 | - // The scriptName is not ending with OC::$SUBURI |
|
191 | - // This most likely means that we are calling from CLI. |
|
192 | - // However some cron jobs still need to generate |
|
193 | - // a web URL, so we use overwritewebroot as a fallback. |
|
194 | - OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
195 | - } |
|
196 | - |
|
197 | - // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
198 | - // slash which is required by URL generation. |
|
199 | - if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
200 | - substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
201 | - header('Location: '.\OC::$WEBROOT.'/'); |
|
202 | - exit(); |
|
203 | - } |
|
204 | - } |
|
205 | - |
|
206 | - // search the apps folder |
|
207 | - $config_paths = self::$config->getValue('apps_paths', []); |
|
208 | - if (!empty($config_paths)) { |
|
209 | - foreach ($config_paths as $paths) { |
|
210 | - if (isset($paths['url']) && isset($paths['path'])) { |
|
211 | - $paths['url'] = rtrim($paths['url'], '/'); |
|
212 | - $paths['path'] = rtrim($paths['path'], '/'); |
|
213 | - OC::$APPSROOTS[] = $paths; |
|
214 | - } |
|
215 | - } |
|
216 | - } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
217 | - OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
218 | - } |
|
219 | - |
|
220 | - if (empty(OC::$APPSROOTS)) { |
|
221 | - throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
222 | - . '. You can also configure the location in the config.php file.'); |
|
223 | - } |
|
224 | - $paths = []; |
|
225 | - foreach (OC::$APPSROOTS as $path) { |
|
226 | - $paths[] = $path['path']; |
|
227 | - if (!is_dir($path['path'])) { |
|
228 | - throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
229 | - . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
230 | - } |
|
231 | - } |
|
232 | - |
|
233 | - // set the right include path |
|
234 | - set_include_path( |
|
235 | - implode(PATH_SEPARATOR, $paths) |
|
236 | - ); |
|
237 | - } |
|
238 | - |
|
239 | - public static function checkConfig(): void { |
|
240 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
241 | - |
|
242 | - // Create config if it does not already exist |
|
243 | - $configFilePath = self::$configDir .'/config.php'; |
|
244 | - if (!file_exists($configFilePath)) { |
|
245 | - @touch($configFilePath); |
|
246 | - } |
|
247 | - |
|
248 | - // Check if config is writable |
|
249 | - $configFileWritable = is_writable($configFilePath); |
|
250 | - if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
251 | - || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
252 | - $urlGenerator = Server::get(IURLGenerator::class); |
|
253 | - |
|
254 | - if (self::$CLI) { |
|
255 | - echo $l->t('Cannot write into "config" directory!')."\n"; |
|
256 | - echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n"; |
|
257 | - echo "\n"; |
|
258 | - echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n"; |
|
259 | - echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n"; |
|
260 | - exit; |
|
261 | - } else { |
|
262 | - OC_Template::printErrorPage( |
|
263 | - $l->t('Cannot write into "config" directory!'), |
|
264 | - $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
265 | - . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
266 | - . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
267 | - 503 |
|
268 | - ); |
|
269 | - } |
|
270 | - } |
|
271 | - } |
|
272 | - |
|
273 | - public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
274 | - if (defined('OC_CONSOLE')) { |
|
275 | - return; |
|
276 | - } |
|
277 | - // Redirect to installer if not installed |
|
278 | - if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
279 | - if (OC::$CLI) { |
|
280 | - throw new Exception('Not installed'); |
|
281 | - } else { |
|
282 | - $url = OC::$WEBROOT . '/index.php'; |
|
283 | - header('Location: ' . $url); |
|
284 | - } |
|
285 | - exit(); |
|
286 | - } |
|
287 | - } |
|
288 | - |
|
289 | - public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
290 | - // Allow ajax update script to execute without being stopped |
|
291 | - if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
292 | - // send http status 503 |
|
293 | - http_response_code(503); |
|
294 | - header('X-Nextcloud-Maintenance-Mode: 1'); |
|
295 | - header('Retry-After: 120'); |
|
296 | - |
|
297 | - // render error page |
|
298 | - $template = new OC_Template('', 'update.user', 'guest'); |
|
299 | - \OCP\Util::addScript('core', 'maintenance'); |
|
300 | - \OCP\Util::addStyle('core', 'guest'); |
|
301 | - $template->printPage(); |
|
302 | - die(); |
|
303 | - } |
|
304 | - } |
|
305 | - |
|
306 | - /** |
|
307 | - * Prints the upgrade page |
|
308 | - */ |
|
309 | - private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
310 | - $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
311 | - $tooBig = false; |
|
312 | - if (!$disableWebUpdater) { |
|
313 | - $apps = Server::get(\OCP\App\IAppManager::class); |
|
314 | - if ($apps->isInstalled('user_ldap')) { |
|
315 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
316 | - |
|
317 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
318 | - ->from('ldap_user_mapping') |
|
319 | - ->executeQuery(); |
|
320 | - $row = $result->fetch(); |
|
321 | - $result->closeCursor(); |
|
322 | - |
|
323 | - $tooBig = ($row['user_count'] > 50); |
|
324 | - } |
|
325 | - if (!$tooBig && $apps->isInstalled('user_saml')) { |
|
326 | - $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
327 | - |
|
328 | - $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
329 | - ->from('user_saml_users') |
|
330 | - ->executeQuery(); |
|
331 | - $row = $result->fetch(); |
|
332 | - $result->closeCursor(); |
|
333 | - |
|
334 | - $tooBig = ($row['user_count'] > 50); |
|
335 | - } |
|
336 | - if (!$tooBig) { |
|
337 | - // count users |
|
338 | - $stats = Server::get(\OCP\IUserManager::class)->countUsers(); |
|
339 | - $totalUsers = array_sum($stats); |
|
340 | - $tooBig = ($totalUsers > 50); |
|
341 | - } |
|
342 | - } |
|
343 | - $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
344 | - $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
345 | - |
|
346 | - if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
347 | - // send http status 503 |
|
348 | - http_response_code(503); |
|
349 | - header('Retry-After: 120'); |
|
350 | - |
|
351 | - // render error page |
|
352 | - $template = new OC_Template('', 'update.use-cli', 'guest'); |
|
353 | - $template->assign('productName', 'nextcloud'); // for now |
|
354 | - $template->assign('version', OC_Util::getVersionString()); |
|
355 | - $template->assign('tooBig', $tooBig); |
|
356 | - |
|
357 | - $template->printPage(); |
|
358 | - die(); |
|
359 | - } |
|
360 | - |
|
361 | - // check whether this is a core update or apps update |
|
362 | - $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
363 | - $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
364 | - |
|
365 | - // if not a core upgrade, then it's apps upgrade |
|
366 | - $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
367 | - |
|
368 | - $oldTheme = $systemConfig->getValue('theme'); |
|
369 | - $systemConfig->setValue('theme', ''); |
|
370 | - \OCP\Util::addScript('core', 'common'); |
|
371 | - \OCP\Util::addScript('core', 'main'); |
|
372 | - \OCP\Util::addTranslations('core'); |
|
373 | - \OCP\Util::addScript('core', 'update'); |
|
374 | - |
|
375 | - /** @var \OC\App\AppManager $appManager */ |
|
376 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
377 | - |
|
378 | - $tmpl = new OC_Template('', 'update.admin', 'guest'); |
|
379 | - $tmpl->assign('version', OC_Util::getVersionString()); |
|
380 | - $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
381 | - |
|
382 | - // get third party apps |
|
383 | - $ocVersion = \OCP\Util::getVersion(); |
|
384 | - $ocVersion = implode('.', $ocVersion); |
|
385 | - $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
386 | - $incompatibleShippedApps = []; |
|
387 | - foreach ($incompatibleApps as $appInfo) { |
|
388 | - if ($appManager->isShipped($appInfo['id'])) { |
|
389 | - $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
390 | - } |
|
391 | - } |
|
392 | - |
|
393 | - if (!empty($incompatibleShippedApps)) { |
|
394 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
395 | - $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]); |
|
396 | - throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint); |
|
397 | - } |
|
398 | - |
|
399 | - $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
400 | - $tmpl->assign('incompatibleAppsList', $incompatibleApps); |
|
401 | - try { |
|
402 | - $defaults = new \OC_Defaults(); |
|
403 | - $tmpl->assign('productName', $defaults->getName()); |
|
404 | - } catch (Throwable $error) { |
|
405 | - $tmpl->assign('productName', 'Nextcloud'); |
|
406 | - } |
|
407 | - $tmpl->assign('oldTheme', $oldTheme); |
|
408 | - $tmpl->printPage(); |
|
409 | - } |
|
410 | - |
|
411 | - public static function initSession(): void { |
|
412 | - $request = Server::get(IRequest::class); |
|
413 | - $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
414 | - if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
415 | - setcookie('cookie_test', 'test', time() + 3600); |
|
416 | - // Do not initialize the session if a request is authenticated directly |
|
417 | - // unless there is a session cookie already sent along |
|
418 | - return; |
|
419 | - } |
|
420 | - |
|
421 | - if ($request->getServerProtocol() === 'https') { |
|
422 | - ini_set('session.cookie_secure', 'true'); |
|
423 | - } |
|
424 | - |
|
425 | - // prevents javascript from accessing php session cookies |
|
426 | - ini_set('session.cookie_httponly', 'true'); |
|
427 | - |
|
428 | - // set the cookie path to the Nextcloud directory |
|
429 | - $cookie_path = OC::$WEBROOT ? : '/'; |
|
430 | - ini_set('session.cookie_path', $cookie_path); |
|
431 | - |
|
432 | - // Let the session name be changed in the initSession Hook |
|
433 | - $sessionName = OC_Util::getInstanceId(); |
|
434 | - |
|
435 | - try { |
|
436 | - // set the session name to the instance id - which is unique |
|
437 | - $session = new \OC\Session\Internal($sessionName); |
|
438 | - |
|
439 | - $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
440 | - $session = $cryptoWrapper->wrapSession($session); |
|
441 | - self::$server->setSession($session); |
|
442 | - |
|
443 | - // if session can't be started break with http 500 error |
|
444 | - } catch (Exception $e) { |
|
445 | - Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
446 | - //show the user a detailed error page |
|
447 | - OC_Template::printExceptionErrorPage($e, 500); |
|
448 | - die(); |
|
449 | - } |
|
450 | - |
|
451 | - //try to set the session lifetime |
|
452 | - $sessionLifeTime = self::getSessionLifeTime(); |
|
453 | - @ini_set('gc_maxlifetime', (string)$sessionLifeTime); |
|
454 | - |
|
455 | - // session timeout |
|
456 | - if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
457 | - if (isset($_COOKIE[session_name()])) { |
|
458 | - setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
459 | - } |
|
460 | - Server::get(IUserSession::class)->logout(); |
|
461 | - } |
|
462 | - |
|
463 | - if (!self::hasSessionRelaxedExpiry()) { |
|
464 | - $session->set('LAST_ACTIVITY', time()); |
|
465 | - } |
|
466 | - $session->close(); |
|
467 | - } |
|
468 | - |
|
469 | - private static function getSessionLifeTime(): int { |
|
470 | - return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
471 | - } |
|
472 | - |
|
473 | - /** |
|
474 | - * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
475 | - */ |
|
476 | - public static function hasSessionRelaxedExpiry(): bool { |
|
477 | - return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
478 | - } |
|
479 | - |
|
480 | - /** |
|
481 | - * Try to set some values to the required Nextcloud default |
|
482 | - */ |
|
483 | - public static function setRequiredIniValues(): void { |
|
484 | - @ini_set('default_charset', 'UTF-8'); |
|
485 | - @ini_set('gd.jpeg_ignore_warning', '1'); |
|
486 | - } |
|
487 | - |
|
488 | - /** |
|
489 | - * Send the same site cookies |
|
490 | - */ |
|
491 | - private static function sendSameSiteCookies(): void { |
|
492 | - $cookieParams = session_get_cookie_params(); |
|
493 | - $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
494 | - $policies = [ |
|
495 | - 'lax', |
|
496 | - 'strict', |
|
497 | - ]; |
|
498 | - |
|
499 | - // Append __Host to the cookie if it meets the requirements |
|
500 | - $cookiePrefix = ''; |
|
501 | - if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
502 | - $cookiePrefix = '__Host-'; |
|
503 | - } |
|
504 | - |
|
505 | - foreach ($policies as $policy) { |
|
506 | - header( |
|
507 | - sprintf( |
|
508 | - 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
509 | - $cookiePrefix, |
|
510 | - $policy, |
|
511 | - $cookieParams['path'], |
|
512 | - $policy |
|
513 | - ), |
|
514 | - false |
|
515 | - ); |
|
516 | - } |
|
517 | - } |
|
518 | - |
|
519 | - /** |
|
520 | - * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
521 | - * be set in every request if cookies are sent to add a second level of |
|
522 | - * defense against CSRF. |
|
523 | - * |
|
524 | - * If the cookie is not sent this will set the cookie and reload the page. |
|
525 | - * We use an additional cookie since we want to protect logout CSRF and |
|
526 | - * also we can't directly interfere with PHP's session mechanism. |
|
527 | - */ |
|
528 | - private static function performSameSiteCookieProtection(\OCP\IConfig $config): void { |
|
529 | - $request = Server::get(IRequest::class); |
|
530 | - |
|
531 | - // Some user agents are notorious and don't really properly follow HTTP |
|
532 | - // specifications. For those, have an automated opt-out. Since the protection |
|
533 | - // for remote.php is applied in base.php as starting point we need to opt out |
|
534 | - // here. |
|
535 | - $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
536 | - |
|
537 | - // Fallback, if csrf.optout is unset |
|
538 | - if (!is_array($incompatibleUserAgents)) { |
|
539 | - $incompatibleUserAgents = [ |
|
540 | - // OS X Finder |
|
541 | - '/^WebDAVFS/', |
|
542 | - // Windows webdav drive |
|
543 | - '/^Microsoft-WebDAV-MiniRedir/', |
|
544 | - ]; |
|
545 | - } |
|
546 | - |
|
547 | - if ($request->isUserAgent($incompatibleUserAgents)) { |
|
548 | - return; |
|
549 | - } |
|
550 | - |
|
551 | - if (count($_COOKIE) > 0) { |
|
552 | - $requestUri = $request->getScriptName(); |
|
553 | - $processingScript = explode('/', $requestUri); |
|
554 | - $processingScript = $processingScript[count($processingScript) - 1]; |
|
555 | - |
|
556 | - // index.php routes are handled in the middleware |
|
557 | - if ($processingScript === 'index.php') { |
|
558 | - return; |
|
559 | - } |
|
560 | - |
|
561 | - // All other endpoints require the lax and the strict cookie |
|
562 | - if (!$request->passesStrictCookieCheck()) { |
|
563 | - self::sendSameSiteCookies(); |
|
564 | - // Debug mode gets access to the resources without strict cookie |
|
565 | - // due to the fact that the SabreDAV browser also lives there. |
|
566 | - if (!$config->getSystemValue('debug', false)) { |
|
567 | - http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); |
|
568 | - exit(); |
|
569 | - } |
|
570 | - } |
|
571 | - } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
572 | - self::sendSameSiteCookies(); |
|
573 | - } |
|
574 | - } |
|
575 | - |
|
576 | - public static function init(): void { |
|
577 | - // calculate the root directories |
|
578 | - OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); |
|
579 | - |
|
580 | - // register autoloader |
|
581 | - $loaderStart = microtime(true); |
|
582 | - require_once __DIR__ . '/autoloader.php'; |
|
583 | - self::$loader = new \OC\Autoloader([ |
|
584 | - OC::$SERVERROOT . '/lib/private/legacy', |
|
585 | - ]); |
|
586 | - if (defined('PHPUNIT_RUN')) { |
|
587 | - self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
588 | - } |
|
589 | - spl_autoload_register([self::$loader, 'load']); |
|
590 | - $loaderEnd = microtime(true); |
|
591 | - |
|
592 | - self::$CLI = (php_sapi_name() == 'cli'); |
|
593 | - |
|
594 | - // Add default composer PSR-4 autoloader |
|
595 | - self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
596 | - self::$composerAutoloader->setApcuPrefix('composer_autoload'); |
|
597 | - |
|
598 | - try { |
|
599 | - self::initPaths(); |
|
600 | - // setup 3rdparty autoloader |
|
601 | - $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; |
|
602 | - if (!file_exists($vendorAutoLoad)) { |
|
603 | - throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
604 | - } |
|
605 | - require_once $vendorAutoLoad; |
|
606 | - } catch (\RuntimeException $e) { |
|
607 | - if (!self::$CLI) { |
|
608 | - http_response_code(503); |
|
609 | - } |
|
610 | - // we can't use the template error page here, because this needs the |
|
611 | - // DI container which isn't available yet |
|
612 | - print($e->getMessage()); |
|
613 | - exit(); |
|
614 | - } |
|
615 | - |
|
616 | - // setup the basic server |
|
617 | - self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
618 | - self::$server->boot(); |
|
619 | - |
|
620 | - $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
621 | - $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
622 | - $eventLogger->start('boot', 'Initialize'); |
|
623 | - |
|
624 | - // Override php.ini and log everything if we're troubleshooting |
|
625 | - if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
626 | - error_reporting(E_ALL); |
|
627 | - } |
|
628 | - |
|
629 | - // Don't display errors and log them |
|
630 | - @ini_set('display_errors', '0'); |
|
631 | - @ini_set('log_errors', '1'); |
|
632 | - |
|
633 | - if (!date_default_timezone_set('UTC')) { |
|
634 | - throw new \RuntimeException('Could not set timezone to UTC'); |
|
635 | - } |
|
636 | - |
|
637 | - |
|
638 | - //try to configure php to enable big file uploads. |
|
639 | - //this doesn´t work always depending on the webserver and php configuration. |
|
640 | - //Let´s try to overwrite some defaults if they are smaller than 1 hour |
|
641 | - |
|
642 | - if (intval(@ini_get('max_execution_time') ?? 0) < 3600) { |
|
643 | - @ini_set('max_execution_time', strval(3600)); |
|
644 | - } |
|
645 | - |
|
646 | - if (intval(@ini_get('max_input_time') ?? 0) < 3600) { |
|
647 | - @ini_set('max_input_time', strval(3600)); |
|
648 | - } |
|
649 | - |
|
650 | - //try to set the maximum execution time to the largest time limit we have |
|
651 | - if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
652 | - @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
653 | - } |
|
654 | - |
|
655 | - self::setRequiredIniValues(); |
|
656 | - self::handleAuthHeaders(); |
|
657 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
658 | - self::registerAutoloaderCache($systemConfig); |
|
659 | - |
|
660 | - // initialize intl fallback if necessary |
|
661 | - OC_Util::isSetLocaleWorking(); |
|
662 | - |
|
663 | - $config = Server::get(\OCP\IConfig::class); |
|
664 | - if (!defined('PHPUNIT_RUN')) { |
|
665 | - $errorHandler = new OC\Log\ErrorHandler( |
|
666 | - \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
667 | - ); |
|
668 | - $exceptionHandler = [$errorHandler, 'onException']; |
|
669 | - if ($config->getSystemValue('debug', false)) { |
|
670 | - set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
671 | - if (\OC::$CLI) { |
|
672 | - $exceptionHandler = ['OC_Template', 'printExceptionErrorPage']; |
|
673 | - } |
|
674 | - } else { |
|
675 | - set_error_handler([$errorHandler, 'onError']); |
|
676 | - } |
|
677 | - register_shutdown_function([$errorHandler, 'onShutdown']); |
|
678 | - set_exception_handler($exceptionHandler); |
|
679 | - } |
|
680 | - |
|
681 | - /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
682 | - $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
683 | - $bootstrapCoordinator->runInitialRegistration(); |
|
684 | - |
|
685 | - $eventLogger->start('init_session', 'Initialize session'); |
|
686 | - OC_App::loadApps(['session']); |
|
687 | - if (!self::$CLI) { |
|
688 | - self::initSession(); |
|
689 | - } |
|
690 | - $eventLogger->end('init_session'); |
|
691 | - self::checkConfig(); |
|
692 | - self::checkInstalled($systemConfig); |
|
693 | - |
|
694 | - OC_Response::addSecurityHeaders(); |
|
695 | - |
|
696 | - self::performSameSiteCookieProtection($config); |
|
697 | - |
|
698 | - if (!defined('OC_CONSOLE')) { |
|
699 | - $errors = OC_Util::checkServer($systemConfig); |
|
700 | - if (count($errors) > 0) { |
|
701 | - if (!self::$CLI) { |
|
702 | - http_response_code(503); |
|
703 | - OC_Util::addStyle('guest'); |
|
704 | - try { |
|
705 | - OC_Template::printGuestPage('', 'error', ['errors' => $errors]); |
|
706 | - exit; |
|
707 | - } catch (\Exception $e) { |
|
708 | - // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
709 | - // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
710 | - } |
|
711 | - } |
|
712 | - |
|
713 | - // Convert l10n string into regular string for usage in database |
|
714 | - $staticErrors = []; |
|
715 | - foreach ($errors as $error) { |
|
716 | - echo $error['error'] . "\n"; |
|
717 | - echo $error['hint'] . "\n\n"; |
|
718 | - $staticErrors[] = [ |
|
719 | - 'error' => (string)$error['error'], |
|
720 | - 'hint' => (string)$error['hint'], |
|
721 | - ]; |
|
722 | - } |
|
723 | - |
|
724 | - try { |
|
725 | - $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
726 | - } catch (\Exception $e) { |
|
727 | - echo('Writing to database failed'); |
|
728 | - } |
|
729 | - exit(1); |
|
730 | - } elseif (self::$CLI && $config->getSystemValue('installed', false)) { |
|
731 | - $config->deleteAppValue('core', 'cronErrors'); |
|
732 | - } |
|
733 | - } |
|
734 | - |
|
735 | - // User and Groups |
|
736 | - if (!$systemConfig->getValue("installed", false)) { |
|
737 | - self::$server->getSession()->set('user_id', ''); |
|
738 | - } |
|
739 | - |
|
740 | - OC_User::useBackend(new \OC\User\Database()); |
|
741 | - Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
742 | - |
|
743 | - // Subscribe to the hook |
|
744 | - \OCP\Util::connectHook( |
|
745 | - '\OCA\Files_Sharing\API\Server2Server', |
|
746 | - 'preLoginNameUsedAsUserName', |
|
747 | - '\OC\User\Database', |
|
748 | - 'preLoginNameUsedAsUserName' |
|
749 | - ); |
|
750 | - |
|
751 | - //setup extra user backends |
|
752 | - if (!\OCP\Util::needUpgrade()) { |
|
753 | - OC_User::setupBackends(); |
|
754 | - } else { |
|
755 | - // Run upgrades in incognito mode |
|
756 | - OC_User::setIncognitoMode(true); |
|
757 | - } |
|
758 | - |
|
759 | - self::registerCleanupHooks($systemConfig); |
|
760 | - self::registerShareHooks($systemConfig); |
|
761 | - self::registerEncryptionWrapperAndHooks(); |
|
762 | - self::registerAccountHooks(); |
|
763 | - self::registerResourceCollectionHooks(); |
|
764 | - self::registerFileReferenceEventListener(); |
|
765 | - self::registerRenderReferenceEventListener(); |
|
766 | - self::registerAppRestrictionsHooks(); |
|
767 | - |
|
768 | - // Make sure that the application class is not loaded before the database is setup |
|
769 | - if ($systemConfig->getValue("installed", false)) { |
|
770 | - OC_App::loadApp('settings'); |
|
771 | - /* Build core application to make sure that listeners are registered */ |
|
772 | - Server::get(\OC\Core\Application::class); |
|
773 | - } |
|
774 | - |
|
775 | - //make sure temporary files are cleaned up |
|
776 | - $tmpManager = Server::get(\OCP\ITempManager::class); |
|
777 | - register_shutdown_function([$tmpManager, 'clean']); |
|
778 | - $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
779 | - register_shutdown_function([$lockProvider, 'releaseAll']); |
|
780 | - |
|
781 | - // Check whether the sample configuration has been copied |
|
782 | - if ($systemConfig->getValue('copied_sample_config', false)) { |
|
783 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
784 | - OC_Template::printErrorPage( |
|
785 | - $l->t('Sample configuration detected'), |
|
786 | - $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
787 | - 503 |
|
788 | - ); |
|
789 | - return; |
|
790 | - } |
|
791 | - |
|
792 | - $request = Server::get(IRequest::class); |
|
793 | - $host = $request->getInsecureServerHost(); |
|
794 | - /** |
|
795 | - * if the host passed in headers isn't trusted |
|
796 | - * FIXME: Should not be in here at all :see_no_evil: |
|
797 | - */ |
|
798 | - if (!OC::$CLI |
|
799 | - && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
800 | - && $config->getSystemValue('installed', false) |
|
801 | - ) { |
|
802 | - // Allow access to CSS resources |
|
803 | - $isScssRequest = false; |
|
804 | - if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
805 | - $isScssRequest = true; |
|
806 | - } |
|
807 | - |
|
808 | - if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
809 | - http_response_code(400); |
|
810 | - header('Content-Type: application/json'); |
|
811 | - echo '{"error": "Trusted domain error.", "code": 15}'; |
|
812 | - exit(); |
|
813 | - } |
|
814 | - |
|
815 | - if (!$isScssRequest) { |
|
816 | - http_response_code(400); |
|
817 | - Server::get(LoggerInterface::class)->info( |
|
818 | - 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
819 | - [ |
|
820 | - 'app' => 'core', |
|
821 | - 'remoteAddress' => $request->getRemoteAddress(), |
|
822 | - 'host' => $host, |
|
823 | - ] |
|
824 | - ); |
|
825 | - |
|
826 | - $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); |
|
827 | - $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
828 | - $tmpl->printPage(); |
|
829 | - |
|
830 | - exit(); |
|
831 | - } |
|
832 | - } |
|
833 | - $eventLogger->end('boot'); |
|
834 | - $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
835 | - $eventLogger->start('runtime', 'Runtime'); |
|
836 | - $eventLogger->start('request', 'Full request after boot'); |
|
837 | - register_shutdown_function(function () use ($eventLogger) { |
|
838 | - $eventLogger->end('request'); |
|
839 | - }); |
|
840 | - } |
|
841 | - |
|
842 | - /** |
|
843 | - * register hooks for the cleanup of cache and bruteforce protection |
|
844 | - */ |
|
845 | - public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
846 | - //don't try to do this before we are properly setup |
|
847 | - if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
848 | - // NOTE: This will be replaced to use OCP |
|
849 | - $userSession = Server::get(\OC\User\Session::class); |
|
850 | - $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
851 | - if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
852 | - // reset brute force delay for this IP address and username |
|
853 | - $uid = $userSession->getUser()->getUID(); |
|
854 | - $request = Server::get(IRequest::class); |
|
855 | - $throttler = Server::get(\OC\Security\Bruteforce\Throttler::class); |
|
856 | - $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
857 | - } |
|
858 | - |
|
859 | - try { |
|
860 | - $cache = new \OC\Cache\File(); |
|
861 | - $cache->gc(); |
|
862 | - } catch (\OC\ServerNotAvailableException $e) { |
|
863 | - // not a GC exception, pass it on |
|
864 | - throw $e; |
|
865 | - } catch (\OC\ForbiddenException $e) { |
|
866 | - // filesystem blocked for this request, ignore |
|
867 | - } catch (\Exception $e) { |
|
868 | - // a GC exception should not prevent users from using OC, |
|
869 | - // so log the exception |
|
870 | - Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
871 | - 'app' => 'core', |
|
872 | - 'exception' => $e, |
|
873 | - ]); |
|
874 | - } |
|
875 | - }); |
|
876 | - } |
|
877 | - } |
|
878 | - |
|
879 | - private static function registerEncryptionWrapperAndHooks(): void { |
|
880 | - $manager = Server::get(\OCP\Encryption\IManager::class); |
|
881 | - \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
882 | - |
|
883 | - $enabled = $manager->isEnabled(); |
|
884 | - if ($enabled) { |
|
885 | - \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
886 | - \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
887 | - \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
888 | - \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
889 | - } |
|
890 | - } |
|
891 | - |
|
892 | - private static function registerAccountHooks(): void { |
|
893 | - /** @var IEventDispatcher $dispatcher */ |
|
894 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
895 | - $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
896 | - } |
|
897 | - |
|
898 | - private static function registerAppRestrictionsHooks(): void { |
|
899 | - /** @var \OC\Group\Manager $groupManager */ |
|
900 | - $groupManager = Server::get(\OCP\IGroupManager::class); |
|
901 | - $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
902 | - $appManager = Server::get(\OCP\App\IAppManager::class); |
|
903 | - $apps = $appManager->getEnabledAppsForGroup($group); |
|
904 | - foreach ($apps as $appId) { |
|
905 | - $restrictions = $appManager->getAppRestriction($appId); |
|
906 | - if (empty($restrictions)) { |
|
907 | - continue; |
|
908 | - } |
|
909 | - $key = array_search($group->getGID(), $restrictions); |
|
910 | - unset($restrictions[$key]); |
|
911 | - $restrictions = array_values($restrictions); |
|
912 | - if (empty($restrictions)) { |
|
913 | - $appManager->disableApp($appId); |
|
914 | - } else { |
|
915 | - $appManager->enableAppForGroups($appId, $restrictions); |
|
916 | - } |
|
917 | - } |
|
918 | - }); |
|
919 | - } |
|
920 | - |
|
921 | - private static function registerResourceCollectionHooks(): void { |
|
922 | - \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class)); |
|
923 | - } |
|
924 | - |
|
925 | - private static function registerFileReferenceEventListener(): void { |
|
926 | - \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
927 | - } |
|
928 | - |
|
929 | - private static function registerRenderReferenceEventListener() { |
|
930 | - \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
931 | - } |
|
932 | - |
|
933 | - /** |
|
934 | - * register hooks for sharing |
|
935 | - */ |
|
936 | - public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
937 | - if ($systemConfig->getValue('installed')) { |
|
938 | - OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser'); |
|
939 | - OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup'); |
|
940 | - |
|
941 | - /** @var IEventDispatcher $dispatcher */ |
|
942 | - $dispatcher = Server::get(IEventDispatcher::class); |
|
943 | - $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class); |
|
944 | - } |
|
945 | - } |
|
946 | - |
|
947 | - protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void { |
|
948 | - // The class loader takes an optional low-latency cache, which MUST be |
|
949 | - // namespaced. The instanceid is used for namespacing, but might be |
|
950 | - // unavailable at this point. Furthermore, it might not be possible to |
|
951 | - // generate an instanceid via \OC_Util::getInstanceId() because the |
|
952 | - // config file may not be writable. As such, we only register a class |
|
953 | - // loader cache if instanceid is available without trying to create one. |
|
954 | - $instanceId = $systemConfig->getValue('instanceid', null); |
|
955 | - if ($instanceId) { |
|
956 | - try { |
|
957 | - $memcacheFactory = Server::get(\OCP\ICacheFactory::class); |
|
958 | - self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
959 | - } catch (\Exception $ex) { |
|
960 | - } |
|
961 | - } |
|
962 | - } |
|
963 | - |
|
964 | - /** |
|
965 | - * Handle the request |
|
966 | - */ |
|
967 | - public static function handleRequest(): void { |
|
968 | - Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
969 | - $systemConfig = Server::get(\OC\SystemConfig::class); |
|
970 | - |
|
971 | - // Check if Nextcloud is installed or in maintenance (update) mode |
|
972 | - if (!$systemConfig->getValue('installed', false)) { |
|
973 | - \OC::$server->getSession()->clear(); |
|
974 | - $setupHelper = new OC\Setup( |
|
975 | - $systemConfig, |
|
976 | - Server::get(\bantu\IniGetWrapper\IniGetWrapper::class), |
|
977 | - Server::get(\OCP\L10N\IFactory::class)->get('lib'), |
|
978 | - Server::get(\OCP\Defaults::class), |
|
979 | - Server::get(\Psr\Log\LoggerInterface::class), |
|
980 | - Server::get(\OCP\Security\ISecureRandom::class), |
|
981 | - Server::get(\OC\Installer::class) |
|
982 | - ); |
|
983 | - $controller = new OC\Core\Controller\SetupController($setupHelper); |
|
984 | - $controller->run($_POST); |
|
985 | - exit(); |
|
986 | - } |
|
987 | - |
|
988 | - $request = Server::get(IRequest::class); |
|
989 | - $requestPath = $request->getRawPathInfo(); |
|
990 | - if ($requestPath === '/heartbeat') { |
|
991 | - return; |
|
992 | - } |
|
993 | - if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
994 | - self::checkMaintenanceMode($systemConfig); |
|
995 | - |
|
996 | - if (\OCP\Util::needUpgrade()) { |
|
997 | - if (function_exists('opcache_reset')) { |
|
998 | - opcache_reset(); |
|
999 | - } |
|
1000 | - if (!((bool) $systemConfig->getValue('maintenance', false))) { |
|
1001 | - self::printUpgradePage($systemConfig); |
|
1002 | - exit(); |
|
1003 | - } |
|
1004 | - } |
|
1005 | - } |
|
1006 | - |
|
1007 | - // emergency app disabling |
|
1008 | - if ($requestPath === '/disableapp' |
|
1009 | - && $request->getMethod() === 'POST' |
|
1010 | - ) { |
|
1011 | - \OC_JSON::callCheck(); |
|
1012 | - \OC_JSON::checkAdminUser(); |
|
1013 | - $appIds = (array)$request->getParam('appid'); |
|
1014 | - foreach ($appIds as $appId) { |
|
1015 | - $appId = \OC_App::cleanAppId($appId); |
|
1016 | - Server::get(\OCP\App\IAppManager::class)->disableApp($appId); |
|
1017 | - } |
|
1018 | - \OC_JSON::success(); |
|
1019 | - exit(); |
|
1020 | - } |
|
1021 | - |
|
1022 | - // Always load authentication apps |
|
1023 | - OC_App::loadApps(['authentication']); |
|
1024 | - |
|
1025 | - // Load minimum set of apps |
|
1026 | - if (!\OCP\Util::needUpgrade() |
|
1027 | - && !((bool) $systemConfig->getValue('maintenance', false))) { |
|
1028 | - // For logged-in users: Load everything |
|
1029 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1030 | - OC_App::loadApps(); |
|
1031 | - } else { |
|
1032 | - // For guests: Load only filesystem and logging |
|
1033 | - OC_App::loadApps(['filesystem', 'logging']); |
|
1034 | - |
|
1035 | - // Don't try to login when a client is trying to get a OAuth token. |
|
1036 | - // OAuth needs to support basic auth too, so the login is not valid |
|
1037 | - // inside Nextcloud and the Login exception would ruin it. |
|
1038 | - if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1039 | - self::handleLogin($request); |
|
1040 | - } |
|
1041 | - } |
|
1042 | - } |
|
1043 | - |
|
1044 | - if (!self::$CLI) { |
|
1045 | - try { |
|
1046 | - if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) { |
|
1047 | - OC_App::loadApps(['filesystem', 'logging']); |
|
1048 | - OC_App::loadApps(); |
|
1049 | - } |
|
1050 | - Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1051 | - return; |
|
1052 | - } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1053 | - //header('HTTP/1.0 404 Not Found'); |
|
1054 | - } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1055 | - http_response_code(405); |
|
1056 | - return; |
|
1057 | - } |
|
1058 | - } |
|
1059 | - |
|
1060 | - // Handle WebDAV |
|
1061 | - if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1062 | - // not allowed any more to prevent people |
|
1063 | - // mounting this root directly. |
|
1064 | - // Users need to mount remote.php/webdav instead. |
|
1065 | - http_response_code(405); |
|
1066 | - return; |
|
1067 | - } |
|
1068 | - |
|
1069 | - // Handle requests for JSON or XML |
|
1070 | - $acceptHeader = $request->getHeader('Accept'); |
|
1071 | - if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1072 | - http_response_code(404); |
|
1073 | - return; |
|
1074 | - } |
|
1075 | - |
|
1076 | - // Handle resources that can't be found |
|
1077 | - // This prevents browsers from redirecting to the default page and then |
|
1078 | - // attempting to parse HTML as CSS and similar. |
|
1079 | - $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1080 | - if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1081 | - http_response_code(404); |
|
1082 | - return; |
|
1083 | - } |
|
1084 | - |
|
1085 | - // Redirect to the default app or login only as an entry point |
|
1086 | - if ($requestPath === '') { |
|
1087 | - // Someone is logged in |
|
1088 | - if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1089 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1090 | - } else { |
|
1091 | - // Not handled and not logged in |
|
1092 | - header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1093 | - } |
|
1094 | - return; |
|
1095 | - } |
|
1096 | - |
|
1097 | - try { |
|
1098 | - Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1099 | - } catch (\Exception $e) { |
|
1100 | - logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1101 | - $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1102 | - OC_Template::printErrorPage( |
|
1103 | - $l->t('404'), |
|
1104 | - $l->t('The page could not be found on the server.'), |
|
1105 | - 404 |
|
1106 | - ); |
|
1107 | - } |
|
1108 | - } |
|
1109 | - |
|
1110 | - /** |
|
1111 | - * Check login: apache auth, auth token, basic auth |
|
1112 | - */ |
|
1113 | - public static function handleLogin(OCP\IRequest $request): bool { |
|
1114 | - $userSession = Server::get(\OC\User\Session::class); |
|
1115 | - if (OC_User::handleApacheAuth()) { |
|
1116 | - return true; |
|
1117 | - } |
|
1118 | - if ($userSession->tryTokenLogin($request)) { |
|
1119 | - return true; |
|
1120 | - } |
|
1121 | - if (isset($_COOKIE['nc_username']) |
|
1122 | - && isset($_COOKIE['nc_token']) |
|
1123 | - && isset($_COOKIE['nc_session_id']) |
|
1124 | - && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1125 | - return true; |
|
1126 | - } |
|
1127 | - if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) { |
|
1128 | - return true; |
|
1129 | - } |
|
1130 | - return false; |
|
1131 | - } |
|
1132 | - |
|
1133 | - protected static function handleAuthHeaders(): void { |
|
1134 | - //copy http auth headers for apache+php-fcgid work around |
|
1135 | - if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1136 | - $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1137 | - } |
|
1138 | - |
|
1139 | - // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1140 | - $vars = [ |
|
1141 | - 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1142 | - 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1143 | - ]; |
|
1144 | - foreach ($vars as $var) { |
|
1145 | - if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1146 | - $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1147 | - if (count($credentials) === 2) { |
|
1148 | - $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1149 | - $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1150 | - break; |
|
1151 | - } |
|
1152 | - } |
|
1153 | - } |
|
1154 | - } |
|
93 | + /** |
|
94 | + * Associative array for autoloading. classname => filename |
|
95 | + */ |
|
96 | + public static array $CLASSPATH = []; |
|
97 | + /** |
|
98 | + * The installation path for Nextcloud on the server (e.g. /srv/http/nextcloud) |
|
99 | + */ |
|
100 | + public static string $SERVERROOT = ''; |
|
101 | + /** |
|
102 | + * the current request path relative to the Nextcloud root (e.g. files/index.php) |
|
103 | + */ |
|
104 | + private static string $SUBURI = ''; |
|
105 | + /** |
|
106 | + * the Nextcloud root path for http requests (e.g. nextcloud/) |
|
107 | + */ |
|
108 | + public static string $WEBROOT = ''; |
|
109 | + /** |
|
110 | + * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and |
|
111 | + * web path in 'url' |
|
112 | + */ |
|
113 | + public static array $APPSROOTS = []; |
|
114 | + |
|
115 | + public static string $configDir; |
|
116 | + |
|
117 | + /** |
|
118 | + * requested app |
|
119 | + */ |
|
120 | + public static string $REQUESTEDAPP = ''; |
|
121 | + |
|
122 | + /** |
|
123 | + * check if Nextcloud runs in cli mode |
|
124 | + */ |
|
125 | + public static bool $CLI = false; |
|
126 | + |
|
127 | + public static \OC\Autoloader $loader; |
|
128 | + |
|
129 | + public static \Composer\Autoload\ClassLoader $composerAutoloader; |
|
130 | + |
|
131 | + public static \OC\Server $server; |
|
132 | + |
|
133 | + private static \OC\Config $config; |
|
134 | + |
|
135 | + /** |
|
136 | + * @throws \RuntimeException when the 3rdparty directory is missing or |
|
137 | + * the app path list is empty or contains an invalid path |
|
138 | + */ |
|
139 | + public static function initPaths(): void { |
|
140 | + if (defined('PHPUNIT_CONFIG_DIR')) { |
|
141 | + self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/'; |
|
142 | + } elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) { |
|
143 | + self::$configDir = OC::$SERVERROOT . '/tests/config/'; |
|
144 | + } elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) { |
|
145 | + self::$configDir = rtrim($dir, '/') . '/'; |
|
146 | + } else { |
|
147 | + self::$configDir = OC::$SERVERROOT . '/config/'; |
|
148 | + } |
|
149 | + self::$config = new \OC\Config(self::$configDir); |
|
150 | + |
|
151 | + OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"] ?? ''), strlen(OC::$SERVERROOT))); |
|
152 | + /** |
|
153 | + * FIXME: The following lines are required because we can't yet instantiate |
|
154 | + * Server::get(\OCP\IRequest::class) since \OC::$server does not yet exist. |
|
155 | + */ |
|
156 | + $params = [ |
|
157 | + 'server' => [ |
|
158 | + 'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'] ?? null, |
|
159 | + 'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'] ?? null, |
|
160 | + ], |
|
161 | + ]; |
|
162 | + $fakeRequest = new \OC\AppFramework\Http\Request( |
|
163 | + $params, |
|
164 | + new \OC\AppFramework\Http\RequestId($_SERVER['UNIQUE_ID'] ?? '', new \OC\Security\SecureRandom()), |
|
165 | + new \OC\AllConfig(new \OC\SystemConfig(self::$config)) |
|
166 | + ); |
|
167 | + $scriptName = $fakeRequest->getScriptName(); |
|
168 | + if (substr($scriptName, -1) == '/') { |
|
169 | + $scriptName .= 'index.php'; |
|
170 | + //make sure suburi follows the same rules as scriptName |
|
171 | + if (substr(OC::$SUBURI, -9) != 'index.php') { |
|
172 | + if (substr(OC::$SUBURI, -1) != '/') { |
|
173 | + OC::$SUBURI = OC::$SUBURI . '/'; |
|
174 | + } |
|
175 | + OC::$SUBURI = OC::$SUBURI . 'index.php'; |
|
176 | + } |
|
177 | + } |
|
178 | + |
|
179 | + |
|
180 | + if (OC::$CLI) { |
|
181 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
182 | + } else { |
|
183 | + if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) { |
|
184 | + OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI)); |
|
185 | + |
|
186 | + if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') { |
|
187 | + OC::$WEBROOT = '/' . OC::$WEBROOT; |
|
188 | + } |
|
189 | + } else { |
|
190 | + // The scriptName is not ending with OC::$SUBURI |
|
191 | + // This most likely means that we are calling from CLI. |
|
192 | + // However some cron jobs still need to generate |
|
193 | + // a web URL, so we use overwritewebroot as a fallback. |
|
194 | + OC::$WEBROOT = self::$config->getValue('overwritewebroot', ''); |
|
195 | + } |
|
196 | + |
|
197 | + // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing |
|
198 | + // slash which is required by URL generation. |
|
199 | + if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT && |
|
200 | + substr($_SERVER['REQUEST_URI'], -1) !== '/') { |
|
201 | + header('Location: '.\OC::$WEBROOT.'/'); |
|
202 | + exit(); |
|
203 | + } |
|
204 | + } |
|
205 | + |
|
206 | + // search the apps folder |
|
207 | + $config_paths = self::$config->getValue('apps_paths', []); |
|
208 | + if (!empty($config_paths)) { |
|
209 | + foreach ($config_paths as $paths) { |
|
210 | + if (isset($paths['url']) && isset($paths['path'])) { |
|
211 | + $paths['url'] = rtrim($paths['url'], '/'); |
|
212 | + $paths['path'] = rtrim($paths['path'], '/'); |
|
213 | + OC::$APPSROOTS[] = $paths; |
|
214 | + } |
|
215 | + } |
|
216 | + } elseif (file_exists(OC::$SERVERROOT . '/apps')) { |
|
217 | + OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true]; |
|
218 | + } |
|
219 | + |
|
220 | + if (empty(OC::$APPSROOTS)) { |
|
221 | + throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder' |
|
222 | + . '. You can also configure the location in the config.php file.'); |
|
223 | + } |
|
224 | + $paths = []; |
|
225 | + foreach (OC::$APPSROOTS as $path) { |
|
226 | + $paths[] = $path['path']; |
|
227 | + if (!is_dir($path['path'])) { |
|
228 | + throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the' |
|
229 | + . ' Nextcloud folder. You can also configure the location in the config.php file.', $path['path'])); |
|
230 | + } |
|
231 | + } |
|
232 | + |
|
233 | + // set the right include path |
|
234 | + set_include_path( |
|
235 | + implode(PATH_SEPARATOR, $paths) |
|
236 | + ); |
|
237 | + } |
|
238 | + |
|
239 | + public static function checkConfig(): void { |
|
240 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
241 | + |
|
242 | + // Create config if it does not already exist |
|
243 | + $configFilePath = self::$configDir .'/config.php'; |
|
244 | + if (!file_exists($configFilePath)) { |
|
245 | + @touch($configFilePath); |
|
246 | + } |
|
247 | + |
|
248 | + // Check if config is writable |
|
249 | + $configFileWritable = is_writable($configFilePath); |
|
250 | + if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled() |
|
251 | + || !$configFileWritable && \OCP\Util::needUpgrade()) { |
|
252 | + $urlGenerator = Server::get(IURLGenerator::class); |
|
253 | + |
|
254 | + if (self::$CLI) { |
|
255 | + echo $l->t('Cannot write into "config" directory!')."\n"; |
|
256 | + echo $l->t('This can usually be fixed by giving the web server write access to the config directory.')."\n"; |
|
257 | + echo "\n"; |
|
258 | + echo $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.')."\n"; |
|
259 | + echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ])."\n"; |
|
260 | + exit; |
|
261 | + } else { |
|
262 | + OC_Template::printErrorPage( |
|
263 | + $l->t('Cannot write into "config" directory!'), |
|
264 | + $l->t('This can usually be fixed by giving the web server write access to the config directory.') . ' ' |
|
265 | + . $l->t('But, if you prefer to keep config.php file read only, set the option "config_is_read_only" to true in it.') . ' ' |
|
266 | + . $l->t('See %s', [ $urlGenerator->linkToDocs('admin-config') ]), |
|
267 | + 503 |
|
268 | + ); |
|
269 | + } |
|
270 | + } |
|
271 | + } |
|
272 | + |
|
273 | + public static function checkInstalled(\OC\SystemConfig $systemConfig): void { |
|
274 | + if (defined('OC_CONSOLE')) { |
|
275 | + return; |
|
276 | + } |
|
277 | + // Redirect to installer if not installed |
|
278 | + if (!$systemConfig->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') { |
|
279 | + if (OC::$CLI) { |
|
280 | + throw new Exception('Not installed'); |
|
281 | + } else { |
|
282 | + $url = OC::$WEBROOT . '/index.php'; |
|
283 | + header('Location: ' . $url); |
|
284 | + } |
|
285 | + exit(); |
|
286 | + } |
|
287 | + } |
|
288 | + |
|
289 | + public static function checkMaintenanceMode(\OC\SystemConfig $systemConfig): void { |
|
290 | + // Allow ajax update script to execute without being stopped |
|
291 | + if (((bool) $systemConfig->getValue('maintenance', false)) && OC::$SUBURI != '/core/ajax/update.php') { |
|
292 | + // send http status 503 |
|
293 | + http_response_code(503); |
|
294 | + header('X-Nextcloud-Maintenance-Mode: 1'); |
|
295 | + header('Retry-After: 120'); |
|
296 | + |
|
297 | + // render error page |
|
298 | + $template = new OC_Template('', 'update.user', 'guest'); |
|
299 | + \OCP\Util::addScript('core', 'maintenance'); |
|
300 | + \OCP\Util::addStyle('core', 'guest'); |
|
301 | + $template->printPage(); |
|
302 | + die(); |
|
303 | + } |
|
304 | + } |
|
305 | + |
|
306 | + /** |
|
307 | + * Prints the upgrade page |
|
308 | + */ |
|
309 | + private static function printUpgradePage(\OC\SystemConfig $systemConfig): void { |
|
310 | + $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false); |
|
311 | + $tooBig = false; |
|
312 | + if (!$disableWebUpdater) { |
|
313 | + $apps = Server::get(\OCP\App\IAppManager::class); |
|
314 | + if ($apps->isInstalled('user_ldap')) { |
|
315 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
316 | + |
|
317 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
318 | + ->from('ldap_user_mapping') |
|
319 | + ->executeQuery(); |
|
320 | + $row = $result->fetch(); |
|
321 | + $result->closeCursor(); |
|
322 | + |
|
323 | + $tooBig = ($row['user_count'] > 50); |
|
324 | + } |
|
325 | + if (!$tooBig && $apps->isInstalled('user_saml')) { |
|
326 | + $qb = Server::get(\OCP\IDBConnection::class)->getQueryBuilder(); |
|
327 | + |
|
328 | + $result = $qb->select($qb->func()->count('*', 'user_count')) |
|
329 | + ->from('user_saml_users') |
|
330 | + ->executeQuery(); |
|
331 | + $row = $result->fetch(); |
|
332 | + $result->closeCursor(); |
|
333 | + |
|
334 | + $tooBig = ($row['user_count'] > 50); |
|
335 | + } |
|
336 | + if (!$tooBig) { |
|
337 | + // count users |
|
338 | + $stats = Server::get(\OCP\IUserManager::class)->countUsers(); |
|
339 | + $totalUsers = array_sum($stats); |
|
340 | + $tooBig = ($totalUsers > 50); |
|
341 | + } |
|
342 | + } |
|
343 | + $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) && |
|
344 | + $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis'; |
|
345 | + |
|
346 | + if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) { |
|
347 | + // send http status 503 |
|
348 | + http_response_code(503); |
|
349 | + header('Retry-After: 120'); |
|
350 | + |
|
351 | + // render error page |
|
352 | + $template = new OC_Template('', 'update.use-cli', 'guest'); |
|
353 | + $template->assign('productName', 'nextcloud'); // for now |
|
354 | + $template->assign('version', OC_Util::getVersionString()); |
|
355 | + $template->assign('tooBig', $tooBig); |
|
356 | + |
|
357 | + $template->printPage(); |
|
358 | + die(); |
|
359 | + } |
|
360 | + |
|
361 | + // check whether this is a core update or apps update |
|
362 | + $installedVersion = $systemConfig->getValue('version', '0.0.0'); |
|
363 | + $currentVersion = implode('.', \OCP\Util::getVersion()); |
|
364 | + |
|
365 | + // if not a core upgrade, then it's apps upgrade |
|
366 | + $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '='); |
|
367 | + |
|
368 | + $oldTheme = $systemConfig->getValue('theme'); |
|
369 | + $systemConfig->setValue('theme', ''); |
|
370 | + \OCP\Util::addScript('core', 'common'); |
|
371 | + \OCP\Util::addScript('core', 'main'); |
|
372 | + \OCP\Util::addTranslations('core'); |
|
373 | + \OCP\Util::addScript('core', 'update'); |
|
374 | + |
|
375 | + /** @var \OC\App\AppManager $appManager */ |
|
376 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
377 | + |
|
378 | + $tmpl = new OC_Template('', 'update.admin', 'guest'); |
|
379 | + $tmpl->assign('version', OC_Util::getVersionString()); |
|
380 | + $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade); |
|
381 | + |
|
382 | + // get third party apps |
|
383 | + $ocVersion = \OCP\Util::getVersion(); |
|
384 | + $ocVersion = implode('.', $ocVersion); |
|
385 | + $incompatibleApps = $appManager->getIncompatibleApps($ocVersion); |
|
386 | + $incompatibleShippedApps = []; |
|
387 | + foreach ($incompatibleApps as $appInfo) { |
|
388 | + if ($appManager->isShipped($appInfo['id'])) { |
|
389 | + $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')'; |
|
390 | + } |
|
391 | + } |
|
392 | + |
|
393 | + if (!empty($incompatibleShippedApps)) { |
|
394 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('core'); |
|
395 | + $hint = $l->t('The files of the app %1$s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]); |
|
396 | + throw new \OCP\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint); |
|
397 | + } |
|
398 | + |
|
399 | + $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion)); |
|
400 | + $tmpl->assign('incompatibleAppsList', $incompatibleApps); |
|
401 | + try { |
|
402 | + $defaults = new \OC_Defaults(); |
|
403 | + $tmpl->assign('productName', $defaults->getName()); |
|
404 | + } catch (Throwable $error) { |
|
405 | + $tmpl->assign('productName', 'Nextcloud'); |
|
406 | + } |
|
407 | + $tmpl->assign('oldTheme', $oldTheme); |
|
408 | + $tmpl->printPage(); |
|
409 | + } |
|
410 | + |
|
411 | + public static function initSession(): void { |
|
412 | + $request = Server::get(IRequest::class); |
|
413 | + $isDavRequest = strpos($request->getRequestUri(), '/remote.php/dav') === 0 || strpos($request->getRequestUri(), '/remote.php/webdav') === 0; |
|
414 | + if ($request->getHeader('Authorization') !== '' && is_null($request->getCookie('cookie_test')) && $isDavRequest && !isset($_COOKIE['nc_session_id'])) { |
|
415 | + setcookie('cookie_test', 'test', time() + 3600); |
|
416 | + // Do not initialize the session if a request is authenticated directly |
|
417 | + // unless there is a session cookie already sent along |
|
418 | + return; |
|
419 | + } |
|
420 | + |
|
421 | + if ($request->getServerProtocol() === 'https') { |
|
422 | + ini_set('session.cookie_secure', 'true'); |
|
423 | + } |
|
424 | + |
|
425 | + // prevents javascript from accessing php session cookies |
|
426 | + ini_set('session.cookie_httponly', 'true'); |
|
427 | + |
|
428 | + // set the cookie path to the Nextcloud directory |
|
429 | + $cookie_path = OC::$WEBROOT ? : '/'; |
|
430 | + ini_set('session.cookie_path', $cookie_path); |
|
431 | + |
|
432 | + // Let the session name be changed in the initSession Hook |
|
433 | + $sessionName = OC_Util::getInstanceId(); |
|
434 | + |
|
435 | + try { |
|
436 | + // set the session name to the instance id - which is unique |
|
437 | + $session = new \OC\Session\Internal($sessionName); |
|
438 | + |
|
439 | + $cryptoWrapper = Server::get(\OC\Session\CryptoWrapper::class); |
|
440 | + $session = $cryptoWrapper->wrapSession($session); |
|
441 | + self::$server->setSession($session); |
|
442 | + |
|
443 | + // if session can't be started break with http 500 error |
|
444 | + } catch (Exception $e) { |
|
445 | + Server::get(LoggerInterface::class)->error($e->getMessage(), ['app' => 'base','exception' => $e]); |
|
446 | + //show the user a detailed error page |
|
447 | + OC_Template::printExceptionErrorPage($e, 500); |
|
448 | + die(); |
|
449 | + } |
|
450 | + |
|
451 | + //try to set the session lifetime |
|
452 | + $sessionLifeTime = self::getSessionLifeTime(); |
|
453 | + @ini_set('gc_maxlifetime', (string)$sessionLifeTime); |
|
454 | + |
|
455 | + // session timeout |
|
456 | + if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) { |
|
457 | + if (isset($_COOKIE[session_name()])) { |
|
458 | + setcookie(session_name(), '', -1, self::$WEBROOT ? : '/'); |
|
459 | + } |
|
460 | + Server::get(IUserSession::class)->logout(); |
|
461 | + } |
|
462 | + |
|
463 | + if (!self::hasSessionRelaxedExpiry()) { |
|
464 | + $session->set('LAST_ACTIVITY', time()); |
|
465 | + } |
|
466 | + $session->close(); |
|
467 | + } |
|
468 | + |
|
469 | + private static function getSessionLifeTime(): int { |
|
470 | + return Server::get(\OC\AllConfig::class)->getSystemValueInt('session_lifetime', 60 * 60 * 24); |
|
471 | + } |
|
472 | + |
|
473 | + /** |
|
474 | + * @return bool true if the session expiry should only be done by gc instead of an explicit timeout |
|
475 | + */ |
|
476 | + public static function hasSessionRelaxedExpiry(): bool { |
|
477 | + return Server::get(\OC\AllConfig::class)->getSystemValueBool('session_relaxed_expiry', false); |
|
478 | + } |
|
479 | + |
|
480 | + /** |
|
481 | + * Try to set some values to the required Nextcloud default |
|
482 | + */ |
|
483 | + public static function setRequiredIniValues(): void { |
|
484 | + @ini_set('default_charset', 'UTF-8'); |
|
485 | + @ini_set('gd.jpeg_ignore_warning', '1'); |
|
486 | + } |
|
487 | + |
|
488 | + /** |
|
489 | + * Send the same site cookies |
|
490 | + */ |
|
491 | + private static function sendSameSiteCookies(): void { |
|
492 | + $cookieParams = session_get_cookie_params(); |
|
493 | + $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : ''; |
|
494 | + $policies = [ |
|
495 | + 'lax', |
|
496 | + 'strict', |
|
497 | + ]; |
|
498 | + |
|
499 | + // Append __Host to the cookie if it meets the requirements |
|
500 | + $cookiePrefix = ''; |
|
501 | + if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') { |
|
502 | + $cookiePrefix = '__Host-'; |
|
503 | + } |
|
504 | + |
|
505 | + foreach ($policies as $policy) { |
|
506 | + header( |
|
507 | + sprintf( |
|
508 | + 'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s', |
|
509 | + $cookiePrefix, |
|
510 | + $policy, |
|
511 | + $cookieParams['path'], |
|
512 | + $policy |
|
513 | + ), |
|
514 | + false |
|
515 | + ); |
|
516 | + } |
|
517 | + } |
|
518 | + |
|
519 | + /** |
|
520 | + * Same Site cookie to further mitigate CSRF attacks. This cookie has to |
|
521 | + * be set in every request if cookies are sent to add a second level of |
|
522 | + * defense against CSRF. |
|
523 | + * |
|
524 | + * If the cookie is not sent this will set the cookie and reload the page. |
|
525 | + * We use an additional cookie since we want to protect logout CSRF and |
|
526 | + * also we can't directly interfere with PHP's session mechanism. |
|
527 | + */ |
|
528 | + private static function performSameSiteCookieProtection(\OCP\IConfig $config): void { |
|
529 | + $request = Server::get(IRequest::class); |
|
530 | + |
|
531 | + // Some user agents are notorious and don't really properly follow HTTP |
|
532 | + // specifications. For those, have an automated opt-out. Since the protection |
|
533 | + // for remote.php is applied in base.php as starting point we need to opt out |
|
534 | + // here. |
|
535 | + $incompatibleUserAgents = $config->getSystemValue('csrf.optout'); |
|
536 | + |
|
537 | + // Fallback, if csrf.optout is unset |
|
538 | + if (!is_array($incompatibleUserAgents)) { |
|
539 | + $incompatibleUserAgents = [ |
|
540 | + // OS X Finder |
|
541 | + '/^WebDAVFS/', |
|
542 | + // Windows webdav drive |
|
543 | + '/^Microsoft-WebDAV-MiniRedir/', |
|
544 | + ]; |
|
545 | + } |
|
546 | + |
|
547 | + if ($request->isUserAgent($incompatibleUserAgents)) { |
|
548 | + return; |
|
549 | + } |
|
550 | + |
|
551 | + if (count($_COOKIE) > 0) { |
|
552 | + $requestUri = $request->getScriptName(); |
|
553 | + $processingScript = explode('/', $requestUri); |
|
554 | + $processingScript = $processingScript[count($processingScript) - 1]; |
|
555 | + |
|
556 | + // index.php routes are handled in the middleware |
|
557 | + if ($processingScript === 'index.php') { |
|
558 | + return; |
|
559 | + } |
|
560 | + |
|
561 | + // All other endpoints require the lax and the strict cookie |
|
562 | + if (!$request->passesStrictCookieCheck()) { |
|
563 | + self::sendSameSiteCookies(); |
|
564 | + // Debug mode gets access to the resources without strict cookie |
|
565 | + // due to the fact that the SabreDAV browser also lives there. |
|
566 | + if (!$config->getSystemValue('debug', false)) { |
|
567 | + http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE); |
|
568 | + exit(); |
|
569 | + } |
|
570 | + } |
|
571 | + } elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) { |
|
572 | + self::sendSameSiteCookies(); |
|
573 | + } |
|
574 | + } |
|
575 | + |
|
576 | + public static function init(): void { |
|
577 | + // calculate the root directories |
|
578 | + OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4)); |
|
579 | + |
|
580 | + // register autoloader |
|
581 | + $loaderStart = microtime(true); |
|
582 | + require_once __DIR__ . '/autoloader.php'; |
|
583 | + self::$loader = new \OC\Autoloader([ |
|
584 | + OC::$SERVERROOT . '/lib/private/legacy', |
|
585 | + ]); |
|
586 | + if (defined('PHPUNIT_RUN')) { |
|
587 | + self::$loader->addValidRoot(OC::$SERVERROOT . '/tests'); |
|
588 | + } |
|
589 | + spl_autoload_register([self::$loader, 'load']); |
|
590 | + $loaderEnd = microtime(true); |
|
591 | + |
|
592 | + self::$CLI = (php_sapi_name() == 'cli'); |
|
593 | + |
|
594 | + // Add default composer PSR-4 autoloader |
|
595 | + self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php'; |
|
596 | + self::$composerAutoloader->setApcuPrefix('composer_autoload'); |
|
597 | + |
|
598 | + try { |
|
599 | + self::initPaths(); |
|
600 | + // setup 3rdparty autoloader |
|
601 | + $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php'; |
|
602 | + if (!file_exists($vendorAutoLoad)) { |
|
603 | + throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".'); |
|
604 | + } |
|
605 | + require_once $vendorAutoLoad; |
|
606 | + } catch (\RuntimeException $e) { |
|
607 | + if (!self::$CLI) { |
|
608 | + http_response_code(503); |
|
609 | + } |
|
610 | + // we can't use the template error page here, because this needs the |
|
611 | + // DI container which isn't available yet |
|
612 | + print($e->getMessage()); |
|
613 | + exit(); |
|
614 | + } |
|
615 | + |
|
616 | + // setup the basic server |
|
617 | + self::$server = new \OC\Server(\OC::$WEBROOT, self::$config); |
|
618 | + self::$server->boot(); |
|
619 | + |
|
620 | + $eventLogger = Server::get(\OCP\Diagnostics\IEventLogger::class); |
|
621 | + $eventLogger->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd); |
|
622 | + $eventLogger->start('boot', 'Initialize'); |
|
623 | + |
|
624 | + // Override php.ini and log everything if we're troubleshooting |
|
625 | + if (self::$config->getValue('loglevel') === ILogger::DEBUG) { |
|
626 | + error_reporting(E_ALL); |
|
627 | + } |
|
628 | + |
|
629 | + // Don't display errors and log them |
|
630 | + @ini_set('display_errors', '0'); |
|
631 | + @ini_set('log_errors', '1'); |
|
632 | + |
|
633 | + if (!date_default_timezone_set('UTC')) { |
|
634 | + throw new \RuntimeException('Could not set timezone to UTC'); |
|
635 | + } |
|
636 | + |
|
637 | + |
|
638 | + //try to configure php to enable big file uploads. |
|
639 | + //this doesn´t work always depending on the webserver and php configuration. |
|
640 | + //Let´s try to overwrite some defaults if they are smaller than 1 hour |
|
641 | + |
|
642 | + if (intval(@ini_get('max_execution_time') ?? 0) < 3600) { |
|
643 | + @ini_set('max_execution_time', strval(3600)); |
|
644 | + } |
|
645 | + |
|
646 | + if (intval(@ini_get('max_input_time') ?? 0) < 3600) { |
|
647 | + @ini_set('max_input_time', strval(3600)); |
|
648 | + } |
|
649 | + |
|
650 | + //try to set the maximum execution time to the largest time limit we have |
|
651 | + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { |
|
652 | + @set_time_limit(max(intval(@ini_get('max_execution_time')), intval(@ini_get('max_input_time')))); |
|
653 | + } |
|
654 | + |
|
655 | + self::setRequiredIniValues(); |
|
656 | + self::handleAuthHeaders(); |
|
657 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
658 | + self::registerAutoloaderCache($systemConfig); |
|
659 | + |
|
660 | + // initialize intl fallback if necessary |
|
661 | + OC_Util::isSetLocaleWorking(); |
|
662 | + |
|
663 | + $config = Server::get(\OCP\IConfig::class); |
|
664 | + if (!defined('PHPUNIT_RUN')) { |
|
665 | + $errorHandler = new OC\Log\ErrorHandler( |
|
666 | + \OCP\Server::get(\Psr\Log\LoggerInterface::class), |
|
667 | + ); |
|
668 | + $exceptionHandler = [$errorHandler, 'onException']; |
|
669 | + if ($config->getSystemValue('debug', false)) { |
|
670 | + set_error_handler([$errorHandler, 'onAll'], E_ALL); |
|
671 | + if (\OC::$CLI) { |
|
672 | + $exceptionHandler = ['OC_Template', 'printExceptionErrorPage']; |
|
673 | + } |
|
674 | + } else { |
|
675 | + set_error_handler([$errorHandler, 'onError']); |
|
676 | + } |
|
677 | + register_shutdown_function([$errorHandler, 'onShutdown']); |
|
678 | + set_exception_handler($exceptionHandler); |
|
679 | + } |
|
680 | + |
|
681 | + /** @var \OC\AppFramework\Bootstrap\Coordinator $bootstrapCoordinator */ |
|
682 | + $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class); |
|
683 | + $bootstrapCoordinator->runInitialRegistration(); |
|
684 | + |
|
685 | + $eventLogger->start('init_session', 'Initialize session'); |
|
686 | + OC_App::loadApps(['session']); |
|
687 | + if (!self::$CLI) { |
|
688 | + self::initSession(); |
|
689 | + } |
|
690 | + $eventLogger->end('init_session'); |
|
691 | + self::checkConfig(); |
|
692 | + self::checkInstalled($systemConfig); |
|
693 | + |
|
694 | + OC_Response::addSecurityHeaders(); |
|
695 | + |
|
696 | + self::performSameSiteCookieProtection($config); |
|
697 | + |
|
698 | + if (!defined('OC_CONSOLE')) { |
|
699 | + $errors = OC_Util::checkServer($systemConfig); |
|
700 | + if (count($errors) > 0) { |
|
701 | + if (!self::$CLI) { |
|
702 | + http_response_code(503); |
|
703 | + OC_Util::addStyle('guest'); |
|
704 | + try { |
|
705 | + OC_Template::printGuestPage('', 'error', ['errors' => $errors]); |
|
706 | + exit; |
|
707 | + } catch (\Exception $e) { |
|
708 | + // In case any error happens when showing the error page, we simply fall back to posting the text. |
|
709 | + // This might be the case when e.g. the data directory is broken and we can not load/write SCSS to/from it. |
|
710 | + } |
|
711 | + } |
|
712 | + |
|
713 | + // Convert l10n string into regular string for usage in database |
|
714 | + $staticErrors = []; |
|
715 | + foreach ($errors as $error) { |
|
716 | + echo $error['error'] . "\n"; |
|
717 | + echo $error['hint'] . "\n\n"; |
|
718 | + $staticErrors[] = [ |
|
719 | + 'error' => (string)$error['error'], |
|
720 | + 'hint' => (string)$error['hint'], |
|
721 | + ]; |
|
722 | + } |
|
723 | + |
|
724 | + try { |
|
725 | + $config->setAppValue('core', 'cronErrors', json_encode($staticErrors)); |
|
726 | + } catch (\Exception $e) { |
|
727 | + echo('Writing to database failed'); |
|
728 | + } |
|
729 | + exit(1); |
|
730 | + } elseif (self::$CLI && $config->getSystemValue('installed', false)) { |
|
731 | + $config->deleteAppValue('core', 'cronErrors'); |
|
732 | + } |
|
733 | + } |
|
734 | + |
|
735 | + // User and Groups |
|
736 | + if (!$systemConfig->getValue("installed", false)) { |
|
737 | + self::$server->getSession()->set('user_id', ''); |
|
738 | + } |
|
739 | + |
|
740 | + OC_User::useBackend(new \OC\User\Database()); |
|
741 | + Server::get(\OCP\IGroupManager::class)->addBackend(new \OC\Group\Database()); |
|
742 | + |
|
743 | + // Subscribe to the hook |
|
744 | + \OCP\Util::connectHook( |
|
745 | + '\OCA\Files_Sharing\API\Server2Server', |
|
746 | + 'preLoginNameUsedAsUserName', |
|
747 | + '\OC\User\Database', |
|
748 | + 'preLoginNameUsedAsUserName' |
|
749 | + ); |
|
750 | + |
|
751 | + //setup extra user backends |
|
752 | + if (!\OCP\Util::needUpgrade()) { |
|
753 | + OC_User::setupBackends(); |
|
754 | + } else { |
|
755 | + // Run upgrades in incognito mode |
|
756 | + OC_User::setIncognitoMode(true); |
|
757 | + } |
|
758 | + |
|
759 | + self::registerCleanupHooks($systemConfig); |
|
760 | + self::registerShareHooks($systemConfig); |
|
761 | + self::registerEncryptionWrapperAndHooks(); |
|
762 | + self::registerAccountHooks(); |
|
763 | + self::registerResourceCollectionHooks(); |
|
764 | + self::registerFileReferenceEventListener(); |
|
765 | + self::registerRenderReferenceEventListener(); |
|
766 | + self::registerAppRestrictionsHooks(); |
|
767 | + |
|
768 | + // Make sure that the application class is not loaded before the database is setup |
|
769 | + if ($systemConfig->getValue("installed", false)) { |
|
770 | + OC_App::loadApp('settings'); |
|
771 | + /* Build core application to make sure that listeners are registered */ |
|
772 | + Server::get(\OC\Core\Application::class); |
|
773 | + } |
|
774 | + |
|
775 | + //make sure temporary files are cleaned up |
|
776 | + $tmpManager = Server::get(\OCP\ITempManager::class); |
|
777 | + register_shutdown_function([$tmpManager, 'clean']); |
|
778 | + $lockProvider = Server::get(\OCP\Lock\ILockingProvider::class); |
|
779 | + register_shutdown_function([$lockProvider, 'releaseAll']); |
|
780 | + |
|
781 | + // Check whether the sample configuration has been copied |
|
782 | + if ($systemConfig->getValue('copied_sample_config', false)) { |
|
783 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
784 | + OC_Template::printErrorPage( |
|
785 | + $l->t('Sample configuration detected'), |
|
786 | + $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php'), |
|
787 | + 503 |
|
788 | + ); |
|
789 | + return; |
|
790 | + } |
|
791 | + |
|
792 | + $request = Server::get(IRequest::class); |
|
793 | + $host = $request->getInsecureServerHost(); |
|
794 | + /** |
|
795 | + * if the host passed in headers isn't trusted |
|
796 | + * FIXME: Should not be in here at all :see_no_evil: |
|
797 | + */ |
|
798 | + if (!OC::$CLI |
|
799 | + && !Server::get(\OC\Security\TrustedDomainHelper::class)->isTrustedDomain($host) |
|
800 | + && $config->getSystemValue('installed', false) |
|
801 | + ) { |
|
802 | + // Allow access to CSS resources |
|
803 | + $isScssRequest = false; |
|
804 | + if (strpos($request->getPathInfo() ?: '', '/css/') === 0) { |
|
805 | + $isScssRequest = true; |
|
806 | + } |
|
807 | + |
|
808 | + if (substr($request->getRequestUri(), -11) === '/status.php') { |
|
809 | + http_response_code(400); |
|
810 | + header('Content-Type: application/json'); |
|
811 | + echo '{"error": "Trusted domain error.", "code": 15}'; |
|
812 | + exit(); |
|
813 | + } |
|
814 | + |
|
815 | + if (!$isScssRequest) { |
|
816 | + http_response_code(400); |
|
817 | + Server::get(LoggerInterface::class)->info( |
|
818 | + 'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.', |
|
819 | + [ |
|
820 | + 'app' => 'core', |
|
821 | + 'remoteAddress' => $request->getRemoteAddress(), |
|
822 | + 'host' => $host, |
|
823 | + ] |
|
824 | + ); |
|
825 | + |
|
826 | + $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest'); |
|
827 | + $tmpl->assign('docUrl', Server::get(IURLGenerator::class)->linkToDocs('admin-trusted-domains')); |
|
828 | + $tmpl->printPage(); |
|
829 | + |
|
830 | + exit(); |
|
831 | + } |
|
832 | + } |
|
833 | + $eventLogger->end('boot'); |
|
834 | + $eventLogger->log('init', 'OC::init', $loaderStart, microtime(true)); |
|
835 | + $eventLogger->start('runtime', 'Runtime'); |
|
836 | + $eventLogger->start('request', 'Full request after boot'); |
|
837 | + register_shutdown_function(function () use ($eventLogger) { |
|
838 | + $eventLogger->end('request'); |
|
839 | + }); |
|
840 | + } |
|
841 | + |
|
842 | + /** |
|
843 | + * register hooks for the cleanup of cache and bruteforce protection |
|
844 | + */ |
|
845 | + public static function registerCleanupHooks(\OC\SystemConfig $systemConfig): void { |
|
846 | + //don't try to do this before we are properly setup |
|
847 | + if ($systemConfig->getValue('installed', false) && !\OCP\Util::needUpgrade()) { |
|
848 | + // NOTE: This will be replaced to use OCP |
|
849 | + $userSession = Server::get(\OC\User\Session::class); |
|
850 | + $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) { |
|
851 | + if (!defined('PHPUNIT_RUN') && $userSession->isLoggedIn()) { |
|
852 | + // reset brute force delay for this IP address and username |
|
853 | + $uid = $userSession->getUser()->getUID(); |
|
854 | + $request = Server::get(IRequest::class); |
|
855 | + $throttler = Server::get(\OC\Security\Bruteforce\Throttler::class); |
|
856 | + $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]); |
|
857 | + } |
|
858 | + |
|
859 | + try { |
|
860 | + $cache = new \OC\Cache\File(); |
|
861 | + $cache->gc(); |
|
862 | + } catch (\OC\ServerNotAvailableException $e) { |
|
863 | + // not a GC exception, pass it on |
|
864 | + throw $e; |
|
865 | + } catch (\OC\ForbiddenException $e) { |
|
866 | + // filesystem blocked for this request, ignore |
|
867 | + } catch (\Exception $e) { |
|
868 | + // a GC exception should not prevent users from using OC, |
|
869 | + // so log the exception |
|
870 | + Server::get(LoggerInterface::class)->warning('Exception when running cache gc.', [ |
|
871 | + 'app' => 'core', |
|
872 | + 'exception' => $e, |
|
873 | + ]); |
|
874 | + } |
|
875 | + }); |
|
876 | + } |
|
877 | + } |
|
878 | + |
|
879 | + private static function registerEncryptionWrapperAndHooks(): void { |
|
880 | + $manager = Server::get(\OCP\Encryption\IManager::class); |
|
881 | + \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage'); |
|
882 | + |
|
883 | + $enabled = $manager->isEnabled(); |
|
884 | + if ($enabled) { |
|
885 | + \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared'); |
|
886 | + \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared'); |
|
887 | + \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename'); |
|
888 | + \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore'); |
|
889 | + } |
|
890 | + } |
|
891 | + |
|
892 | + private static function registerAccountHooks(): void { |
|
893 | + /** @var IEventDispatcher $dispatcher */ |
|
894 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
895 | + $dispatcher->addServiceListener(UserChangedEvent::class, \OC\Accounts\Hooks::class); |
|
896 | + } |
|
897 | + |
|
898 | + private static function registerAppRestrictionsHooks(): void { |
|
899 | + /** @var \OC\Group\Manager $groupManager */ |
|
900 | + $groupManager = Server::get(\OCP\IGroupManager::class); |
|
901 | + $groupManager->listen('\OC\Group', 'postDelete', function (\OCP\IGroup $group) { |
|
902 | + $appManager = Server::get(\OCP\App\IAppManager::class); |
|
903 | + $apps = $appManager->getEnabledAppsForGroup($group); |
|
904 | + foreach ($apps as $appId) { |
|
905 | + $restrictions = $appManager->getAppRestriction($appId); |
|
906 | + if (empty($restrictions)) { |
|
907 | + continue; |
|
908 | + } |
|
909 | + $key = array_search($group->getGID(), $restrictions); |
|
910 | + unset($restrictions[$key]); |
|
911 | + $restrictions = array_values($restrictions); |
|
912 | + if (empty($restrictions)) { |
|
913 | + $appManager->disableApp($appId); |
|
914 | + } else { |
|
915 | + $appManager->enableAppForGroups($appId, $restrictions); |
|
916 | + } |
|
917 | + } |
|
918 | + }); |
|
919 | + } |
|
920 | + |
|
921 | + private static function registerResourceCollectionHooks(): void { |
|
922 | + \OC\Collaboration\Resources\Listener::register(Server::get(SymfonyAdapter::class), Server::get(IEventDispatcher::class)); |
|
923 | + } |
|
924 | + |
|
925 | + private static function registerFileReferenceEventListener(): void { |
|
926 | + \OC\Collaboration\Reference\File\FileReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
927 | + } |
|
928 | + |
|
929 | + private static function registerRenderReferenceEventListener() { |
|
930 | + \OC\Collaboration\Reference\RenderReferenceEventListener::register(Server::get(IEventDispatcher::class)); |
|
931 | + } |
|
932 | + |
|
933 | + /** |
|
934 | + * register hooks for sharing |
|
935 | + */ |
|
936 | + public static function registerShareHooks(\OC\SystemConfig $systemConfig): void { |
|
937 | + if ($systemConfig->getValue('installed')) { |
|
938 | + OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser'); |
|
939 | + OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup'); |
|
940 | + |
|
941 | + /** @var IEventDispatcher $dispatcher */ |
|
942 | + $dispatcher = Server::get(IEventDispatcher::class); |
|
943 | + $dispatcher->addServiceListener(UserRemovedEvent::class, \OC\Share20\UserRemovedListener::class); |
|
944 | + } |
|
945 | + } |
|
946 | + |
|
947 | + protected static function registerAutoloaderCache(\OC\SystemConfig $systemConfig): void { |
|
948 | + // The class loader takes an optional low-latency cache, which MUST be |
|
949 | + // namespaced. The instanceid is used for namespacing, but might be |
|
950 | + // unavailable at this point. Furthermore, it might not be possible to |
|
951 | + // generate an instanceid via \OC_Util::getInstanceId() because the |
|
952 | + // config file may not be writable. As such, we only register a class |
|
953 | + // loader cache if instanceid is available without trying to create one. |
|
954 | + $instanceId = $systemConfig->getValue('instanceid', null); |
|
955 | + if ($instanceId) { |
|
956 | + try { |
|
957 | + $memcacheFactory = Server::get(\OCP\ICacheFactory::class); |
|
958 | + self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader')); |
|
959 | + } catch (\Exception $ex) { |
|
960 | + } |
|
961 | + } |
|
962 | + } |
|
963 | + |
|
964 | + /** |
|
965 | + * Handle the request |
|
966 | + */ |
|
967 | + public static function handleRequest(): void { |
|
968 | + Server::get(\OCP\Diagnostics\IEventLogger::class)->start('handle_request', 'Handle request'); |
|
969 | + $systemConfig = Server::get(\OC\SystemConfig::class); |
|
970 | + |
|
971 | + // Check if Nextcloud is installed or in maintenance (update) mode |
|
972 | + if (!$systemConfig->getValue('installed', false)) { |
|
973 | + \OC::$server->getSession()->clear(); |
|
974 | + $setupHelper = new OC\Setup( |
|
975 | + $systemConfig, |
|
976 | + Server::get(\bantu\IniGetWrapper\IniGetWrapper::class), |
|
977 | + Server::get(\OCP\L10N\IFactory::class)->get('lib'), |
|
978 | + Server::get(\OCP\Defaults::class), |
|
979 | + Server::get(\Psr\Log\LoggerInterface::class), |
|
980 | + Server::get(\OCP\Security\ISecureRandom::class), |
|
981 | + Server::get(\OC\Installer::class) |
|
982 | + ); |
|
983 | + $controller = new OC\Core\Controller\SetupController($setupHelper); |
|
984 | + $controller->run($_POST); |
|
985 | + exit(); |
|
986 | + } |
|
987 | + |
|
988 | + $request = Server::get(IRequest::class); |
|
989 | + $requestPath = $request->getRawPathInfo(); |
|
990 | + if ($requestPath === '/heartbeat') { |
|
991 | + return; |
|
992 | + } |
|
993 | + if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade |
|
994 | + self::checkMaintenanceMode($systemConfig); |
|
995 | + |
|
996 | + if (\OCP\Util::needUpgrade()) { |
|
997 | + if (function_exists('opcache_reset')) { |
|
998 | + opcache_reset(); |
|
999 | + } |
|
1000 | + if (!((bool) $systemConfig->getValue('maintenance', false))) { |
|
1001 | + self::printUpgradePage($systemConfig); |
|
1002 | + exit(); |
|
1003 | + } |
|
1004 | + } |
|
1005 | + } |
|
1006 | + |
|
1007 | + // emergency app disabling |
|
1008 | + if ($requestPath === '/disableapp' |
|
1009 | + && $request->getMethod() === 'POST' |
|
1010 | + ) { |
|
1011 | + \OC_JSON::callCheck(); |
|
1012 | + \OC_JSON::checkAdminUser(); |
|
1013 | + $appIds = (array)$request->getParam('appid'); |
|
1014 | + foreach ($appIds as $appId) { |
|
1015 | + $appId = \OC_App::cleanAppId($appId); |
|
1016 | + Server::get(\OCP\App\IAppManager::class)->disableApp($appId); |
|
1017 | + } |
|
1018 | + \OC_JSON::success(); |
|
1019 | + exit(); |
|
1020 | + } |
|
1021 | + |
|
1022 | + // Always load authentication apps |
|
1023 | + OC_App::loadApps(['authentication']); |
|
1024 | + |
|
1025 | + // Load minimum set of apps |
|
1026 | + if (!\OCP\Util::needUpgrade() |
|
1027 | + && !((bool) $systemConfig->getValue('maintenance', false))) { |
|
1028 | + // For logged-in users: Load everything |
|
1029 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1030 | + OC_App::loadApps(); |
|
1031 | + } else { |
|
1032 | + // For guests: Load only filesystem and logging |
|
1033 | + OC_App::loadApps(['filesystem', 'logging']); |
|
1034 | + |
|
1035 | + // Don't try to login when a client is trying to get a OAuth token. |
|
1036 | + // OAuth needs to support basic auth too, so the login is not valid |
|
1037 | + // inside Nextcloud and the Login exception would ruin it. |
|
1038 | + if ($request->getRawPathInfo() !== '/apps/oauth2/api/v1/token') { |
|
1039 | + self::handleLogin($request); |
|
1040 | + } |
|
1041 | + } |
|
1042 | + } |
|
1043 | + |
|
1044 | + if (!self::$CLI) { |
|
1045 | + try { |
|
1046 | + if (!((bool) $systemConfig->getValue('maintenance', false)) && !\OCP\Util::needUpgrade()) { |
|
1047 | + OC_App::loadApps(['filesystem', 'logging']); |
|
1048 | + OC_App::loadApps(); |
|
1049 | + } |
|
1050 | + Server::get(\OC\Route\Router::class)->match($request->getRawPathInfo()); |
|
1051 | + return; |
|
1052 | + } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) { |
|
1053 | + //header('HTTP/1.0 404 Not Found'); |
|
1054 | + } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) { |
|
1055 | + http_response_code(405); |
|
1056 | + return; |
|
1057 | + } |
|
1058 | + } |
|
1059 | + |
|
1060 | + // Handle WebDAV |
|
1061 | + if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { |
|
1062 | + // not allowed any more to prevent people |
|
1063 | + // mounting this root directly. |
|
1064 | + // Users need to mount remote.php/webdav instead. |
|
1065 | + http_response_code(405); |
|
1066 | + return; |
|
1067 | + } |
|
1068 | + |
|
1069 | + // Handle requests for JSON or XML |
|
1070 | + $acceptHeader = $request->getHeader('Accept'); |
|
1071 | + if (in_array($acceptHeader, ['application/json', 'application/xml'], true)) { |
|
1072 | + http_response_code(404); |
|
1073 | + return; |
|
1074 | + } |
|
1075 | + |
|
1076 | + // Handle resources that can't be found |
|
1077 | + // This prevents browsers from redirecting to the default page and then |
|
1078 | + // attempting to parse HTML as CSS and similar. |
|
1079 | + $destinationHeader = $request->getHeader('Sec-Fetch-Dest'); |
|
1080 | + if (in_array($destinationHeader, ['font', 'script', 'style'])) { |
|
1081 | + http_response_code(404); |
|
1082 | + return; |
|
1083 | + } |
|
1084 | + |
|
1085 | + // Redirect to the default app or login only as an entry point |
|
1086 | + if ($requestPath === '') { |
|
1087 | + // Someone is logged in |
|
1088 | + if (Server::get(IUserSession::class)->isLoggedIn()) { |
|
1089 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToDefaultPageUrl()); |
|
1090 | + } else { |
|
1091 | + // Not handled and not logged in |
|
1092 | + header('Location: ' . Server::get(IURLGenerator::class)->linkToRouteAbsolute('core.login.showLoginForm')); |
|
1093 | + } |
|
1094 | + return; |
|
1095 | + } |
|
1096 | + |
|
1097 | + try { |
|
1098 | + Server::get(\OC\Route\Router::class)->match('/error/404'); |
|
1099 | + } catch (\Exception $e) { |
|
1100 | + logger('core')->emergency($e->getMessage(), ['exception' => $e]); |
|
1101 | + $l = Server::get(\OCP\L10N\IFactory::class)->get('lib'); |
|
1102 | + OC_Template::printErrorPage( |
|
1103 | + $l->t('404'), |
|
1104 | + $l->t('The page could not be found on the server.'), |
|
1105 | + 404 |
|
1106 | + ); |
|
1107 | + } |
|
1108 | + } |
|
1109 | + |
|
1110 | + /** |
|
1111 | + * Check login: apache auth, auth token, basic auth |
|
1112 | + */ |
|
1113 | + public static function handleLogin(OCP\IRequest $request): bool { |
|
1114 | + $userSession = Server::get(\OC\User\Session::class); |
|
1115 | + if (OC_User::handleApacheAuth()) { |
|
1116 | + return true; |
|
1117 | + } |
|
1118 | + if ($userSession->tryTokenLogin($request)) { |
|
1119 | + return true; |
|
1120 | + } |
|
1121 | + if (isset($_COOKIE['nc_username']) |
|
1122 | + && isset($_COOKIE['nc_token']) |
|
1123 | + && isset($_COOKIE['nc_session_id']) |
|
1124 | + && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) { |
|
1125 | + return true; |
|
1126 | + } |
|
1127 | + if ($userSession->tryBasicAuthLogin($request, Server::get(\OC\Security\Bruteforce\Throttler::class))) { |
|
1128 | + return true; |
|
1129 | + } |
|
1130 | + return false; |
|
1131 | + } |
|
1132 | + |
|
1133 | + protected static function handleAuthHeaders(): void { |
|
1134 | + //copy http auth headers for apache+php-fcgid work around |
|
1135 | + if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) { |
|
1136 | + $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION']; |
|
1137 | + } |
|
1138 | + |
|
1139 | + // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary. |
|
1140 | + $vars = [ |
|
1141 | + 'HTTP_AUTHORIZATION', // apache+php-cgi work around |
|
1142 | + 'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative |
|
1143 | + ]; |
|
1144 | + foreach ($vars as $var) { |
|
1145 | + if (isset($_SERVER[$var]) && is_string($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) { |
|
1146 | + $credentials = explode(':', base64_decode($matches[1]), 2); |
|
1147 | + if (count($credentials) === 2) { |
|
1148 | + $_SERVER['PHP_AUTH_USER'] = $credentials[0]; |
|
1149 | + $_SERVER['PHP_AUTH_PW'] = $credentials[1]; |
|
1150 | + break; |
|
1151 | + } |
|
1152 | + } |
|
1153 | + } |
|
1154 | + } |
|
1155 | 1155 | } |
1156 | 1156 | |
1157 | 1157 | OC::init(); |
@@ -30,90 +30,90 @@ |
||
30 | 30 | use OCP\IRequest; |
31 | 31 | |
32 | 32 | class ReferenceApiController extends \OCP\AppFramework\OCSController { |
33 | - private IReferenceManager $referenceManager; |
|
34 | - private ?string $userId; |
|
35 | - |
|
36 | - public function __construct(string $appName, |
|
37 | - IRequest $request, |
|
38 | - IReferenceManager $referenceManager, |
|
39 | - ?string $userId) { |
|
40 | - parent::__construct($appName, $request); |
|
41 | - $this->referenceManager = $referenceManager; |
|
42 | - $this->userId = $userId; |
|
43 | - } |
|
44 | - |
|
45 | - /** |
|
46 | - * @NoAdminRequired |
|
47 | - */ |
|
48 | - public function extract(string $text, bool $resolve = false, int $limit = 1): DataResponse { |
|
49 | - $references = $this->referenceManager->extractReferences($text); |
|
50 | - |
|
51 | - $result = []; |
|
52 | - $index = 0; |
|
53 | - foreach ($references as $reference) { |
|
54 | - if ($index++ >= $limit) { |
|
55 | - break; |
|
56 | - } |
|
57 | - |
|
58 | - $result[$reference] = $resolve ? $this->referenceManager->resolveReference($reference) : null; |
|
59 | - } |
|
60 | - |
|
61 | - return new DataResponse([ |
|
62 | - 'references' => $result |
|
63 | - ]); |
|
64 | - } |
|
65 | - |
|
66 | - /** |
|
67 | - * @NoAdminRequired |
|
68 | - */ |
|
69 | - public function resolveOne(string $reference): DataResponse { |
|
70 | - $resolvedReference = $this->referenceManager->resolveReference(trim($reference)); |
|
71 | - |
|
72 | - $response = new DataResponse(['references' => [ $reference => $resolvedReference ]]); |
|
73 | - $response->cacheFor(3600, false, true); |
|
74 | - return $response; |
|
75 | - } |
|
76 | - |
|
77 | - /** |
|
78 | - * @NoAdminRequired |
|
79 | - * |
|
80 | - * @param string[] $references |
|
81 | - */ |
|
82 | - public function resolve(array $references, int $limit = 1): DataResponse { |
|
83 | - $result = []; |
|
84 | - $index = 0; |
|
85 | - foreach ($references as $reference) { |
|
86 | - if ($index++ >= $limit) { |
|
87 | - break; |
|
88 | - } |
|
89 | - |
|
90 | - $result[$reference] = $this->referenceManager->resolveReference($reference); |
|
91 | - } |
|
92 | - |
|
93 | - return new DataResponse([ |
|
94 | - 'references' => array_filter($result) |
|
95 | - ]); |
|
96 | - } |
|
97 | - |
|
98 | - /** |
|
99 | - * @NoAdminRequired |
|
100 | - */ |
|
101 | - public function getProvidersInfo(): DataResponse { |
|
102 | - $providers = $this->referenceManager->getDiscoverableProviders(); |
|
103 | - $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
104 | - return $provider->jsonSerialize(); |
|
105 | - }, $providers); |
|
106 | - return new DataResponse($jsonProviders); |
|
107 | - } |
|
108 | - |
|
109 | - /** |
|
110 | - * @NoAdminRequired |
|
111 | - */ |
|
112 | - public function touchProvider(string $providerId, ?int $timestamp = null): DataResponse { |
|
113 | - if ($this->userId !== null) { |
|
114 | - $success = $this->referenceManager->touchProvider($this->userId, $providerId, $timestamp); |
|
115 | - return new DataResponse(['success' => $success]); |
|
116 | - } |
|
117 | - return new DataResponse(['success' => false]); |
|
118 | - } |
|
33 | + private IReferenceManager $referenceManager; |
|
34 | + private ?string $userId; |
|
35 | + |
|
36 | + public function __construct(string $appName, |
|
37 | + IRequest $request, |
|
38 | + IReferenceManager $referenceManager, |
|
39 | + ?string $userId) { |
|
40 | + parent::__construct($appName, $request); |
|
41 | + $this->referenceManager = $referenceManager; |
|
42 | + $this->userId = $userId; |
|
43 | + } |
|
44 | + |
|
45 | + /** |
|
46 | + * @NoAdminRequired |
|
47 | + */ |
|
48 | + public function extract(string $text, bool $resolve = false, int $limit = 1): DataResponse { |
|
49 | + $references = $this->referenceManager->extractReferences($text); |
|
50 | + |
|
51 | + $result = []; |
|
52 | + $index = 0; |
|
53 | + foreach ($references as $reference) { |
|
54 | + if ($index++ >= $limit) { |
|
55 | + break; |
|
56 | + } |
|
57 | + |
|
58 | + $result[$reference] = $resolve ? $this->referenceManager->resolveReference($reference) : null; |
|
59 | + } |
|
60 | + |
|
61 | + return new DataResponse([ |
|
62 | + 'references' => $result |
|
63 | + ]); |
|
64 | + } |
|
65 | + |
|
66 | + /** |
|
67 | + * @NoAdminRequired |
|
68 | + */ |
|
69 | + public function resolveOne(string $reference): DataResponse { |
|
70 | + $resolvedReference = $this->referenceManager->resolveReference(trim($reference)); |
|
71 | + |
|
72 | + $response = new DataResponse(['references' => [ $reference => $resolvedReference ]]); |
|
73 | + $response->cacheFor(3600, false, true); |
|
74 | + return $response; |
|
75 | + } |
|
76 | + |
|
77 | + /** |
|
78 | + * @NoAdminRequired |
|
79 | + * |
|
80 | + * @param string[] $references |
|
81 | + */ |
|
82 | + public function resolve(array $references, int $limit = 1): DataResponse { |
|
83 | + $result = []; |
|
84 | + $index = 0; |
|
85 | + foreach ($references as $reference) { |
|
86 | + if ($index++ >= $limit) { |
|
87 | + break; |
|
88 | + } |
|
89 | + |
|
90 | + $result[$reference] = $this->referenceManager->resolveReference($reference); |
|
91 | + } |
|
92 | + |
|
93 | + return new DataResponse([ |
|
94 | + 'references' => array_filter($result) |
|
95 | + ]); |
|
96 | + } |
|
97 | + |
|
98 | + /** |
|
99 | + * @NoAdminRequired |
|
100 | + */ |
|
101 | + public function getProvidersInfo(): DataResponse { |
|
102 | + $providers = $this->referenceManager->getDiscoverableProviders(); |
|
103 | + $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
104 | + return $provider->jsonSerialize(); |
|
105 | + }, $providers); |
|
106 | + return new DataResponse($jsonProviders); |
|
107 | + } |
|
108 | + |
|
109 | + /** |
|
110 | + * @NoAdminRequired |
|
111 | + */ |
|
112 | + public function touchProvider(string $providerId, ?int $timestamp = null): DataResponse { |
|
113 | + if ($this->userId !== null) { |
|
114 | + $success = $this->referenceManager->touchProvider($this->userId, $providerId, $timestamp); |
|
115 | + return new DataResponse(['success' => $success]); |
|
116 | + } |
|
117 | + return new DataResponse(['success' => false]); |
|
118 | + } |
|
119 | 119 | } |
@@ -69,7 +69,7 @@ discard block |
||
69 | 69 | public function resolveOne(string $reference): DataResponse { |
70 | 70 | $resolvedReference = $this->referenceManager->resolveReference(trim($reference)); |
71 | 71 | |
72 | - $response = new DataResponse(['references' => [ $reference => $resolvedReference ]]); |
|
72 | + $response = new DataResponse(['references' => [$reference => $resolvedReference]]); |
|
73 | 73 | $response->cacheFor(3600, false, true); |
74 | 74 | return $response; |
75 | 75 | } |
@@ -100,7 +100,7 @@ discard block |
||
100 | 100 | */ |
101 | 101 | public function getProvidersInfo(): DataResponse { |
102 | 102 | $providers = $this->referenceManager->getDiscoverableProviders(); |
103 | - $jsonProviders = array_map(static function (IDiscoverableReferenceProvider $provider) { |
|
103 | + $jsonProviders = array_map(static function(IDiscoverableReferenceProvider $provider) { |
|
104 | 104 | return $provider->jsonSerialize(); |
105 | 105 | }, $providers); |
106 | 106 | return new DataResponse($jsonProviders); |