AdminDirectoryController.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\PixelfedDirectoryController;
  4. use App\Models\ConfigCache;
  5. use App\Services\AccountService;
  6. use App\Services\ConfigCacheService;
  7. use App\Services\StatusService;
  8. use App\Status;
  9. use App\User;
  10. use Cache;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Facades\Http;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Facades\Validator;
  15. use Illuminate\Support\Str;
  16. use League\ISO3166\ISO3166;
  17. trait AdminDirectoryController
  18. {
  19. public function directoryHome(Request $request)
  20. {
  21. return view('admin.directory.home');
  22. }
  23. public function directoryInitialData(Request $request)
  24. {
  25. $res = [];
  26. $res['countries'] = collect((new ISO3166)->all())->pluck('name');
  27. $res['admins'] = User::whereIsAdmin(true)
  28. ->where('2fa_enabled', true)
  29. ->get()->map(function ($user) {
  30. return [
  31. 'uid' => (string) $user->id,
  32. 'pid' => (string) $user->profile_id,
  33. 'username' => $user->username,
  34. 'created_at' => $user->created_at,
  35. ];
  36. });
  37. $config = ConfigCache::whereK('pixelfed.directory')->first();
  38. if ($config) {
  39. $data = $config->v ? json_decode($config->v, true) : [];
  40. $res = array_merge($res, $data);
  41. }
  42. if (empty($res['summary'])) {
  43. $summary = ConfigCache::whereK('app.short_description')->pluck('v');
  44. $res['summary'] = $summary ? $summary[0] : null;
  45. }
  46. if (isset($res['banner_image']) && ! empty($res['banner_image'])) {
  47. $res['banner_image'] = url(Storage::url($res['banner_image']));
  48. }
  49. if (isset($res['favourite_posts'])) {
  50. $res['favourite_posts'] = collect($res['favourite_posts'])->map(function ($id) {
  51. return StatusService::get($id);
  52. })
  53. ->filter(function ($post) {
  54. return $post && isset($post['account']);
  55. })
  56. ->values();
  57. }
  58. $res['community_guidelines'] = config_cache('app.rules') ? json_decode(config_cache('app.rules'), true) : [];
  59. $res['curated_onboarding'] = (bool) config_cache('instance.curated_registration.enabled');
  60. $res['open_registration'] = (bool) config_cache('pixelfed.open_registration');
  61. $res['oauth_enabled'] = (bool) config_cache('pixelfed.oauth_enabled') && file_exists(storage_path('oauth-public.key')) && file_exists(storage_path('oauth-private.key'));
  62. $res['activitypub_enabled'] = (bool) config_cache('federation.activitypub.enabled');
  63. $res['feature_config'] = [
  64. 'media_types' => Str::of(config_cache('pixelfed.media_types'))->explode(','),
  65. 'image_quality' => config_cache('pixelfed.image_quality'),
  66. 'optimize_image' => (bool) config_cache('pixelfed.optimize_image'),
  67. 'max_photo_size' => config_cache('pixelfed.max_photo_size'),
  68. 'max_caption_length' => config_cache('pixelfed.max_caption_length'),
  69. 'max_altext_length' => config_cache('pixelfed.max_altext_length'),
  70. 'enforce_account_limit' => (bool) config_cache('pixelfed.enforce_account_limit'),
  71. 'max_account_size' => config_cache('pixelfed.max_account_size'),
  72. 'max_album_length' => config_cache('pixelfed.max_album_length'),
  73. 'account_deletion' => (bool) config_cache('pixelfed.account_deletion'),
  74. ];
  75. if (config_cache('pixelfed.directory.testimonials')) {
  76. $testimonials = collect(json_decode(config_cache('pixelfed.directory.testimonials'), true))
  77. ->map(function ($t) {
  78. return [
  79. 'profile' => AccountService::get($t['profile_id']),
  80. 'body' => $t['body'],
  81. ];
  82. });
  83. $res['testimonials'] = $testimonials;
  84. }
  85. $validator = Validator::make($res['feature_config'], [
  86. 'media_types' => [
  87. 'required',
  88. function ($attribute, $value, $fail) {
  89. if (! in_array('image/jpeg', $value->toArray()) || ! in_array('image/png', $value->toArray())) {
  90. $fail('You must enable image/jpeg and image/png support.');
  91. }
  92. },
  93. ],
  94. 'image_quality' => 'required_if:optimize_image,true|integer|min:75|max:100',
  95. 'max_altext_length' => 'required|integer|min:1000|max:5000',
  96. 'max_photo_size' => 'required|integer|min:15000|max:100000',
  97. 'max_account_size' => 'required_if:enforce_account_limit,true|integer|min:1000000',
  98. 'max_album_length' => 'required|integer|min:4|max:20',
  99. 'account_deletion' => 'required|accepted',
  100. 'max_caption_length' => 'required|integer|min:500|max:10000',
  101. ]);
  102. $res['requirements_validator'] = $validator->errors();
  103. $res['is_eligible'] = ($res['open_registration'] || $res['curated_onboarding']) &&
  104. $res['oauth_enabled'] &&
  105. $res['activitypub_enabled'] &&
  106. count($res['requirements_validator']) === 0 &&
  107. $this->validVal($res, 'admin') &&
  108. $this->validVal($res, 'summary', null, 10) &&
  109. $this->validVal($res, 'favourite_posts', 3) &&
  110. $this->validVal($res, 'contact_email') &&
  111. $this->validVal($res, 'privacy_pledge') &&
  112. $this->validVal($res, 'location');
  113. $res['has_submitted'] = config_cache('pixelfed.directory.has_submitted') ?? false;
  114. $res['synced'] = config_cache('pixelfed.directory.is_synced') ?? false;
  115. $res['latest_response'] = config_cache('pixelfed.directory.latest_response') ?? null;
  116. $path = base_path('resources/lang');
  117. $langs = collect([]);
  118. foreach (new \DirectoryIterator($path) as $io) {
  119. $name = $io->getFilename();
  120. $skip = ['vendor'];
  121. if ($io->isDot() || in_array($name, $skip)) {
  122. continue;
  123. }
  124. if ($io->isDir()) {
  125. $langs->push(['code' => $name, 'name' => locale_get_display_name($name)]);
  126. }
  127. }
  128. $res['available_languages'] = $langs->sortBy('name')->values();
  129. $res['primary_locale'] = config('app.locale');
  130. $submissionState = Http::withoutVerifying()
  131. ->post('https://pixelfed.org/api/v1/directory/check-submission', [
  132. 'domain' => config('pixelfed.domain.app'),
  133. ]);
  134. $res['submission_state'] = $submissionState->json();
  135. return $res;
  136. }
  137. protected function validVal($res, $val, $count = false, $minLen = false)
  138. {
  139. if (! isset($res[$val])) {
  140. return false;
  141. }
  142. if ($count) {
  143. return count($res[$val]) >= $count;
  144. }
  145. if ($minLen) {
  146. return strlen($res[$val]) >= $minLen;
  147. }
  148. return $res[$val];
  149. }
  150. public function directoryStore(Request $request)
  151. {
  152. $this->validate($request, [
  153. 'location' => 'string|min:1|max:53',
  154. 'summary' => 'string|nullable|max:140',
  155. 'admin_uid' => 'sometimes|nullable',
  156. 'contact_email' => 'sometimes|nullable|email:rfc,dns',
  157. 'favourite_posts' => 'array|max:12',
  158. 'favourite_posts.*' => 'distinct',
  159. 'privacy_pledge' => 'sometimes',
  160. 'banner_image' => 'sometimes|mimes:jpg,png|dimensions:width=1920,height:1080|max:5000',
  161. ]);
  162. $config = ConfigCache::firstOrNew([
  163. 'k' => 'pixelfed.directory',
  164. ]);
  165. $res = $config->v ? json_decode($config->v, true) : [];
  166. $res['summary'] = strip_tags($request->input('summary'));
  167. $res['favourite_posts'] = $request->input('favourite_posts');
  168. $res['admin'] = (string) $request->input('admin_uid');
  169. $res['contact_email'] = $request->input('contact_email');
  170. $res['privacy_pledge'] = (bool) $request->input('privacy_pledge');
  171. if ($request->filled('location')) {
  172. $exists = (new ISO3166)->name($request->location);
  173. if ($exists) {
  174. $res['location'] = $request->input('location');
  175. }
  176. }
  177. if ($request->hasFile('banner_image')) {
  178. collect(Storage::files('public/headers'))
  179. ->filter(function ($name) {
  180. $protected = [
  181. 'public/headers/.gitignore',
  182. 'public/headers/default.jpg',
  183. 'public/headers/missing.png',
  184. ];
  185. return ! in_array($name, $protected);
  186. })
  187. ->each(function ($name) {
  188. Storage::delete($name);
  189. });
  190. $path = $request->file('banner_image')->storePublicly('public/headers');
  191. $res['banner_image'] = $path;
  192. ConfigCacheService::put('app.banner_image', url(Storage::url($path)));
  193. Cache::forget('api:v1:instance-data-response-v1');
  194. }
  195. $config->v = json_encode($res);
  196. $config->save();
  197. ConfigCacheService::put('pixelfed.directory', $config->v);
  198. $updated = json_decode($config->v, true);
  199. if (isset($updated['banner_image'])) {
  200. $updated['banner_image'] = url(Storage::url($updated['banner_image']));
  201. }
  202. return $updated;
  203. }
  204. public function directoryHandleServerSubmission(Request $request)
  205. {
  206. $reqs = [];
  207. $reqs['feature_config'] = [
  208. 'open_registration' => (bool) config_cache('pixelfed.open_registration'),
  209. 'curated_onboarding' => (bool) config_cache('instance.curated_registration.enabled'),
  210. 'activitypub_enabled' => config_cache('federation.activitypub.enabled'),
  211. 'oauth_enabled' => (bool) config_cache('pixelfed.oauth_enabled'),
  212. 'media_types' => Str::of(config_cache('pixelfed.media_types'))->explode(','),
  213. 'image_quality' => config_cache('pixelfed.image_quality'),
  214. 'optimize_image' => config_cache('pixelfed.optimize_image'),
  215. 'max_photo_size' => config_cache('pixelfed.max_photo_size'),
  216. 'max_caption_length' => config_cache('pixelfed.max_caption_length'),
  217. 'max_altext_length' => config_cache('pixelfed.max_altext_length'),
  218. 'enforce_account_limit' => config_cache('pixelfed.enforce_account_limit'),
  219. 'max_account_size' => config_cache('pixelfed.max_account_size'),
  220. 'max_album_length' => config_cache('pixelfed.max_album_length'),
  221. 'account_deletion' => config_cache('pixelfed.account_deletion'),
  222. ];
  223. $validator = Validator::make($reqs['feature_config'], [
  224. 'open_registration' => 'required_unless:curated_onboarding,true',
  225. 'curated_onboarding' => 'required_unless:open_registration,true',
  226. 'activitypub_enabled' => 'required|accepted',
  227. 'oauth_enabled' => 'required|accepted',
  228. 'media_types' => [
  229. 'required',
  230. function ($attribute, $value, $fail) {
  231. if (! in_array('image/jpeg', $value->toArray()) || ! in_array('image/png', $value->toArray())) {
  232. $fail('You must enable image/jpeg and image/png support.');
  233. }
  234. },
  235. ],
  236. 'image_quality' => 'required_if:optimize_image,true|integer|min:75|max:100',
  237. 'max_altext_length' => 'required|integer|min:1000|max:5000',
  238. 'max_photo_size' => 'required|integer|min:15000|max:100000',
  239. 'max_account_size' => 'required_if:enforce_account_limit,true|integer|min:1000000',
  240. 'max_album_length' => 'required|integer|min:4|max:20',
  241. 'account_deletion' => 'required|accepted',
  242. 'max_caption_length' => 'required|integer|min:500|max:10000',
  243. ]);
  244. if (! $validator->validate()) {
  245. return response()->json($validator->errors(), 422);
  246. }
  247. ConfigCacheService::put('pixelfed.directory.submission-key', Str::random(random_int(40, 69)));
  248. ConfigCacheService::put('pixelfed.directory.submission-ts', now());
  249. $data = (new PixelfedDirectoryController())->buildListing();
  250. $res = Http::withoutVerifying()->post('https://pixelfed.org/api/v1/directory/submission', $data);
  251. return 200;
  252. }
  253. public function directoryDeleteBannerImage(Request $request)
  254. {
  255. $bannerImage = ConfigCache::whereK('app.banner_image')->first();
  256. $directory = ConfigCache::whereK('pixelfed.directory')->first();
  257. if (! $bannerImage && ! $directory || empty($directory->v)) {
  258. return;
  259. }
  260. $directoryArr = json_decode($directory->v, true);
  261. $path = isset($directoryArr['banner_image']) ? $directoryArr['banner_image'] : false;
  262. $protected = [
  263. 'public/headers/.gitignore',
  264. 'public/headers/default.jpg',
  265. 'public/headers/missing.png',
  266. ];
  267. if (! $path || in_array($path, $protected)) {
  268. return;
  269. }
  270. if (Storage::exists($directoryArr['banner_image'])) {
  271. Storage::delete($directoryArr['banner_image']);
  272. }
  273. $directoryArr['banner_image'] = 'public/headers/default.jpg';
  274. $directory->v = $directoryArr;
  275. $directory->save();
  276. $bannerImage->v = url(Storage::url('public/headers/default.jpg'));
  277. $bannerImage->save();
  278. Cache::forget('api:v1:instance-data-response-v1');
  279. ConfigCacheService::put('pixelfed.directory', $directory);
  280. return $bannerImage->v;
  281. }
  282. public function directoryGetPopularPosts(Request $request)
  283. {
  284. $ids = Cache::remember('admin:api:popular_posts', 86400, function () {
  285. return Status::whereLocal(true)
  286. ->whereScope('public')
  287. ->whereType('photo')
  288. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  289. ->orderByDesc('likes_count')
  290. ->take(50)
  291. ->pluck('id');
  292. });
  293. $res = $ids->map(function ($id) {
  294. return StatusService::get($id);
  295. })
  296. ->filter(function ($post) {
  297. return $post && isset($post['account']);
  298. })
  299. ->values();
  300. return response()->json($res, 200, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  301. }
  302. public function directoryGetAddPostByIdSearch(Request $request)
  303. {
  304. $this->validate($request, [
  305. 'q' => 'required|integer',
  306. ]);
  307. $id = $request->input('q');
  308. $status = Status::whereLocal(true)
  309. ->whereType('photo')
  310. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  311. ->findOrFail($id);
  312. $res = StatusService::get($status->id);
  313. return $res;
  314. }
  315. public function directoryDeleteTestimonial(Request $request)
  316. {
  317. $this->validate($request, [
  318. 'profile_id' => 'required',
  319. ]);
  320. $profile_id = $request->input('profile_id');
  321. $testimonials = ConfigCache::whereK('pixelfed.directory.testimonials')->firstOrFail();
  322. $existing = collect(json_decode($testimonials->v, true))
  323. ->filter(function ($t) use ($profile_id) {
  324. return $t['profile_id'] !== $profile_id;
  325. })
  326. ->values();
  327. ConfigCacheService::put('pixelfed.directory.testimonials', $existing);
  328. return $existing;
  329. }
  330. public function directorySaveTestimonial(Request $request)
  331. {
  332. $this->validate($request, [
  333. 'username' => 'required',
  334. 'body' => 'required|string|min:5|max:500',
  335. ]);
  336. $user = User::whereUsername($request->input('username'))->whereNull('status')->firstOrFail();
  337. $configCache = ConfigCache::firstOrCreate([
  338. 'k' => 'pixelfed.directory.testimonials',
  339. ]);
  340. $testimonials = $configCache->v ? collect(json_decode($configCache->v, true)) : collect([]);
  341. abort_if($testimonials->contains('profile_id', $user->profile_id), 422, 'Testimonial already exists');
  342. abort_if($testimonials->count() == 10, 422, 'You can only have 10 active testimonials');
  343. $testimonials->push([
  344. 'profile_id' => (string) $user->profile_id,
  345. 'username' => $request->input('username'),
  346. 'body' => $request->input('body'),
  347. ]);
  348. $configCache->v = json_encode($testimonials->toArray());
  349. $configCache->save();
  350. ConfigCacheService::put('pixelfed.directory.testimonials', $configCache->v);
  351. $res = [
  352. 'profile' => AccountService::get($user->profile_id),
  353. 'body' => $request->input('body'),
  354. ];
  355. return $res;
  356. }
  357. public function directoryUpdateTestimonial(Request $request)
  358. {
  359. $this->validate($request, [
  360. 'profile_id' => 'required',
  361. 'body' => 'required|string|min:5|max:500',
  362. ]);
  363. $profile_id = $request->input('profile_id');
  364. $body = $request->input('body');
  365. $user = User::whereProfileId($profile_id)->firstOrFail();
  366. $configCache = ConfigCache::firstOrCreate([
  367. 'k' => 'pixelfed.directory.testimonials',
  368. ]);
  369. $testimonials = $configCache->v ? collect(json_decode($configCache->v, true)) : collect([]);
  370. $updated = $testimonials->map(function ($t) use ($profile_id, $body) {
  371. if ($t['profile_id'] == $profile_id) {
  372. $t['body'] = $body;
  373. }
  374. return $t;
  375. })
  376. ->values();
  377. $configCache->v = json_encode($updated);
  378. $configCache->save();
  379. ConfigCacheService::put('pixelfed.directory.testimonials', $configCache->v);
  380. return $updated;
  381. }
  382. }