ApiV1Dot1Controller.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Cache;
  4. use DB;
  5. use App\Http\Controllers\Controller;
  6. use Illuminate\Http\Request;
  7. use League\Fractal;
  8. use League\Fractal\Serializer\ArraySerializer;
  9. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  10. use App\AccountLog;
  11. use App\EmailVerification;
  12. use App\Place;
  13. use App\Status;
  14. use App\Report;
  15. use App\Profile;
  16. use App\StatusArchived;
  17. use App\User;
  18. use App\Services\AccountService;
  19. use App\Services\StatusService;
  20. use App\Services\ProfileStatusService;
  21. use App\Services\PublicTimelineService;
  22. use App\Services\NetworkTimelineService;
  23. use App\Util\Lexer\RestrictedNames;
  24. use App\Services\BouncerService;
  25. use App\Services\EmailService;
  26. use Illuminate\Support\Str;
  27. use Illuminate\Support\Facades\Hash;
  28. use Jenssegers\Agent\Agent;
  29. use Mail;
  30. use App\Mail\PasswordChange;
  31. use App\Mail\ConfirmAppEmail;
  32. use App\Http\Resources\StatusStateless;
  33. use App\Jobs\StatusPipeline\StatusDelete;
  34. use App\Jobs\ReportPipeline\ReportNotifyAdminViaEmail;
  35. use Illuminate\Support\Facades\RateLimiter;
  36. class ApiV1Dot1Controller extends Controller
  37. {
  38. protected $fractal;
  39. public function __construct()
  40. {
  41. $this->fractal = new Fractal\Manager();
  42. $this->fractal->setSerializer(new ArraySerializer());
  43. }
  44. public function json($res, $code = 200, $headers = [])
  45. {
  46. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  47. }
  48. public function error($msg, $code = 400, $extra = [], $headers = [])
  49. {
  50. $res = [
  51. "msg" => $msg,
  52. "code" => $code
  53. ];
  54. return response()->json(array_merge($res, $extra), $code, $headers, JSON_UNESCAPED_SLASHES);
  55. }
  56. public function report(Request $request)
  57. {
  58. $user = $request->user();
  59. abort_if(!$user, 403);
  60. abort_if($user->status != null, 403);
  61. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  62. abort_if(BouncerService::checkIp($request->ip()), 404);
  63. }
  64. $report_type = $request->input('report_type');
  65. $object_id = $request->input('object_id');
  66. $object_type = $request->input('object_type');
  67. $types = [
  68. 'spam',
  69. 'sensitive',
  70. 'abusive',
  71. 'underage',
  72. 'violence',
  73. 'copyright',
  74. 'impersonation',
  75. 'scam',
  76. 'terrorism'
  77. ];
  78. if (!$report_type || !$object_id || !$object_type) {
  79. return $this->error("Invalid or missing parameters", 400, ["error_code" => "ERROR_INVALID_PARAMS"]);
  80. }
  81. if (!in_array($report_type, $types)) {
  82. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_TYPE_INVALID"]);
  83. }
  84. if ($object_type === "user" && $object_id == $user->profile_id) {
  85. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  86. }
  87. $rpid = null;
  88. switch ($object_type) {
  89. case 'post':
  90. $object = Status::find($object_id);
  91. if (!$object) {
  92. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  93. }
  94. $object_type = 'App\Status';
  95. $exists = Report::whereUserId($user->id)
  96. ->whereObjectId($object->id)
  97. ->whereObjectType('App\Status')
  98. ->count();
  99. $rpid = $object->profile_id;
  100. break;
  101. case 'user':
  102. $object = Profile::find($object_id);
  103. if (!$object) {
  104. return $this->error("Invalid object id", 400, ["error_code" => "ERROR_INVALID_OBJECT_ID"]);
  105. }
  106. $object_type = 'App\Profile';
  107. $exists = Report::whereUserId($user->id)
  108. ->whereObjectId($object->id)
  109. ->whereObjectType('App\Profile')
  110. ->count();
  111. $rpid = $object->id;
  112. break;
  113. default:
  114. return $this->error("Invalid report type", 400, ["error_code" => "ERROR_REPORT_OBJECT_TYPE_INVALID"]);
  115. break;
  116. }
  117. if ($exists !== 0) {
  118. return $this->error("Duplicate report", 400, ["error_code" => "ERROR_REPORT_DUPLICATE"]);
  119. }
  120. if ($object->profile_id == $user->profile_id) {
  121. return $this->error("Cannot self report", 400, ["error_code" => "ERROR_NO_SELF_REPORTS"]);
  122. }
  123. $report = new Report;
  124. $report->profile_id = $user->profile_id;
  125. $report->user_id = $user->id;
  126. $report->object_id = $object->id;
  127. $report->object_type = $object_type;
  128. $report->reported_profile_id = $rpid;
  129. $report->type = $report_type;
  130. $report->save();
  131. if(config('instance.reports.email.enabled')) {
  132. ReportNotifyAdminViaEmail::dispatch($report)->onQueue('default');
  133. }
  134. $res = [
  135. "msg" => "Successfully sent report",
  136. "code" => 200
  137. ];
  138. return $this->json($res);
  139. }
  140. /**
  141. * DELETE /api/v1.1/accounts/avatar
  142. *
  143. * @return \App\Transformer\Api\AccountTransformer
  144. */
  145. public function deleteAvatar(Request $request)
  146. {
  147. $user = $request->user();
  148. abort_if(!$user, 403);
  149. abort_if($user->status != null, 403);
  150. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  151. abort_if(BouncerService::checkIp($request->ip()), 404);
  152. }
  153. $avatar = $user->profile->avatar;
  154. if( $avatar->media_path == 'public/avatars/default.png' ||
  155. $avatar->media_path == 'public/avatars/default.jpg'
  156. ) {
  157. return AccountService::get($user->profile_id);
  158. }
  159. if(is_file(storage_path('app/' . $avatar->media_path))) {
  160. @unlink(storage_path('app/' . $avatar->media_path));
  161. }
  162. $avatar->media_path = 'public/avatars/default.jpg';
  163. $avatar->change_count = $avatar->change_count + 1;
  164. $avatar->save();
  165. Cache::forget('avatar:' . $user->profile_id);
  166. Cache::forget("avatar:{$user->profile_id}");
  167. Cache::forget('user:account:id:'.$user->id);
  168. AccountService::del($user->profile_id);
  169. return AccountService::get($user->profile_id);
  170. }
  171. /**
  172. * GET /api/v1.1/accounts/{id}/posts
  173. *
  174. * @return \App\Transformer\Api\StatusTransformer
  175. */
  176. public function accountPosts(Request $request, $id)
  177. {
  178. $user = $request->user();
  179. abort_if(!$user, 403);
  180. abort_if($user->status != null, 403);
  181. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  182. abort_if(BouncerService::checkIp($request->ip()), 404);
  183. }
  184. $account = AccountService::get($id);
  185. if(!$account || $account['username'] !== $request->input('username')) {
  186. return $this->json([]);
  187. }
  188. $posts = ProfileStatusService::get($id);
  189. if(!$posts) {
  190. return $this->json([]);
  191. }
  192. $res = collect($posts)
  193. ->map(function($id) {
  194. return StatusService::get($id);
  195. })
  196. ->filter(function($post) {
  197. return $post && isset($post['account']);
  198. })
  199. ->toArray();
  200. return $this->json($res);
  201. }
  202. /**
  203. * POST /api/v1.1/accounts/change-password
  204. *
  205. * @return \App\Transformer\Api\AccountTransformer
  206. */
  207. public function accountChangePassword(Request $request)
  208. {
  209. $user = $request->user();
  210. abort_if(!$user, 403);
  211. abort_if($user->status != null, 403);
  212. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  213. abort_if(BouncerService::checkIp($request->ip()), 404);
  214. }
  215. $this->validate($request, [
  216. 'current_password' => 'bail|required|current_password',
  217. 'new_password' => 'required|min:' . config('pixelfed.min_password_length', 8),
  218. 'confirm_password' => 'required|same:new_password'
  219. ],[
  220. 'current_password' => 'The password you entered is incorrect'
  221. ]);
  222. $user->password = bcrypt($request->input('new_password'));
  223. $user->save();
  224. $log = new AccountLog;
  225. $log->user_id = $user->id;
  226. $log->item_id = $user->id;
  227. $log->item_type = 'App\User';
  228. $log->action = 'account.edit.password';
  229. $log->message = 'Password changed';
  230. $log->link = null;
  231. $log->ip_address = $request->ip();
  232. $log->user_agent = $request->userAgent();
  233. $log->save();
  234. Mail::to($request->user())->send(new PasswordChange($user));
  235. return $this->json(AccountService::get($user->profile_id));
  236. }
  237. /**
  238. * GET /api/v1.1/accounts/login-activity
  239. *
  240. * @return array
  241. */
  242. public function accountLoginActivity(Request $request)
  243. {
  244. $user = $request->user();
  245. abort_if(!$user, 403);
  246. abort_if($user->status != null, 403);
  247. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  248. abort_if(BouncerService::checkIp($request->ip()), 404);
  249. }
  250. $agent = new Agent();
  251. $currentIp = $request->ip();
  252. $activity = AccountLog::whereUserId($user->id)
  253. ->whereAction('auth.login')
  254. ->orderBy('created_at', 'desc')
  255. ->groupBy('ip_address')
  256. ->limit(10)
  257. ->get()
  258. ->map(function($item) use($agent, $currentIp) {
  259. $agent->setUserAgent($item->user_agent);
  260. return [
  261. 'id' => $item->id,
  262. 'action' => $item->action,
  263. 'ip' => $item->ip_address,
  264. 'ip_current' => $item->ip_address === $currentIp,
  265. 'is_mobile' => $agent->isMobile(),
  266. 'device' => $agent->device(),
  267. 'browser' => $agent->browser(),
  268. 'platform' => $agent->platform(),
  269. 'created_at' => $item->created_at->format('c')
  270. ];
  271. });
  272. return $this->json($activity);
  273. }
  274. /**
  275. * GET /api/v1.1/accounts/two-factor
  276. *
  277. * @return array
  278. */
  279. public function accountTwoFactor(Request $request)
  280. {
  281. $user = $request->user();
  282. abort_if(!$user, 403);
  283. abort_if($user->status != null, 403);
  284. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  285. abort_if(BouncerService::checkIp($request->ip()), 404);
  286. }
  287. $res = [
  288. 'active' => (bool) $user->{'2fa_enabled'},
  289. 'setup_at' => $user->{'2fa_setup_at'}
  290. ];
  291. return $this->json($res);
  292. }
  293. /**
  294. * GET /api/v1.1/accounts/emails-from-pixelfed
  295. *
  296. * @return array
  297. */
  298. public function accountEmailsFromPixelfed(Request $request)
  299. {
  300. $user = $request->user();
  301. abort_if(!$user, 403);
  302. abort_if($user->status != null, 403);
  303. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  304. abort_if(BouncerService::checkIp($request->ip()), 404);
  305. }
  306. $from = config('mail.from.address');
  307. $emailVerifications = EmailVerification::whereUserId($user->id)
  308. ->orderByDesc('id')
  309. ->where('created_at', '>', now()->subDays(14))
  310. ->limit(10)
  311. ->get()
  312. ->map(function($mail) use($user, $from) {
  313. return [
  314. 'type' => 'Email Verification',
  315. 'subject' => 'Confirm Email',
  316. 'to_address' => $user->email,
  317. 'from_address' => $from,
  318. 'created_at' => str_replace('@', 'at', $mail->created_at->format('M j, Y @ g:i:s A'))
  319. ];
  320. })
  321. ->toArray();
  322. $passwordResets = DB::table('password_resets')
  323. ->whereEmail($user->email)
  324. ->where('created_at', '>', now()->subDays(14))
  325. ->orderByDesc('created_at')
  326. ->limit(10)
  327. ->get()
  328. ->map(function($mail) use($user, $from) {
  329. return [
  330. 'type' => 'Password Reset',
  331. 'subject' => 'Reset Password Notification',
  332. 'to_address' => $user->email,
  333. 'from_address' => $from,
  334. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  335. ];
  336. })
  337. ->toArray();
  338. $passwordChanges = AccountLog::whereUserId($user->id)
  339. ->whereAction('account.edit.password')
  340. ->where('created_at', '>', now()->subDays(14))
  341. ->orderByDesc('created_at')
  342. ->limit(10)
  343. ->get()
  344. ->map(function($mail) use($user, $from) {
  345. return [
  346. 'type' => 'Password Change',
  347. 'subject' => 'Password Change',
  348. 'to_address' => $user->email,
  349. 'from_address' => $from,
  350. 'created_at' => str_replace('@', 'at', now()->parse($mail->created_at)->format('M j, Y @ g:i:s A'))
  351. ];
  352. })
  353. ->toArray();
  354. $res = collect([])
  355. ->merge($emailVerifications)
  356. ->merge($passwordResets)
  357. ->merge($passwordChanges)
  358. ->sortByDesc('created_at')
  359. ->values();
  360. return $this->json($res);
  361. }
  362. /**
  363. * GET /api/v1.1/accounts/apps-and-applications
  364. *
  365. * @return array
  366. */
  367. public function accountApps(Request $request)
  368. {
  369. $user = $request->user();
  370. abort_if(!$user, 403);
  371. abort_if($user->status != null, 403);
  372. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  373. abort_if(BouncerService::checkIp($request->ip()), 404);
  374. }
  375. $res = $user->tokens->sortByDesc('created_at')->take(10)->map(function($token, $key) use($request) {
  376. return [
  377. 'id' => $token->id,
  378. 'current_session' => $request->user()->token()->id == $token->id,
  379. 'name' => $token->client->name,
  380. 'scopes' => $token->scopes,
  381. 'revoked' => $token->revoked,
  382. 'created_at' => str_replace('@', 'at', now()->parse($token->created_at)->format('M j, Y @ g:i:s A')),
  383. 'expires_at' => str_replace('@', 'at', now()->parse($token->expires_at)->format('M j, Y @ g:i:s A'))
  384. ];
  385. });
  386. return $this->json($res);
  387. }
  388. public function inAppRegistrationPreFlightCheck(Request $request)
  389. {
  390. return [
  391. 'open' => (bool) config_cache('pixelfed.open_registration'),
  392. 'iara' => config('pixelfed.allow_app_registration')
  393. ];
  394. }
  395. public function inAppRegistration(Request $request)
  396. {
  397. abort_if($request->user(), 404);
  398. abort_unless(config_cache('pixelfed.open_registration'), 404);
  399. abort_unless(config('pixelfed.allow_app_registration'), 404);
  400. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  401. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  402. abort_if(BouncerService::checkIp($request->ip()), 404);
  403. }
  404. $rl = RateLimiter::attempt('pf:apiv1.1:iar:'.$request->ip(), 3, function(){}, 1800);
  405. abort_if(!$rl, 400, 'Too many requests');
  406. $this->validate($request, [
  407. 'email' => [
  408. 'required',
  409. 'string',
  410. 'email',
  411. 'max:255',
  412. 'unique:users',
  413. function ($attribute, $value, $fail) {
  414. $banned = EmailService::isBanned($value);
  415. if($banned) {
  416. return $fail('Email is invalid.');
  417. }
  418. },
  419. ],
  420. 'username' => [
  421. 'required',
  422. 'min:2',
  423. 'max:15',
  424. 'unique:users',
  425. function ($attribute, $value, $fail) {
  426. $dash = substr_count($value, '-');
  427. $underscore = substr_count($value, '_');
  428. $period = substr_count($value, '.');
  429. if(ends_with($value, ['.php', '.js', '.css'])) {
  430. return $fail('Username is invalid.');
  431. }
  432. if(($dash + $underscore + $period) > 1) {
  433. return $fail('Username is invalid. Can only contain one dash (-), period (.) or underscore (_).');
  434. }
  435. if (!ctype_alnum($value[0])) {
  436. return $fail('Username is invalid. Must start with a letter or number.');
  437. }
  438. if (!ctype_alnum($value[strlen($value) - 1])) {
  439. return $fail('Username is invalid. Must end with a letter or number.');
  440. }
  441. $val = str_replace(['_', '.', '-'], '', $value);
  442. if(!ctype_alnum($val)) {
  443. return $fail('Username is invalid. Username must be alpha-numeric and may contain dashes (-), periods (.) and underscores (_).');
  444. }
  445. $restricted = RestrictedNames::get();
  446. if (in_array(strtolower($value), array_map('strtolower', $restricted))) {
  447. return $fail('Username cannot be used.');
  448. }
  449. },
  450. ],
  451. 'password' => 'required|string|min:8',
  452. ]);
  453. $email = $request->input('email');
  454. $username = $request->input('username');
  455. $password = $request->input('password');
  456. if(config('database.default') == 'pgsql') {
  457. $username = strtolower($username);
  458. $email = strtolower($email);
  459. }
  460. $user = new User;
  461. $user->name = $username;
  462. $user->username = $username;
  463. $user->email = $email;
  464. $user->password = Hash::make($password);
  465. $user->register_source = 'app';
  466. $user->app_register_ip = $request->ip();
  467. $user->app_register_token = Str::random(32);
  468. $user->save();
  469. $rtoken = Str::random(mt_rand(64, 70));
  470. $verify = new EmailVerification();
  471. $verify->user_id = $user->id;
  472. $verify->email = $user->email;
  473. $verify->user_token = $user->app_register_token;
  474. $verify->random_token = $rtoken;
  475. $verify->save();
  476. $appUrl = url('/api/v1.1/auth/iarer?ut=' . $user->app_register_token . '&rt=' . $rtoken);
  477. Mail::to($user->email)->send(new ConfirmAppEmail($verify, $appUrl));
  478. return response()->json([
  479. 'success' => true,
  480. ]);
  481. }
  482. public function inAppRegistrationEmailRedirect(Request $request)
  483. {
  484. $this->validate($request, [
  485. 'ut' => 'required',
  486. 'rt' => 'required'
  487. ]);
  488. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  489. abort_if(BouncerService::checkIp($request->ip()), 404);
  490. }
  491. $ut = $request->input('ut');
  492. $rt = $request->input('rt');
  493. $url = 'pixelfed://confirm-account/'. $ut . '?rt=' . $rt;
  494. return redirect()->away($url);
  495. }
  496. public function inAppRegistrationConfirm(Request $request)
  497. {
  498. abort_if($request->user(), 404);
  499. abort_unless(config_cache('pixelfed.open_registration'), 404);
  500. abort_unless(config('pixelfed.allow_app_registration'), 404);
  501. abort_unless($request->hasHeader('X-PIXELFED-APP'), 403);
  502. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  503. abort_if(BouncerService::checkIp($request->ip()), 404);
  504. }
  505. $rl = RateLimiter::attempt('pf:apiv1.1:iarc:'.$request->ip(), 10, function(){}, 1800);
  506. abort_if(!$rl, 400, 'Too many requests');
  507. $this->validate($request, [
  508. 'user_token' => 'required',
  509. 'random_token' => 'required',
  510. 'email' => 'required'
  511. ]);
  512. $verify = EmailVerification::whereEmail($request->input('email'))
  513. ->whereUserToken($request->input('user_token'))
  514. ->whereRandomToken($request->input('random_token'))
  515. ->first();
  516. if(!$verify) {
  517. return response()->json(['error' => 'Invalid tokens'], 403);
  518. }
  519. if($verify->created_at->lt(now()->subHours(24))) {
  520. $verify->delete();
  521. return response()->json(['error' => 'Invalid tokens'], 403);
  522. }
  523. $user = User::findOrFail($verify->user_id);
  524. $user->email_verified_at = now();
  525. $user->last_active_at = now();
  526. $user->save();
  527. $token = $user->createToken('Pixelfed');
  528. return response()->json([
  529. 'access_token' => $token->accessToken
  530. ]);
  531. }
  532. public function archive(Request $request, $id)
  533. {
  534. abort_if(!$request->user(), 403);
  535. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  536. abort_if(BouncerService::checkIp($request->ip()), 404);
  537. }
  538. $status = Status::whereNull('in_reply_to_id')
  539. ->whereNull('reblog_of_id')
  540. ->whereProfileId($request->user()->profile_id)
  541. ->findOrFail($id);
  542. if($status->scope === 'archived') {
  543. return [200];
  544. }
  545. $archive = new StatusArchived;
  546. $archive->status_id = $status->id;
  547. $archive->profile_id = $status->profile_id;
  548. $archive->original_scope = $status->scope;
  549. $archive->save();
  550. $status->scope = 'archived';
  551. $status->visibility = 'draft';
  552. $status->save();
  553. StatusService::del($status->id, true);
  554. AccountService::syncPostCount($status->profile_id);
  555. return [200];
  556. }
  557. public function unarchive(Request $request, $id)
  558. {
  559. abort_if(!$request->user(), 403);
  560. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  561. abort_if(BouncerService::checkIp($request->ip()), 404);
  562. }
  563. $status = Status::whereNull('in_reply_to_id')
  564. ->whereNull('reblog_of_id')
  565. ->whereProfileId($request->user()->profile_id)
  566. ->findOrFail($id);
  567. if($status->scope !== 'archived') {
  568. return [200];
  569. }
  570. $archive = StatusArchived::whereStatusId($status->id)
  571. ->whereProfileId($status->profile_id)
  572. ->firstOrFail();
  573. $status->scope = $archive->original_scope;
  574. $status->visibility = $archive->original_scope;
  575. $status->save();
  576. $archive->delete();
  577. StatusService::del($status->id, true);
  578. AccountService::syncPostCount($status->profile_id);
  579. return [200];
  580. }
  581. public function archivedPosts(Request $request)
  582. {
  583. abort_if(!$request->user(), 403);
  584. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  585. abort_if(BouncerService::checkIp($request->ip()), 404);
  586. }
  587. $statuses = Status::whereProfileId($request->user()->profile_id)
  588. ->whereScope('archived')
  589. ->orderByDesc('id')
  590. ->cursorPaginate(10);
  591. return StatusStateless::collection($statuses);
  592. }
  593. public function placesById(Request $request, $id, $slug)
  594. {
  595. abort_if(!$request->user(), 403);
  596. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  597. abort_if(BouncerService::checkIp($request->ip()), 404);
  598. }
  599. $place = Place::whereSlug($slug)->findOrFail($id);
  600. $posts = Cache::remember('pf-api:v1.1:places-by-id:' . $place->id, 3600, function() use($place) {
  601. return Status::wherePlaceId($place->id)
  602. ->whereNull('uri')
  603. ->whereScope('public')
  604. ->orderByDesc('created_at')
  605. ->limit(60)
  606. ->pluck('id');
  607. });
  608. $posts = $posts->map(function($id) {
  609. return StatusService::get($id);
  610. })
  611. ->filter()
  612. ->values();
  613. return [
  614. 'place' =>
  615. [
  616. 'id' => $place->id,
  617. 'name' => $place->name,
  618. 'slug' => $place->slug,
  619. 'country' => $place->country,
  620. 'lat' => $place->lat,
  621. 'long' => $place->long
  622. ],
  623. 'posts' => $posts];
  624. }
  625. public function moderatePost(Request $request, $id)
  626. {
  627. abort_if(!$request->user(), 403);
  628. abort_if($request->user()->is_admin != true, 403);
  629. if(config('pixelfed.bouncer.cloud_ips.ban_signups')) {
  630. abort_if(BouncerService::checkIp($request->ip()), 404);
  631. }
  632. $this->validate($request, [
  633. 'action' => 'required|in:cw,mark-public,mark-unlisted,mark-private,mark-spammer,delete'
  634. ]);
  635. $action = $request->input('action');
  636. $status = Status::find($id);
  637. if(!$status) {
  638. return response()->json(['error' => 'Cannot find status'], 400);
  639. }
  640. if($status->uri == null) {
  641. if($status->profile->user && $status->profile->user->is_admin) {
  642. return response()->json(['error' => 'Cannot moderate admin accounts'], 400);
  643. }
  644. }
  645. if($action == 'mark-spammer') {
  646. $status->profile->update([
  647. 'unlisted' => true,
  648. 'cw' => true,
  649. 'no_autolink' => true
  650. ]);
  651. Status::whereProfileId($status->profile_id)
  652. ->get()
  653. ->each(function($s) {
  654. if(in_array($s->scope, ['public', 'unlisted'])) {
  655. $s->scope = 'private';
  656. $s->visibility = 'private';
  657. }
  658. $s->is_nsfw = true;
  659. $s->save();
  660. StatusService::del($s->id, true);
  661. });
  662. Cache::forget('pf:bouncer_v0:exemption_by_pid:' . $status->profile_id);
  663. Cache::forget('pf:bouncer_v0:recent_by_pid:' . $status->profile_id);
  664. Cache::forget('admin-dash:reports:spam-count');
  665. } else if ($action == 'cw') {
  666. $state = $status->is_nsfw;
  667. $status->is_nsfw = !$state;
  668. $status->save();
  669. StatusService::del($status->id);
  670. } else if ($action == 'mark-public') {
  671. $state = $status->scope;
  672. $status->scope = 'public';
  673. $status->visibility = 'public';
  674. $status->save();
  675. StatusService::del($status->id, true);
  676. if($state !== 'public') {
  677. if($status->uri) {
  678. NetworkTimelineService::add($status->id);
  679. } else {
  680. PublicTimelineService::add($status->id);
  681. }
  682. }
  683. } else if ($action == 'mark-unlisted') {
  684. $state = $status->scope;
  685. $status->scope = 'unlisted';
  686. $status->visibility = 'unlisted';
  687. $status->save();
  688. StatusService::del($status->id);
  689. if($state == 'public') {
  690. PublicTimelineService::del($status->id);
  691. NetworkTimelineService::del($status->id);
  692. }
  693. } else if ($action == 'mark-private') {
  694. $state = $status->scope;
  695. $status->scope = 'private';
  696. $status->visibility = 'private';
  697. $status->save();
  698. StatusService::del($status->id);
  699. if($state == 'public') {
  700. PublicTimelineService::del($status->id);
  701. NetworkTimelineService::del($status->id);
  702. }
  703. } else if ($action == 'delete') {
  704. PublicTimelineService::del($status->id);
  705. NetworkTimelineService::del($status->id);
  706. Cache::forget('_api:statuses:recent_9:' . $status->profile_id);
  707. Cache::forget('profile:status_count:' . $status->profile_id);
  708. Cache::forget('profile:embed:' . $status->profile_id);
  709. StatusService::del($status->id, true);
  710. Cache::forget('profile:status_count:'.$status->profile_id);
  711. StatusDelete::dispatch($status);
  712. return [];
  713. }
  714. Cache::forget('_api:statuses:recent_9:'.$status->profile_id);
  715. return StatusService::get($status->id, false);
  716. }
  717. }