ApiV1Dot1Controller.php 24 KB

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