ApiV1Dot1Controller.php 25 KB

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