AdminDirectoryController.php 18 KB

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