ApiV1Dot1Controller.php 24 KB

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