ApiV1Dot1Controller.php 24 KB

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