diff --git a/composer.json b/composer.json index a0295b1..8100df7 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,9 @@ "symfony/translation": "4.3.*", "symfony/twig-bundle": "4.3.*", "symfony/yaml": "4.3.*", - "twig/extensions": "^1.5" + "twig/extensions": "^1.5", + "ext-curl": "*", + "ext-json": "*" }, "require-dev": { "symfony/web-server-bundle": "4.3.*" diff --git a/src/Controller/FediPlanController.php b/src/Controller/FediPlanController.php index 4f21cff..e284c70 100644 --- a/src/Controller/FediPlanController.php +++ b/src/Controller/FediPlanController.php @@ -1,4 +1,9 @@ -isGranted('IS_AUTHENTICATED_FULLY')){ + if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) { $local = $request->getSession()->get('_locale'); - return $this->redirect($this->generateUrl('schedule',['_locale' => $local])); + return $this->redirect($this->generateUrl('schedule', ['_locale' => $local])); } $client = new Client(); $flow->bind($client); @@ -50,25 +56,25 @@ class FediPlanController extends AbstractController $client_id = null; $client_secret = null; if ($flow->isValid($form)) { - if( $flow->getCurrentStep() == 1){ + if ($flow->getCurrentStep() == 1) { $host = $client->getHost(); $result = $mastodon_api->getInstanceNodeInfo($host); //We currently only support Mastodon accounts - if( $result != "MASTODON" && $result != "PLEROMA"){ - $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only',[],'fediplan','en'))); - }else{ + if ($result != "MASTODON" && $result != "PLEROMA") { + $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only', [], 'fediplan', 'en'))); + } else { $mastodon_api->set_url("https://" . $host); $mastodon_api->set_scopes([]); $createApp = $mastodon_api->create_app("FediPlan", [], '', "https://plan.fedilab.app"); - if( isset($createApp['error']) ){ - $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id',[],'fediplan','en'))); - }else{ + if (isset($createApp['error'])) { + $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id', [], 'fediplan', 'en'))); + } else { // form for the next step $mastodon_api->set_client($createApp['response']['client_id'], $createApp['response']['client_secret']); $urlToMastodon = $mastodon_api->getAuthorizationUrl(); - if( isset($createApp['error']) ){ - $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url',[],'fediplan','en'))); - }else{ + if (isset($createApp['error'])) { + $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url', [], 'fediplan', 'en'))); + } else { $flow->saveCurrentStepData($form); $client_id = $createApp['response']['client_id']; $client_secret = $createApp['response']['client_secret']; @@ -85,48 +91,24 @@ class FediPlanController extends AbstractController $mastodon_api->set_scopes([]); $mastodon_api->set_client($client->getClientId(), $client->getClientSecret()); $reply = $mastodon_api->loginAuthorization($code); - if( isset($reply['error']) ){ - - /* $access_token = $code; - $token_type = "Bearer"; - $mastodon_api->set_url("https://" . $client->getHost()); - $mastodon_api->set_token($access_token, $token_type); - try { - $accountReply = $mastodon_api->accounts_verify_credentials(); - } catch (\ErrorException $e) { - } - if( isset($accountReply['error']) ){ - $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account',[],'fediplan','en'))); - }else{ - $Account = $mastodon_api->getSingleAccount($accountReply['response']); - $Account->setInstance($host); - $Account->setToken($token_type ." ".$access_token); - $token = new UsernamePasswordToken($Account, null, 'main', array('ROLE_USER')); - $this->get('security.token_storage')->setToken($token); - $event = new InteractiveLoginEvent($request, $token); - $eventDispatcher->dispatch("security.interactive_login", $event); - return $this->redirectToRoute('schedule'); - }*/ - $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_token',[],'fediplan','en'))); - }else{ + if (isset($reply['error'])) { + $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_token', [], 'fediplan', 'en'))); + } else { $access_token = $reply['response']['access_token']; $token_type = $reply['response']['token_type']; $mastodon_api->set_url("https://" . $client->getHost()); $mastodon_api->set_token($access_token, $token_type); - try { - $accountReply = $mastodon_api->accounts_verify_credentials(); - } catch (\ErrorException $e) { - } - if( isset($accountReply['error']) ){ - $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account',[],'fediplan','en'))); - }else{ - $Account = $mastodon_api->getSingleAccount($accountReply['response']); + $accountReply = $mastodon_api->accounts_verify_credentials(); + if (isset($accountReply['error'])) { + $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account', [], 'fediplan', 'en'))); + } else { + $Account = $mastodon_api->getSingleAccount($accountReply['response']); $Account->setInstance($host); - $Account->setToken($token_type ." ".$access_token); + $Account->setToken($token_type . " " . $access_token); $token = new UsernamePasswordToken($Account, null, 'main', array('ROLE_USER')); $this->get('security.token_storage')->setToken($token); $event = new InteractiveLoginEvent($request, $token); - $eventDispatcher->dispatch("security.interactive_login", $event); + $eventDispatcher->dispatch($event, "security.interactive_login"); return $this->redirectToRoute('schedule'); } } @@ -168,58 +150,55 @@ class FediPlanController extends AbstractController /* @var $user MastodonAccount */ $user = $this->getUser(); $mastodon_api->set_url("https://" . $user->getInstance()); - - $token = explode(" " ,$user->getToken())[1]; + $token = explode(" ", $user->getToken())[1]; $type = explode(" ", $user->getToken())[0]; $mastodon_api->set_token($token, $type); $params = []; //Update media description and store their id - foreach ($_POST as $key => $value){ - if( $key != "compose"){ + foreach ($_POST as $key => $value) { + if ($key != "compose") { - if (strpos($key, 'media_id_') !== false){ + if (strpos($key, 'media_id_') !== false) { $mediaId = $value; - $description = $_POST['media_description_'.$mediaId]; + $description = $_POST['media_description_' . $mediaId]; //update description if needed - if( $description != null && trim($description) != ""){ - try { - $res = $mastodon_api->update_media($mediaId, ['description' => $description]); - } catch (\ErrorException $e) {} + if ($description != null && trim($description) != "") { + $mastodon_api->update_media($mediaId, ['description' => $description]); } $params['media_ids'][] = $mediaId; } } } //Schedule status - if( $data->getContentWarning() ){ + if ($data->getContentWarning()) { $params['spoiler_text'] = $data->getContentWarning(); } - if( $data->getContent() ){ + if ($data->getContent()) { $params['status'] = $data->getContent(); } - if( $data->getVisibility() ){ + if ($data->getVisibility()) { $params['visibility'] = $data->getVisibility(); } - $params['sensitive'] = ($data->getSensitive() == null || !$data->getSensitive())?false:true; + $params['sensitive'] = ($data->getSensitive() == null || !$data->getSensitive()) ? false : true; $pollOptions = $data->getPollOptions(); $pollExpiresAt = $data->getPollExpiresAt(); $isPollMultiple = $data->isPollMultiple(); - if( count($pollOptions) > 0){ + if (count($pollOptions) > 0) { $count_correct_values = 0; - foreach($pollOptions as $po) { + foreach ($pollOptions as $po) { /** @var $po PollOption */ - if( $po->getTitle() != null && strlen(trim($po->getTitle())) > 0){ + if ($po->getTitle() != null && strlen(trim($po->getTitle())) > 0) { $count_correct_values++; } } - if( $count_correct_values > 1 ){ + if ($count_correct_values > 1) { $params['poll']['options'] = []; - foreach($pollOptions as $po) { + foreach ($pollOptions as $po) { /** @var $po PollOption */ - if( $po->getTitle() != null && strlen(trim($po->getTitle())) > 0){ + if ($po->getTitle() != null && strlen(trim($po->getTitle())) > 0) { $params['poll']['options'][] = trim($po->getTitle()); } } @@ -228,22 +207,21 @@ class FediPlanController extends AbstractController } } try { - $date = new DateTime( $data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone()) ); - $date->setTimezone( new DateTimeZone("UTC")); + $date = new DateTime($data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone())); + $date->setTimezone(new DateTimeZone("UTC")); $params['scheduled_at'] = $date->format(DateTime::ISO8601); - } catch (\Exception $e) {} - try { - $response = $mastodon_api->post_statuses($params); - } catch (\ErrorException $e) {} + } catch (Exception $e) { + } + $response = $mastodon_api->post_statuses($params); $session = $request->getSession(); - if( isset($response['error']) ){ + if (isset($response['error'])) { $session->getFlashBag()->add( 'Error', $response['error_message'] ); - }else{ + } else { unset($compose); unset($form); $compose = new Compose(); @@ -263,11 +241,11 @@ class FediPlanController extends AbstractController $user = $this->getUser(); /** @var $user MastodonAccount */ - return $this->render("fediplan/schedule.html.twig",[ + return $this->render("fediplan/schedule.html.twig", [ 'form' => $form->createView(), 'instance' => $user->getInstance(), 'token' => $user->getToken(), - ]); + ]); } @@ -284,27 +262,19 @@ class FediPlanController extends AbstractController /** * @Route("/{_locale}/scheduled/messages/{max_id}", options={"expose"=true}, name="load_more") */ - public function loadMoreAction(Mastodon_api $mastodon_api, String $max_id = null){ - + public function loadMoreAction(Mastodon_api $mastodon_api, string $max_id = null) + { $user = $this->getUser(); - /** @var $mastodon_api Mastodon_api */ $mastodon_api->set_url("https://" . $user->getInstance()); - - $token = explode(" " ,$user->getToken())[1]; + $token = explode(" ", $user->getToken())[1]; $type = explode(" ", $user->getToken())[0]; $mastodon_api->set_token($token, $type); - $params = []; - - if( $max_id != null){ + if ($max_id != null) { $params['max_id'] = $max_id; } - $scheduled_reply = []; - try { - $scheduled_reply = $mastodon_api->get_scheduled($params); - } catch (\ErrorException $e) { - } + $scheduled_reply = $mastodon_api->get_scheduled($params); $statuses = $mastodon_api->getScheduledStatuses($scheduled_reply['response'], $this->getUser()); $data['max_id'] = $scheduled_reply['max_id']; $data['html'] = $this->renderView('fediplan/Ajax/layout.html.twig', ['statuses' => $statuses]); @@ -314,19 +284,14 @@ class FediPlanController extends AbstractController /** * @Route("/{_locale}/scheduled/delete/messages/{id}", options={"expose"=true}, name="delete_message", methods={"POST"}, defaults={"_locale"="en"}, requirements={"_locale": "%allowed_language%"}) */ - public function deleteMessage(Mastodon_api $mastodon_api, String $id = null){ - - + public function deleteMessage(Mastodon_api $mastodon_api, string $id = null) + { $user = $this->getUser(); - /** @var $mastodon_api Mastodon_api */ $mastodon_api->set_url("https://" . $user->getInstance()); - $token = explode(" " ,$user->getToken())[1]; + $token = explode(" ", $user->getToken())[1]; $type = explode(" ", $user->getToken())[0]; $mastodon_api->set_token($token, $type); - $response = []; - try { - $response = $mastodon_api->delete_scheduled($id); - } catch (\ErrorException $e) {} + $response = $mastodon_api->delete_scheduled($id); return new JsonResponse($response); } diff --git a/src/EventSubscriber/LocaleSubscriber.php b/src/EventSubscriber/LocaleSubscriber.php index 8565d62..6ee600c 100644 --- a/src/EventSubscriber/LocaleSubscriber.php +++ b/src/EventSubscriber/LocaleSubscriber.php @@ -22,6 +22,14 @@ class LocaleSubscriber implements EventSubscriberInterface $this->defaultLocale = $defaultLocale; } + public static function getSubscribedEvents() + { + return [ + // must be registered before (i.e. with a higher priority than) the default Locale listener + KernelEvents::REQUEST => [['onKernelRequest', 20]], + ]; + } + public function onKernelRequest(RequestEvent $event) { $request = $event->getRequest(); @@ -37,12 +45,4 @@ class LocaleSubscriber implements EventSubscriberInterface $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); } } - - public static function getSubscribedEvents() - { - return [ - // must be registered before (i.e. with a higher priority than) the default Locale listener - KernelEvents::REQUEST => [['onKernelRequest', 20]], - ]; - } } \ No newline at end of file diff --git a/src/Form/ComposeType.php b/src/Form/ComposeType.php index a4c969d..b73ae59 100644 --- a/src/Form/ComposeType.php +++ b/src/Form/ComposeType.php @@ -1,4 +1,5 @@ -getDefaultSensitivity()) { + if ($user->getDefaultSensitivity()) { $checkbox = [ 'required' => false, 'attr' => ['checked' => 'checked'], 'label' => 'page.schedule.form.sensitive', 'translation_domain' => 'fediplan' ]; - }else { + } else { $checkbox = ['required' => false, 'label' => 'page.schedule.form.sensitive', 'translation_domain' => 'fediplan']; } @@ -79,7 +81,7 @@ class ComposeType extends AbstractType { 'label' => 'page.schedule.form.timeZone', 'translation_domain' => 'fediplan']); $builder->add('sensitive', CheckboxType::class, $checkbox); - $builder->add('scheduled_at', DateTimeType::class,[ + $builder->add('scheduled_at', DateTimeType::class, [ 'widget' => 'single_text', "data" => new DateTime(), 'label' => 'page.schedule.form.scheduled_at', @@ -87,7 +89,7 @@ class ComposeType extends AbstractType { $builder->add('poll_options', CollectionType::class, [ - 'entry_type' => PollOptionType::class, + 'entry_type' => PollOptionType::class, 'by_reference' => false, 'allow_add' => true, 'prototype' => true, @@ -101,16 +103,16 @@ class ComposeType extends AbstractType { $builder->add('poll_expires_at', ChoiceType::class, [ 'choices' => [ - $this->translator->trans('poll.duration_m', ['minutes' => 5], 'fediplan') => 5*60, - $this->translator->trans('poll.duration_m', ['minutes' => 30], 'fediplan') => 30*60, - $this->translator->trans('poll.duration_h', ['hours' => 1], 'fediplan') => 60*60, - $this->translator->trans('poll.duration_h', ['hours' => 6], 'fediplan') => 6*60*60, - $this->translator->trans('poll.duration_d', ['days' => 1], 'fediplan') => 24*60*60, - $this->translator->trans('poll.duration_d', ['days' => 3], 'fediplan') => 3*24*60*60, - $this->translator->trans('poll.duration_d', ['days' => 7], 'fediplan') => 7*24*60*60, + $this->translator->trans('poll.duration_m', ['minutes' => 5], 'fediplan') => 5 * 60, + $this->translator->trans('poll.duration_m', ['minutes' => 30], 'fediplan') => 30 * 60, + $this->translator->trans('poll.duration_h', ['hours' => 1], 'fediplan') => 60 * 60, + $this->translator->trans('poll.duration_h', ['hours' => 6], 'fediplan') => 6 * 60 * 60, + $this->translator->trans('poll.duration_d', ['days' => 1], 'fediplan') => 24 * 60 * 60, + $this->translator->trans('poll.duration_d', ['days' => 3], 'fediplan') => 3 * 24 * 60 * 60, + $this->translator->trans('poll.duration_d', ['days' => 7], 'fediplan') => 7 * 24 * 60 * 60, ], - 'data' => 24*60*60, + 'data' => 24 * 60 * 60, 'required' => false, 'label' => 'page.schedule.form.end_in', 'translation_domain' => 'fediplan']); diff --git a/src/Form/ConnectMastodonAccountFlow.php b/src/Form/ConnectMastodonAccountFlow.php index de5d0eb..68521a9 100644 --- a/src/Form/ConnectMastodonAccountFlow.php +++ b/src/Form/ConnectMastodonAccountFlow.php @@ -11,9 +11,11 @@ namespace App\Form; use Craue\FormFlowBundle\Form\FormFlow; -class ConnectMastodonAccountFlow extends FormFlow { +class ConnectMastodonAccountFlow extends FormFlow +{ - protected function loadStepsConfig() { + protected function loadStepsConfig() + { return [ [ 'form_type' => ConnectMastodonAccountType::class, diff --git a/src/Form/ConnectMastodonAccountType.php b/src/Form/ConnectMastodonAccountType.php index a79594a..4b4c9b0 100644 --- a/src/Form/ConnectMastodonAccountType.php +++ b/src/Form/ConnectMastodonAccountType.php @@ -7,19 +7,22 @@ */ namespace App\Form; + use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; -class ConnectMastodonAccountType extends AbstractType { +class ConnectMastodonAccountType extends AbstractType +{ - public function buildForm(FormBuilderInterface $builder, array $options) { + public function buildForm(FormBuilderInterface $builder, array $options) + { switch ($options['flow_step']) { case 1: $builder->add('host', TextType::class, [ - 'label' => 'page.index.form.instance', + 'label' => 'page.index.form.instance', 'translation_domain' => 'fediplan' ]); break; @@ -35,7 +38,8 @@ class ConnectMastodonAccountType extends AbstractType { } } - public function getBlockPrefix() { + public function getBlockPrefix() + { return 'addMastodonAccount'; } diff --git a/src/Form/PollOptionType.php b/src/Form/PollOptionType.php index d5f70a5..7671b87 100644 --- a/src/Form/PollOptionType.php +++ b/src/Form/PollOptionType.php @@ -14,7 +14,8 @@ use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Security\Core\Security; -class PollOptionType extends AbstractType { +class PollOptionType extends AbstractType +{ private $securityContext; @@ -29,7 +30,7 @@ class PollOptionType extends AbstractType { $builder->add('title', TextType::class, [ 'required' => false, - 'attr'=> ['class'=>'form-control'], + 'attr' => ['class' => 'form-control'], 'label' => 'page.schedule.form.poll_item', ]); } diff --git a/src/Kernel.php b/src/Kernel.php index 785b0be..11636c2 100644 --- a/src/Kernel.php +++ b/src/Kernel.php @@ -8,6 +8,7 @@ use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\Routing\RouteCollectionBuilder; +use function dirname; class Kernel extends BaseKernel { @@ -17,7 +18,7 @@ class Kernel extends BaseKernel public function registerBundles(): iterable { - $contents = require $this->getProjectDir().'/config/bundles.php'; + $contents = require $this->getProjectDir() . '/config/bundles.php'; foreach ($contents as $class => $envs) { if ($envs[$this->environment] ?? $envs['all'] ?? false) { yield new $class(); @@ -27,27 +28,27 @@ class Kernel extends BaseKernel public function getProjectDir(): string { - return \dirname(__DIR__); + return dirname(__DIR__); } protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void { - $container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php')); + $container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php')); $container->setParameter('container.dumper.inline_class_loader', true); - $confDir = $this->getProjectDir().'/config'; + $confDir = $this->getProjectDir() . '/config'; - $loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob'); - $loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob'); - $loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob'); - $loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob'); + $loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob'); + $loader->load($confDir . '/{packages}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, 'glob'); + $loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob'); + $loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob'); } protected function configureRoutes(RouteCollectionBuilder $routes): void { - $confDir = $this->getProjectDir().'/config'; + $confDir = $this->getProjectDir() . '/config'; - $routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob'); - $routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob'); - $routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob'); + $routes->import($confDir . '/{routes}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, '/', 'glob'); + $routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob'); + $routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob'); } } diff --git a/src/Services/Curl.php b/src/Services/Curl.php index a4c3466..e5a6161 100644 --- a/src/Services/Curl.php +++ b/src/Services/Curl.php @@ -1,7 +1,10 @@ -init(); @@ -176,6 +163,44 @@ class Curl return $this; } + /** + * Provide a User Agent. + * + * In order to provide you cusomtized user agent name you can use this method. + * + * ```php + * $curl = new Curl(); + * $curl->setUserAgent('My John Doe Agent 1.0'); + * $curl->get('http://example.com/request.php'); + * ``` + * + * @param string $useragent The name of the user agent to set for the current request + * @return self + */ + public function setUserAgent($useragent) + { + $this->setOpt(CURLOPT_USERAGENT, $useragent); + return $this; + } + + // protected methods + + /** + * Set customized curl options. + * + * To see a full list of options: http://php.net/curl_setopt + * + * @see http://php.net/curl_setopt + * + * @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` + * @param mixed $value The value to pass for the given $option + * @return bool + */ + public function setOpt($option, $value) + { + return curl_setopt($this->curl, $option, $value); + } + /** * Handle writing the response headers * @@ -183,6 +208,7 @@ class Curl * @param string $header_line A line from the list of response headers * * @return int Returns the length of the $header_line + * @noinspection PhpUnusedParameterInspection */ public function addResponseHeaderLine($curl, $header_line) { @@ -195,11 +221,19 @@ class Curl } elseif (!$this->response_header_continue) { $this->response_headers[] = $trimmed_header; } - + return strlen($header_line); } - // protected methods + /** + * @deprecated calling exec() directly is discouraged + */ + public function _exec() + { + return $this->exec(); + } + + // public methods /** * Execute the curl request based on the respectiv settings. @@ -224,61 +258,6 @@ class Curl return $this->error_code; } - /** - * @param array|object|string $data - */ - protected function preparePayload($data) - { - $this->setOpt(CURLOPT_POST, true); - - if (is_array($data) || is_object($data)) { - $skip = false; - foreach ($data as $key => $value) { - // If a value is an instance of CurlFile skip the http_build_query - // see issue https://github.com/php-mod/curl/issues/46 - // suggestion from: https://stackoverflow.com/a/36603038/4611030 - if ($value instanceof \CurlFile) { - $skip = true; - } - } - - if (!$skip) { - $data = http_build_query($data); - } - } - - $this->setOpt(CURLOPT_POSTFIELDS, $data); - } - - /** - * Set auth options for the current request. - * - * Available auth types are: - * - * + self::AUTH_BASIC - * + self::AUTH_DIGEST - * + self::AUTH_GSSNEGOTIATE - * + self::AUTH_NTLM - * + self::AUTH_ANY - * + self::AUTH_ANYSAFE - * - * @param int $httpauth The type of authentication - */ - protected function setHttpAuth($httpauth) - { - $this->setOpt(CURLOPT_HTTPAUTH, $httpauth); - } - - // public methods - - /** - * @deprecated calling exec() directly is discouraged - */ - public function _exec() - { - return $this->exec(); - } - // functions /** @@ -286,14 +265,14 @@ class Curl * * The get request has no body data, the data will be correctly added to the $url with the http_build_query() method. * - * @param string $url The url to make the get request for - * @param array $data Optional arguments who are part of the url + * @param string $url The url to make the get request for + * @param array $data Optional arguments who are part of the url * @return self */ public function get($url, $data = array()) { if (count($data) > 0) { - $this->setOpt(CURLOPT_URL, $url.'?'.http_build_query($data)); + $this->setOpt(CURLOPT_URL, $url . '?' . http_build_query($data)); } else { $this->setOpt(CURLOPT_URL, $url); } @@ -305,13 +284,14 @@ class Curl /** * Make a post request with optional post data. * - * @param string $url The url to make the post request - * @param array $data Post data to pass to the url + * @param string $url The url to make the post request + * @param array $data Post data to pass to the url + * @param bool $payload * @return self */ public function post($url, $data = array(), $payload = false) { - if (! empty($data)) { + if (!empty($data)) { if ($payload === false) { // Check if the url has not already been modified $url .= strpos($url, '?') !== false ? '&' : '?'; @@ -327,6 +307,32 @@ class Curl return $this; } + /** + * @param array|object|string $data + */ + protected function preparePayload($data) + { + $this->setOpt(CURLOPT_POST, true); + + if (is_array($data) || is_object($data)) { + $skip = false; + foreach ($data as $key => $value) { + // If a value is an instance of CurlFile skip the http_build_query + // see issue https://github.com/php-mod/curl/issues/46 + // suggestion from: https://stackoverflow.com/a/36603038/4611030 + if ($value instanceof CurlFile) { + $skip = true; + } + } + + if (!$skip) { + $data = http_build_query($data); + } + } + + $this->setOpt(CURLOPT_POSTFIELDS, $data); + } + /** * Make a put request with optional data. * @@ -339,9 +345,9 @@ class Curl */ public function put($url, $data = array(), $payload = false) { - if (! empty($data)) { + if (!empty($data)) { if ($payload === false) { - $url .= '?'.http_build_query($data); + $url .= '?' . http_build_query($data); } else { $this->preparePayload($data); } @@ -365,9 +371,9 @@ class Curl */ public function patch($url, $data = array(), $payload = false) { - if (! empty($data)) { + if (!empty($data)) { if ($payload === false) { - $url .= '?'.http_build_query($data); + $url .= '?' . http_build_query($data); } else { $this->preparePayload($data); } @@ -379,6 +385,8 @@ class Curl return $this; } + // setters + /** * Make a delete request with optional data. * @@ -389,9 +397,9 @@ class Curl */ public function delete($url, $data = array(), $payload = false) { - if (! empty($data)) { + if (!empty($data)) { if ($payload === false) { - $url .= '?'.http_build_query($data); + $url .= '?' . http_build_query($data); } else { $this->preparePayload($data); } @@ -403,8 +411,6 @@ class Curl return $this; } - // setters - /** * Pass basic auth data. * @@ -423,10 +429,29 @@ class Curl public function setBasicAuthentication($username, $password) { $this->setHttpAuth(self::AUTH_BASIC); - $this->setOpt(CURLOPT_USERPWD, $username.':'.$password); + $this->setOpt(CURLOPT_USERPWD, $username . ':' . $password); return $this; } + /** + * Set auth options for the current request. + * + * Available auth types are: + * + * + self::AUTH_BASIC + * + self::AUTH_DIGEST + * + self::AUTH_GSSNEGOTIATE + * + self::AUTH_NTLM + * + self::AUTH_ANY + * + self::AUTH_ANYSAFE + * + * @param int $httpauth The type of authentication + */ + protected function setHttpAuth($httpauth) + { + $this->setOpt(CURLOPT_HTTPAUTH, $httpauth); + } + /** * Provide optional header informations. * @@ -438,38 +463,20 @@ class Curl * $curl->get('http://example.com/request.php'); * ``` * - * @param string $key The header key + * @param string $key The header key * @param string $value The value for the given header key * @return self */ public function setHeader($key, $value) { - $this->_headers[$key] = $key.': '.$value; + $this->_headers[$key] = $key . ': ' . $value; $this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers)); return $this; } /** - * Provide a User Agent. - * - * In order to provide you cusomtized user agent name you can use this method. - * - * ```php - * $curl = new Curl(); - * $curl->setUserAgent('My John Doe Agent 1.0'); - * $curl->get('http://example.com/request.php'); - * ``` - * - * @param string $useragent The name of the user agent to set for the current request - * @return self - */ - public function setUserAgent($useragent) - { - $this->setOpt(CURLOPT_USERAGENT, $useragent); - return $this; - } - - /** + * @param $referrer + * @return Curl * @deprecated Call setReferer() instead */ public function setReferrer($referrer) @@ -495,7 +502,7 @@ class Curl /** * Set contents of HTTP Cookie header. * - * @param string $key The name of the cookie + * @param string $key The name of the cookie * @param string $value The value for the provided cookie name * @return self */ @@ -507,53 +514,36 @@ class Curl } /** - * Set customized curl options. + * Return the endpoint set for curl * - * To see a full list of options: http://php.net/curl_setopt + * @see http://php.net/curl_getinfo * - * @see http://php.net/curl_setopt - * - * @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` - * @param mixed $value The value to pass for the given $option + * @return string of endpoint */ - public function setOpt($option, $value) - { - return curl_setopt($this->curl, $option, $value); - } - - /** - * Get customized curl options. - * - * To see a full list of options: http://php.net/curl_getinfo - * - * @see http://php.net/curl_getinfo - * - * @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` - * @param mixed $value The value to check for the given $option - */ - public function getOpt($option) - { - return curl_getinfo($this->curl, $option); - } - - /** - * Return the endpoint set for curl - * - * @see http://php.net/curl_getinfo - * - * @return string of endpoint - */ public function getEndpoint() { return $this->getOpt(CURLINFO_EFFECTIVE_URL); } + /** + * Get customized curl options. + * + * To see a full list of options: http://php.net/curl_getinfo + * + * @see http://php.net/curl_getinfo + * + * @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION` + * @return mixed + */ + public function getOpt($option) + { + return curl_getinfo($this->curl, $option); + } + /** * Enable verbositiy. * - * @todo As to keep naming convention it should be renamed to `setVerbose()` - * - * @param string $on + * @param bool $on * @return self */ public function verbose($on = true) @@ -662,7 +652,7 @@ class Curl { return $this->http_status_code >= 500 && $this->http_status_code < 600; } - + /** * Get a specific response header key or all values from the response headers array. * @@ -683,27 +673,27 @@ class Curl * ``` * * @param string $headerKey Optional key to get from the array. - * @return bool|string + * @return array * @since 1.9 */ public function getResponseHeaders($headerKey = null) { $headers = array(); $headerKey = strtolower($headerKey); - + foreach ($this->response_headers as $header) { $parts = explode(":", $header, 2); - + $key = isset($parts[0]) ? $parts[0] : null; $value = isset($parts[1]) ? $parts[1] : null; - + $headers[trim(strtolower($key))] = trim($value); } - + if ($headerKey) { - return isset($headers[$headerKey]) ? $headers[$headerKey] : false; + return isset($headers[$headerKey]) ? $headers[$headerKey] : []; } - + return $headers; } diff --git a/src/Services/Mastodon_api.php b/src/Services/Mastodon_api.php index df3a832..da4dd20 100644 --- a/src/Services/Mastodon_api.php +++ b/src/Services/Mastodon_api.php @@ -1,4 +1,6 @@ -mastodon_url = $path; + } + + /** + * set_client + * + * @param string $id + * @param string $secret + */ + public function set_client($id, $secret) + { + $this->client_id = $id; + $this->client_secret = $secret; + } + + /** + * set_token + * + * @param string $token + * @param string $type + */ + public function set_token($token, $type) + { + $this->token['access_token'] = $token; + $this->token['token_type'] = $type; + } + + /** + * set_scopes + * + * @param array $scopes read / write / follow + */ + public function set_scopes($scopes) + { + $this->scopes = $scopes; + } + + /** + * create_app + * + * @param string $client_name + * @param array $scopes read / write / follow + * @param string $redirect_uris + * @param string $website + * + * @return array $response + * int $response['id'] + * string $response['redirect_uri'] + * string $response['client_id'] + * string $response['client_secret'] + */ + public function create_app($client_name, $scopes = array(), $redirect_uris = '', $website = '') + { + $parameters = array(); + + if (count($scopes) == 0) { + if (count($this->scopes) == 0) { + $scopes = array('read', 'write', 'follow'); + } else { + $scopes = $this->scopes; + } + } + + $parameters['client_name'] = $client_name; + $parameters['scopes'] = implode(' ', $scopes); + if (empty($redirect_uris)) { + $parameters['redirect_uris'] = 'urn:ietf:wg:oauth:2.0:oob'; + } else { + $parameters['redirect_uris'] = $redirect_uris; + } + + if ($website) { + $parameters['website'] = $website; + } + + $response = $this->_post('/api/v1/apps', $parameters); + if (isset($response['html']['client_id'])) { + $this->client_id = $response['html']['client_id']; + $this->client_secret = $response['html']['client_secret']; + } + + return $response; + } /** * _post * * HTTP API post * - * @param string $url - * @param array $parameters + * @param string $url + * @param array $parameters * * @return array $response - * @throws \ErrorException */ - private function _post ($url, $parameters = array()) { + private function _post($url, $parameters = array()) + { $params["method"] = "POST"; // set access_token @@ -70,123 +170,20 @@ class Mastodon_api { ); } $params['body'] = $parameters; - $url = $this->mastodon_url.$url; - $response = $this->get_content_remote($url,$params); - return $response; - } - - - /** - * _put - * - * HTTP API put - * - * @param string $url - * @param array $parameters - * - * @return array $response - * @throws \ErrorException - */ - private function _put ($url, $parameters = array()) { - - $params["method"] = "PUT"; - // set access_token - if (isset($this->token['access_token'])) { - $params['headers'] = array( - 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] - ); - } - $params['body'] = $parameters; - $url = $this->mastodon_url.$url; - $response = $this->get_content_remote($url,$params); - return $response; - } - - /** - * _get - * - * @param string $url - * @param array $parameters - * - * @return array $response - * @throws \ErrorException - */ - private function _get ($url, $parameters = array()) { - - $params["method"] = "GET"; - // set authorization bearer - if (isset($this->token['access_token'])) { - $params['headers'] = array( - 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] - ); - } - $params['body'] = $parameters; - $url = $this->mastodon_url.$url; - - $response = $this->get_content_remote($url,$params); - return $response; - } - - /** - * _patch - * - * @param string $url - * @param array $parameters - * - * @return array $parameters - * @throws \ErrorException - */ - private function _patch ($url,$parameters = array()) { - - $params["method"] = "PATCH"; - - // set authorization bearer - if (isset($this->token['access_token'])) { - $params['headers'] = array( - 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] - ); - } - $params['body'] = $parameters; - - $url = $this->mastodon_url.$url; - $response = $this->get_content_remote($url,$params); - return $response; - } - - /** - * _delete - * - * @param string $url - * - * @return array $response - * - * @throws \ErrorException - */ - private function _delete ($url) { - $parameters = array(); - $parameters["method"] = "DELETE"; - - // set authorization bearer - if (isset($this->token['access_token'])) { - $parameters['headers'] = array( - 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] - ); - } - $url = $this->mastodon_url.$url; - $response = $this->get_content_remote($url,$parameters); - return $response; + $url = $this->mastodon_url . $url; + return $this->get_content_remote($url, $params); } /** * get_content_remote_get * - * @param string $url - * @param array $parameters + * @param string $url + * @param array $parameters * * @return array $data - * @throws \ErrorException */ - public function get_content_remote ($url,$parameters = array()) { + public function get_content_remote($url, $parameters = array()) + { $data = array(); // set USERAGENT @@ -199,30 +196,30 @@ class Mastodon_api { $curl = new Curl(); $response = null; - foreach ($parameters['headers'] as $key => $value){ + foreach ($parameters['headers'] as $key => $value) { $curl->setHeader($key, $value); } //Special treatment for sending media when editing profile - if(isset($parameters['body']['media'])) { - $fields = [$parameters['body']['media']['name'] => new \CURLFile($parameters['body']['media']['path'], $parameters['body']['media']['mimetype'], $parameters['body']['media']['filename'])]; + if (isset($parameters['body']['media'])) { + $fields = [$parameters['body']['media']['name'] => new CURLFile($parameters['body']['media']['path'], $parameters['body']['media']['mimetype'], $parameters['body']['media']['filename'])]; $curl->setOpt(CURLOPT_POSTFIELDS, $fields); } // Since Curl does not let us upload media_ids as we wish, we had to pass it through the url, directly. - if(isset($parameters['body']['media_ids'])) { - $url .= strpos($url, '?') !== false ? '' : '?'; + if (isset($parameters['body']['media_ids'])) { + $url .= strpos($url, '?') !== false ? '' : '?'; - foreach ($parameters['body']['media_ids'] as $key => $value){ - $url .= 'media_ids[]=' . (int) $value . '&'; + foreach ($parameters['body']['media_ids'] as $key => $value) { + $url .= 'media_ids[]=' . (int)$value . '&'; } $url = substr($url, 0, -1); unset($parameters['body']['media_ids']); } - if(isset($parameters['body']['poll']['options'])) { - $url .= strpos($url, '?') !== false ? '' : '?'; - foreach ($parameters['body']['poll']['options'] as $key => $value){ + if (isset($parameters['body']['poll']['options'])) { + $url .= strpos($url, '?') !== false ? '' : '?'; + foreach ($parameters['body']['poll']['options'] as $key => $value) { $url .= 'poll[options][]=' . $value . '&'; } $url = substr($url, 0, -1); @@ -230,29 +227,29 @@ class Mastodon_api { unset($parameters['body']['poll']['options']); } //Special treatment for filtering notifications - if( isset($parameters['body']['exclude_types[]']) && $parameters['method'] == "GET" ){ - $url .="?"; - foreach ($parameters['body']['exclude_types[]'] as $key => $value){ - $url .= "exclude_types[]=".$value."&"; + if (isset($parameters['body']['exclude_types[]']) && $parameters['method'] == "GET") { + $url .= "?"; + foreach ($parameters['body']['exclude_types[]'] as $key => $value) { + $url .= "exclude_types[]=" . $value . "&"; } - if( isset($parameters['body']['max_id'])) - $url .= "&max_id=".$parameters['body']['max_id']; + if (isset($parameters['body']['max_id'])) + $url .= "&max_id=" . $parameters['body']['max_id']; $parameters['body'] = []; } - if( isset($parameters["method"]) && $parameters['method'] == "POST" ) - $response = $curl->post($url, $parameters['body'] ); - else if( isset($parameters["method"]) && $parameters['method'] == "GET" ) - $response = $curl->get($url, $parameters['body'] ); - else if( isset($parameters["method"]) && $parameters['method'] == "PUT" ) - $response = $curl->put($url, $parameters['body'] ); - else if( isset($parameters["method"]) && $parameters['method'] == "PATCH" ) - $response = $curl->patch($url, $parameters['body'] ); - else if( isset($parameters["method"]) && $parameters['method'] == "DELETE" ) + if (isset($parameters["method"]) && $parameters['method'] == "POST") + $response = $curl->post($url, $parameters['body']); + else if (isset($parameters["method"]) && $parameters['method'] == "GET") + $response = $curl->get($url, $parameters['body']); + else if (isset($parameters["method"]) && $parameters['method'] == "PUT") + $response = $curl->put($url, $parameters['body']); + else if (isset($parameters["method"]) && $parameters['method'] == "PATCH") + $response = $curl->patch($url, $parameters['body']); + else if (isset($parameters["method"]) && $parameters['method'] == "DELETE") $response = $curl->delete($url); $min_id = null; $max_id = null; - if( $response->response_headers) { + if ($response->response_headers) { foreach ($response->response_headers as $value) { if (strpos($value, 'Link: ') !== false) { @@ -279,120 +276,33 @@ class Mastodon_api { } $data['min_id'] = $min_id; $data['max_id'] = $max_id; - if( $response->error){ + if ($response->error) { $data['error'] = $response->error; $data['error_code'] = $response->error_code; - $data['error_message'] =$response->error_message; - if( $response->response) - $data['error_message'] = \json_decode($response->response, true)['error']; - }else{ + $data['error_message'] = $response->error_message; + if ($response->response) + $data['error_message'] = json_decode($response->response, true)['error']; + } else { $data['response_headers'] = $response->response_headers; - $data['response'] = \json_decode($response->response, true); + $data['response'] = json_decode($response->response, true); } return $data; } - /** - * set_url - * - * @param string $path - */ - public function set_url ($path) { - $this->mastodon_url = $path; - } - - /** - * set_client - * - * @param string $id - * @param string $secret - */ - public function set_client ($id,$secret) { - $this->client_id = $id; - $this->client_secret = $secret; - } - - /** - * set_token - * - * @param string $token - * @param string $type - */ - public function set_token ($token,$type) { - $this->token['access_token'] = $token; - $this->token['token_type'] = $type; - } - - /** - * set_scopes - * - * @param array $scopes read / write / follow - */ - public function set_scopes ($scopes) { - $this->scopes = $scopes; - } - - /** - * create_app - * - * @param string $client_name - * @param array $scopes read / write / follow - * @param string $redirect_uris - * @param string $website - * - * @return array $response - * int $response['id'] - * string $response['redirect_uri'] - * string $response['client_id'] - * string $response['client_secret'] - * @throws \ErrorException - */ - public function create_app ($client_name,$scopes = array(),$redirect_uris = '',$website = '') { - $parameters = array(); - - if (count($scopes) == 0) { - if (count($this->scopes) == 0) { - $scopes = array('read','write','follow'); - } else { - $scopes = $this->scopes; - } - } - - $parameters['client_name'] = $client_name; - $parameters['scopes'] = implode(' ',$scopes); - if (empty($redirect_uris)) { - $parameters['redirect_uris'] = 'urn:ietf:wg:oauth:2.0:oob'; - } else { - $parameters['redirect_uris'] = $redirect_uris; - } - - if ($website) { - $parameters['website'] = $website; - } - - $response = $this->_post('/api/v1/apps',$parameters); - if (isset($response['html']['client_id'])) { - $this->client_id = $response['html']['client_id']; - $this->client_secret = $response['html']['client_secret']; - } - - return $response; - } - /** * login * - * @param string $id E-mail Address - * @param string $password Password + * @param string $id E-mail Address + * @param string $password Password * * @return array $response * string $response['access_token'] * string $response['token_type'] bearer * string $response['scope'] read * int $response['created_at'] time - * @throws \ErrorException */ - public function login ($id,$password) { + public function login($id, $password) + { $parameters = array(); $parameters['client_id'] = $this->client_id; $parameters['client_secret'] = $this->client_secret; @@ -401,11 +311,11 @@ class Mastodon_api { $parameters['password'] = $password; if (count($this->scopes) == 0) { - $parameters['scope'] = implode(' ',array('read','write','follow')); + $parameters['scope'] = implode(' ', array('read', 'write', 'follow')); } else { - $parameters['scope'] = implode(' ',$this->scopes); + $parameters['scope'] = implode(' ', $this->scopes); } - $response = $this->_post('/oauth/token',$parameters); + $response = $this->_post('/oauth/token', $parameters); if (isset($response['html']['access_token'])) { $this->token['access_token'] = $response['html']['access_token']; @@ -418,17 +328,17 @@ class Mastodon_api { /** * login * - * @param string $code Authorization code - * @param string $redirect_uri + * @param string $code Authorization code + * @param string $redirect_uri * * @return array $response * string $response['access_token'] * string $response['token_type'] bearer * string $response['scope'] read * int $response['created_at'] time - * @throws \ErrorException */ - public function loginAuthorization ($code, $redirect_uri = '') { + public function loginAuthorization($code, $redirect_uri = '') + { $parameters = array(); $parameters['client_id'] = $this->client_id; $parameters['client_secret'] = $this->client_secret; @@ -439,7 +349,7 @@ class Mastodon_api { } $parameters['grant_type'] = 'authorization_code'; $parameters['code'] = $code; - $response = $this->_post('/oauth/token',$parameters); + $response = $this->_post('/oauth/token', $parameters); if (isset($response['html']['access_token'])) { $this->token['access_token'] = $response['html']['access_token']; $this->token['token_type'] = $response['html']['token_type']; @@ -450,7 +360,7 @@ class Mastodon_api { /** * getAuthorizationUrl * - * @param string $redirect_uri + * @param string $redirect_uri * * @return string $response Authorization code */ @@ -459,26 +369,24 @@ class Mastodon_api { if (empty($redirect_uri)) $redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'; if (count($this->scopes) == 0) { - $scopes = array('read','write','follow'); + $scopes = array('read', 'write', 'follow'); } else { $scopes = $this->scopes; } $scope_uri = ""; - foreach($scopes as $scope) - $scope_uri .= $scope. " "; - return $this->mastodon_url.'/oauth/authorize?'. - "client_id=".$this->client_id."&redirect_uri=" . $redirect_uri. - "&response_type=code&scope=".trim($scope_uri); + foreach ($scopes as $scope) + $scope_uri .= $scope . " "; + return $this->mastodon_url . '/oauth/authorize?' . + "client_id=" . $this->client_id . "&redirect_uri=" . $redirect_uri . + "&response_type=code&scope=" . trim($scope_uri); } - - /** * accounts * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response * int $response['id'] @@ -496,11 +404,34 @@ class Mastodon_api { * string $response['avatar_static'] * string $response['header'] A base64 encoded image to display as the user's header image * string $response['header_static'] - * @throws \ErrorException */ - public function accounts ($id) { - $response = $this->_get('/api/v1/accounts/'.$id); - return $response; + public function accounts($id) + { + return $this->_get('/api/v1/accounts/' . $id); + } + + /** + * _get + * + * @param string $url + * @param array $parameters + * + * @return array $response + */ + private function _get($url, $parameters = array()) + { + + $params["method"] = "GET"; + // set authorization bearer + if (isset($this->token['access_token'])) { + $params['headers'] = array( + 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] + ); + } + $params['body'] = $parameters; + $url = $this->mastodon_url . $url; + + return $this->get_content_remote($url, $params); } /** @@ -509,11 +440,10 @@ class Mastodon_api { * Getting the current user * * @return array $response - * @throws \ErrorException */ - public function accounts_verify_credentials () { - $response = $this->_get('/api/v1/accounts/verify_credentials'); - return $response; + public function accounts_verify_credentials() + { + return $this->_get('/api/v1/accounts/verify_credentials'); } /** @@ -521,18 +451,42 @@ class Mastodon_api { * * Updating the current user * - * @param array $parameters + * @param array $parameters * string $parameters['display_name'] The name to display in the user's profile * string $parameters['note'] A new biography for the user * string $parameters['avatar'] A base64 encoded image to display as the user's avatar * string $parameters['header'] A base64 encoded image to display as the user's header image * * @return array $response - * @throws \ErrorException */ - public function accounts_update_credentials ($parameters) { - $response = $this->_patch('/api/v1/accounts/update_credentials',$parameters); - return $response; + public function accounts_update_credentials($parameters) + { + return $this->_patch('/api/v1/accounts/update_credentials', $parameters); + } + + /** + * _patch + * + * @param string $url + * @param array $parameters + * + * @return array $parameters + */ + private function _patch($url, $parameters = array()) + { + + $params["method"] = "PATCH"; + + // set authorization bearer + if (isset($this->token['access_token'])) { + $params['headers'] = array( + 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] + ); + } + $params['body'] = $parameters; + + $url = $this->mastodon_url . $url; + return $this->get_content_remote($url, $params); } /** @@ -540,14 +494,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_followers ($id) { - $response = $this->_get('/api/v1/accounts/'.$id.'/followers'); - return $response; + public function accounts_followers($id) + { + return $this->_get('/api/v1/accounts/' . $id . '/followers'); } /** @@ -555,14 +508,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_following ($id) { - $response = $this->_get('/api/v1/accounts/'.$id.'/following'); - return $response; + public function accounts_following($id) + { + return $this->_get('/api/v1/accounts/' . $id . '/following'); } /** @@ -570,14 +522,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_statuses ($id) { - $response = $this->_get('/api/v1/accounts/'.$id.'/statuses'); - return $response; + public function accounts_statuses($id) + { + return $this->_get('/api/v1/accounts/' . $id . '/statuses'); } /** @@ -585,16 +536,16 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_own_statuses ($id) { - $response = $this->_get('/api/v1/accounts/'.$id.'/statuses?exclude_replies=1'); + public function accounts_own_statuses($id) + { + $response = $this->_get('/api/v1/accounts/' . $id . '/statuses?exclude_replies=1'); $result = []; foreach ($response['html'] as $r) { - if(is_null($r['reblog'])) { + if (is_null($r['reblog'])) { $result[] = $r; } } @@ -609,14 +560,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_follow ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/follow'); - return $response; + public function accounts_follow($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/follow'); } /** @@ -624,14 +574,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_unfollow ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/unfollow'); - return $response; + public function accounts_unfollow($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/unfollow'); } /** @@ -639,14 +588,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_block ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/block'); - return $response; + public function accounts_block($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/block'); } /** @@ -654,14 +602,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_unblock ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/unblock'); - return $response; + public function accounts_unblock($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/unblock'); } /** @@ -669,14 +616,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_mute ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/mute'); - return $response; + public function accounts_mute($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/mute'); } /** @@ -684,14 +630,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function accounts_unmute ($id) { - $response = $this->_post('/api/v1/accounts/'.$id.'/unmute'); - return $response; + public function accounts_unmute($id) + { + return $this->_post('/api/v1/accounts/' . $id . '/unmute'); } /** @@ -699,7 +644,7 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param array $parameters + * @param array $parameters * int $parameters['id'] * * @return array $response @@ -709,59 +654,54 @@ class Mastodon_api { * bool $response['blocking'] * bool $response['muting'] * bool $response['requested'] - * @throws \ErrorException */ - public function accounts_relationships ($parameters) { - $response = $this->_get('/api/v1/accounts/relationships',$parameters); - return $response; + public function accounts_relationships($parameters) + { + return $this->_get('/api/v1/accounts/relationships', $parameters); } /** * accounts_search * - * @param array $parameters + * @param array $parameters * string $parameters['q'] * int $parameters['limit'] default : 40 * * @return array $response - * @throws \ErrorException */ - public function accounts_search ($parameters) { - $response = $this->_get('/api/v1/accounts/search',$parameters); - return $response; + public function accounts_search($parameters) + { + return $this->_get('/api/v1/accounts/search', $parameters); } /** * blocks * * @return array $response - * @throws \ErrorException */ - public function blocks () { - $response = $this->_get('/api/v1/blocks'); - return $response; + public function blocks() + { + return $this->_get('/api/v1/blocks'); } /** * favourites * * @return array $response - * @throws \ErrorException */ - public function favourites () { - $response = $this->_get('/api/v1/favourites'); - return $response; + public function favourites() + { + return $this->_get('/api/v1/favourites'); } /** * follow_requests * * @return array $response - * @throws \ErrorException */ - public function follow_requests () { - $response = $this->_get('/api/v1/follow_requests'); - return $response; + public function follow_requests() + { + return $this->_get('/api/v1/follow_requests'); } /** @@ -769,14 +709,13 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function follow_requests_authorize ($id) { - $response = $this->_post('/api/v1/follow_requests/authorize',array('id'=>$id)); - return $response; + public function follow_requests_authorize($id) + { + return $this->_post('/api/v1/follow_requests/authorize', array('id' => $id)); } /** @@ -784,13 +723,12 @@ class Mastodon_api { * * @see https://your-domain/web/accounts/:id * - * @param int $id + * @param int $id * @return array $response - * @throws \ErrorException */ - public function follow_requests_reject ($id) { - $response = $this->_post('/api/v1/follow_requests/reject',array('id'=>$id)); - return $response; + public function follow_requests_reject($id) + { + return $this->_post('/api/v1/follow_requests/reject', array('id' => $id)); } /** @@ -798,13 +736,12 @@ class Mastodon_api { * * Following a remote user * - * @param string $uri username@domain of the person you want to follow + * @param string $uri username@domain of the person you want to follow * @return array $response - * @throws \ErrorException */ - public function follows ($uri) { - $response = $this->_post('/api/v1/follows',array('uri'=>$uri)); - return $response; + public function follows($uri) + { + return $this->_post('/api/v1/follows', array('uri' => $uri)); } /** @@ -817,25 +754,22 @@ class Mastodon_api { * string $response['title'] * string $response['description'] * string $response['email'] - * @throws \ErrorException */ - public function instance () { - $response = $this->_get('/api/v1/instance'); - return $response; + public function instance() + { + return $this->_get('/api/v1/instance'); } - /** * mutes * * Fetching a user's mutes * * @return array $response - * @throws \ErrorException */ - public function mutes () { - $response = $this->_get('/api/v1/mutes'); - return $response; + public function mutes() + { + return $this->_get('/api/v1/mutes'); } /** @@ -845,13 +779,12 @@ class Mastodon_api { * @param $parameters * * @return array $response - * @throws \ErrorException */ - public function notifications ($parameters) { + public function notifications($parameters) + { $url = '/api/v1/notifications'; - $response = $this->_get($url, $parameters); - return $response; + return $this->_get($url, $parameters); } /** @@ -860,11 +793,10 @@ class Mastodon_api { * Clearing notifications * * @return array $response - * @throws \ErrorException */ - public function notifications_clear () { - $response = $this->_post('/api/v1/notifications/clear'); - return $response; + public function notifications_clear() + { + return $this->_post('/api/v1/notifications/clear'); } /** @@ -873,11 +805,10 @@ class Mastodon_api { * Fetching a user's reports * * @return array $response - * @throws \ErrorException */ - public function get_reports () { - $response = $this->_get('/api/v1/reports'); - return $response; + public function get_reports() + { + return $this->_get('/api/v1/reports'); } /** @@ -885,17 +816,16 @@ class Mastodon_api { * * Reporting a user * - * @param array $parameters + * @param array $parameters * int $parameters['account_id'] The ID of the account to report * int $parameters['status_ids'] The IDs of statuses to report (can be an array) * string $parameters['comment'] A comment to associate with the report. * * @return array $response - * @throws \ErrorException */ - public function post_reports ($parameters) { - $response = $this->_post('/api/v1/reports',$parameters); - return $response; + public function post_reports($parameters) + { + return $this->_post('/api/v1/reports', $parameters); } /** @@ -903,16 +833,15 @@ class Mastodon_api { * * Searching for content * - * @param array $parameters + * @param array $parameters * string $parameters['q'] The search query * string $parameters['resolve'] Whether to resolve non-local accounts * * @return array $response - * @throws \ErrorException */ - public function search ($parameters) { - $response = $this->_get('/api/v1/search',$parameters); - return $response; + public function search($parameters) + { + return $this->_get('/api/v1/search', $parameters); } /** @@ -920,14 +849,13 @@ class Mastodon_api { * * Fetching a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses ($id) { - $response = $this->_get('/api/v1/statuses/'.$id); - return $response; + public function statuses($id) + { + return $this->_get('/api/v1/statuses/' . $id); } /** @@ -935,14 +863,13 @@ class Mastodon_api { * * Getting status context * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_context ($id) { - $response = $this->_get('/api/v1/statuses/'.$id.'/context'); - return $response; + public function statuses_context($id) + { + return $this->_get('/api/v1/statuses/' . $id . '/context'); } /** @@ -950,14 +877,13 @@ class Mastodon_api { * * Getting a card associated with a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_card ($id) { - $response = $this->_get('/api/v1/statuses/'.$id.'/card'); - return $response; + public function statuses_card($id) + { + return $this->_get('/api/v1/statuses/' . $id . '/card'); } /** @@ -965,14 +891,13 @@ class Mastodon_api { * * Getting who reblogged a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_reblogged_by ($id) { - $response = $this->_get('/api/v1/statuses/'.$id.'/reblogged_by'); - return $response; + public function statuses_reblogged_by($id) + { + return $this->_get('/api/v1/statuses/' . $id . '/reblogged_by'); } /** @@ -980,53 +905,75 @@ class Mastodon_api { * * Getting who favourited a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_favourited_by ($id) { - $response = $this->_get('/api/v1/statuses/'.$id.'/favourited_by'); - return $response; + public function statuses_favourited_by($id) + { + return $this->_get('/api/v1/statuses/' . $id . '/favourited_by'); } - /** * post_media * - * @param array $parameters + * @param array $parameters * file $parameters['file'] Media file encoded using multipart/form-data * string $parameters['description'] (optional): A plain-text description of the media for accessibility (max 420 chars) * array $parameters['focus'] (optional):Two floating points, comma-delimited. See focal points * * @return array $response - * @throws \ErrorException */ - public function post_media ($parameters) { - $response = $this->_post('/api/v1/media',$parameters); - return $response; + public function post_media($parameters) + { + return $this->_post('/api/v1/media', $parameters); } /** * post_media * - * @param string $id + * @param string $id * array $parameters * string $parameters['description'] (optional): A plain-text description of the media for accessibility (max 420 chars) * array $parameters['focus'] (optional):Two floating points, comma-delimited. See focal points * + * @param $parameters * @return array $response - * @throws \ErrorException */ - public function update_media ($id, $parameters) { - $response = $this->_put('/api/v1/media/'.$id, $parameters); - return $response; + public function update_media($id, $parameters) + { + return $this->_put('/api/v1/media/' . $id, $parameters); + } + + /** + * _put + * + * HTTP API put + * + * @param string $url + * @param array $parameters + * + * @return array $response + */ + private function _put($url, $parameters = array()) + { + + $params["method"] = "PUT"; + // set access_token + if (isset($this->token['access_token'])) { + $params['headers'] = array( + 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] + ); + } + $params['body'] = $parameters; + $url = $this->mastodon_url . $url; + return $this->get_content_remote($url, $params); } /** * post_statuses * - * @param array $parameters + * @param array $parameters * string $parameters['status'] The text of the status * int $parameters['in_reply_to_id'] (optional): local ID of the status you want to reply to * int $parameters['media_ids'] (optional): array of media IDs to attach to the status (maximum 4) @@ -1035,11 +982,10 @@ class Mastodon_api { * string $parameters['visibility'] (optional): either "direct", "private", "unlisted" or "public" * * @return array $response - * @throws \ErrorException */ - public function post_statuses ($parameters) { - $response = $this->_post('/api/v1/statuses',$parameters); - return $response; + public function post_statuses($parameters) + { + return $this->_post('/api/v1/statuses', $parameters); } /** @@ -1047,30 +993,51 @@ class Mastodon_api { * * Deleting a status * - * @param int $id + * @param int $id * * @return array $response empty - * @throws \ErrorException */ - public function delete_statuses ($id) { - $response = $this->_delete('/api/v1/statuses/'.$id); - return $response; + public function delete_statuses($id) + { + return $this->_delete('/api/v1/statuses/' . $id); } + /** + * _delete + * + * @param string $url + * + * @return array $response + * + + */ + private function _delete($url) + { + $parameters = array(); + $parameters["method"] = "DELETE"; + + // set authorization bearer + if (isset($this->token['access_token'])) { + $parameters['headers'] = array( + 'Authorization' => $this->token['token_type'] . ' ' . $this->token['access_token'] + ); + } + $url = $this->mastodon_url . $url; + return $this->get_content_remote($url, $parameters); + } /** * delete_scheduled * * Deleting a scheduled status * - * @param int $id + * @param int $id * * @return array $response empty - * @throws \ErrorException */ - public function delete_scheduled ($id) { - $response = $this->_delete('/api/v1/scheduled_statuses/'.$id); - return $response; + public function delete_scheduled($id) + { + return $this->_delete('/api/v1/scheduled_statuses/' . $id); } /** @@ -1078,14 +1045,13 @@ class Mastodon_api { * * Reblogging a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_reblog ($id) { - $response = $this->_post('/api/v1/statuses/'.$id.'/reblog'); - return $response; + public function statuses_reblog($id) + { + return $this->_post('/api/v1/statuses/' . $id . '/reblog'); } /** @@ -1093,14 +1059,13 @@ class Mastodon_api { * * Unreblogging a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_unreblog ($id) { - $response = $this->_post('/api/v1/statuses/'.$id.'/unreblog'); - return $response; + public function statuses_unreblog($id) + { + return $this->_post('/api/v1/statuses/' . $id . '/unreblog'); } /** @@ -1108,14 +1073,13 @@ class Mastodon_api { * * Favouriting a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_favourite ($id) { - $response = $this->_post('/api/v1/statuses/'.$id.'/favourite'); - return $response; + public function statuses_favourite($id) + { + return $this->_post('/api/v1/statuses/' . $id . '/favourite'); } /** @@ -1123,68 +1087,63 @@ class Mastodon_api { * * Unfavouriting a status * - * @param int $id + * @param int $id * * @return array $response - * @throws \ErrorException */ - public function statuses_unfavourite ($id) { - $response = $this->_post('/api/v1/statuses/'.$id.'/unfavourite'); - return $response; + public function statuses_unfavourite($id) + { + return $this->_post('/api/v1/statuses/' . $id . '/unfavourite'); } /** * scheduled_statuses * - * @param array $parameters + * @param array $parameters * * @return array $response - * @throws \ErrorException */ - public function get_scheduled ($parameters = array()) { - $response = $this->_get('/api/v1/scheduled_statuses/', $parameters); - return $response; + public function get_scheduled($parameters = array()) + { + return $this->_get('/api/v1/scheduled_statuses/', $parameters); } /** * timelines_home * * @return array $response - * @throws \ErrorException */ - public function timelines_home () { - $response = $this->_get('/api/v1/timelines/home'); - return $response; + public function timelines_home() + { + return $this->_get('/api/v1/timelines/home'); } /** * timelines_public * - * @param array $parameters + * @param array $parameters * bool $parameters['local'] Only return statuses originating from this instance * * @return array $response - * @throws \ErrorException */ - public function timelines_public ($parameters = array()) { - $response = $this->_get('/api/v1/timelines/public',$parameters); - return $response; + public function timelines_public($parameters = array()) + { + return $this->_get('/api/v1/timelines/public', $parameters); } /** * timelines_tag * - * @param string $hashtag - * @param array $parameters + * @param string $hashtag + * @param array $parameters * bool $parameters['local'] Only return statuses originating from this instance * * @return array $response - * @throws \ErrorException */ - public function timelines_tag ($hashtag,$parameters = array()) { - $response = $this->_get('/api/v1/timelines/tag/'.$hashtag,$parameters); - return $response; + public function timelines_tag($hashtag, $parameters = array()) + { + return $this->_get('/api/v1/timelines/tag/' . $hashtag, $parameters); } @@ -1198,44 +1157,134 @@ class Mastodon_api { * @param $host * @return string|null */ - public function getInstanceNodeInfo($host){ - try { + public function getInstanceNodeInfo($host) + { + $curl = new Curl(); + $url = "https://" . $host . "/.well-known/nodeinfo"; + $reply = $curl->get($url); + + + $responseArray = json_decode($reply->response, true); + if (empty($responseArray)) { $curl = new Curl(); - $url = "https://" . $host . "/.well-known/nodeinfo"; + $url = "https://" . $host . "/api/v1/instance"; $reply = $curl->get($url); - - - $responseArray = \json_decode($reply->response, true); - if ( empty($responseArray)){ - $curl = new Curl(); - $url = "https://" . $host . "/api/v1/instance"; - $reply = $curl->get($url); - $responseArray = \json_decode($reply->response, true); - if ( empty($responseArray)){ - return null; - }else{ - return "MASTODON"; - } - }else{ - $url = $responseArray["links"][count($responseArray["links"])-1]["href"]; - $curl = new Curl(); - $reply = $curl->get($url); - $responseArray = \json_decode($reply->response, true); - return strtoupper($responseArray["software"]["name"]); + $responseArray = json_decode($reply->response, true); + if (empty($responseArray)) { + return null; + } else { + return "MASTODON"; } - - } catch (\ErrorException $e) { - + } else { + $url = $responseArray["links"][count($responseArray["links"]) - 1]["href"]; + $curl = new Curl(); + $reply = $curl->get($url); + $responseArray = json_decode($reply->response, true); + return strtoupper($responseArray["software"]["name"]); } } + /** + * Update a Mastodon account with new params + * @param $MastodonAccount MastodonAccount + * @param $accountParams array + * @return MastodonAccount + */ + public function updateAccount(MastodonAccount $MastodonAccount, $accountParams) + { + + $MastodonAccount->setUsername($accountParams['username']); + $MastodonAccount->setAcct($accountParams['acct']); + $MastodonAccount->setDisplayName($accountParams['display_name']); + $MastodonAccount->setLocked($accountParams['locked']); + $MastodonAccount->setBot($accountParams['bot']); + $MastodonAccount->setCreatedAt($this->stringToDate($accountParams['created_at'])); + $MastodonAccount->setNote(strip_tags($accountParams['note'])); + $MastodonAccount->setUrl($accountParams['url']); + $MastodonAccount->setAvatar($accountParams['avatar']); + $MastodonAccount->setAvatarStatic($accountParams['avatar_static']); + $MastodonAccount->setHeader($accountParams['header']); + $MastodonAccount->setHeaderStatic($accountParams['header_static']); + $MastodonAccount->setFollowersCount($accountParams['followers_count']); + $MastodonAccount->setFollowingCount($accountParams['following_count']); + $MastodonAccount->setStatusesCount($accountParams['statuses_count']); + + foreach ($MastodonAccount->getEmojis() as $emoji) { + $MastodonAccount->removeEmoji($emoji); + } + if ($accountParams['emojis'] && count($accountParams['emojis']) > 0) { + foreach ($accountParams['emojis'] as $_e) { + $emoji = new Emoji(); + $emoji->setUrl($_e['url']); + $emoji->setShortcode($_e['shortcode']); + $emoji->setStaticUrl($_e['static_url']); + $emoji->setVisibleInPicker($_e['visible_in_picker']); + $emoji->setMastodonAccount($MastodonAccount); + $MastodonAccount->addEmoji($emoji); + } + } + foreach ($MastodonAccount->getFields() as $field) { + $MastodonAccount->removeField($field); + } + if ($accountParams['fields'] && count($accountParams['fields']) > 0) { + foreach ($accountParams['fields'] as $_f) { + $field = new CustomField(); + $field->setName($_f['name']); + $field->setValue(strip_tags($_f['value'])); + $field->setVerifiedAt($this->stringToDate($_f['verified_at'])); + $field->setMastodonAccount($MastodonAccount); + $MastodonAccount->addField($field); + } + } + return $MastodonAccount; + } + + public function stringToDate($string_date) + { + try { + return new DateTime($string_date); + } catch (Exception $e) { + } + return ""; + } + + /** + * getNotifications Hydrate an array of Notification from API reply + * @param $notificationParams + * @return array + */ + public function getNotifications($notificationParams) + { + $notifications = []; + foreach ($notificationParams as $notificationParam) + $notifications[] = $this->getSingleNotification($notificationParam); + return $notifications; + } + + /** + * getSingleNotification Hydrate a Notification from API reply + * @param $notificationParams + * @return Notification + */ + public function getSingleNotification($notificationParams) + { + $notification = new Notification(); + $notification->setId($notificationParams['id']); + $notification->setType($notificationParams['type']); + $notification->setCreatedAt($this->stringToDate($notificationParams['created_at'])); + $notification->setAccount($this->getSingleAccount($notificationParams['account'])); + if (isset($notificationParams['status'])) + $notification->setStatus($this->getSingleStatus($notificationParams['status'])); + return $notification; + } /** * getSingleAccount Hydrate a MastodonAccount from API reply * @param $accountParams * @return MastodonAccount */ - public function getSingleAccount($accountParams){ + public function getSingleAccount($accountParams) + { $MastodonAccount = new MastodonAccount(); $MastodonAccount->setAccountId($accountParams['id']); @@ -1255,8 +1304,8 @@ class Mastodon_api { $MastodonAccount->setFollowingCount($accountParams['following_count']); $MastodonAccount->setStatusesCount($accountParams['statuses_count']); - if( $accountParams['emojis'] && count($accountParams['emojis']) > 0){ - foreach ($accountParams['emojis'] as $_e){ + if ($accountParams['emojis'] && count($accountParams['emojis']) > 0) { + foreach ($accountParams['emojis'] as $_e) { $emoji = new Emoji(); $emoji->setUrl($_e['url']); $emoji->setShortcode($_e['shortcode']); @@ -1266,8 +1315,8 @@ class Mastodon_api { $MastodonAccount->addEmoji($emoji); } } - if( $accountParams['fields'] && count($accountParams['fields']) > 0){ - foreach ($accountParams['fields'] as $_f){ + if ($accountParams['fields'] && count($accountParams['fields']) > 0) { + foreach ($accountParams['fields'] as $_f) { $field = new CustomField(); $field->setName($_f['name']); $field->setValue(strip_tags($_f['value'])); @@ -1276,133 +1325,26 @@ class Mastodon_api { $MastodonAccount->addField($field); } } - if( $accountParams['source'] && $accountParams['source']['privacy']){ + if ($accountParams['source'] && $accountParams['source']['privacy']) { $MastodonAccount->setDefaultVisibility($accountParams['source']['privacy']); - }else{ + } else { $MastodonAccount->setDefaultVisibility("public"); } - if( $accountParams['source'] ){ - $MastodonAccount->setDefaultSensitivity($accountParams['source']['sensitive']?1:0); - }else{ + if ($accountParams['source']) { + $MastodonAccount->setDefaultSensitivity($accountParams['source']['sensitive'] ? 1 : 0); + } else { $MastodonAccount->setDefaultSensitivity(0); } return $MastodonAccount; } - - /** - * Update a Mastodon account with new params - * @param $MastodonAccount MastodonAccount - * @param $accountParams array - * @return MastodonAccount - */ - public function updateAccount(MastodonAccount $MastodonAccount, $accountParams){ - - $MastodonAccount->setUsername($accountParams['username']); - $MastodonAccount->setAcct($accountParams['acct']); - $MastodonAccount->setDisplayName($accountParams['display_name']); - $MastodonAccount->setLocked($accountParams['locked']); - $MastodonAccount->setBot($accountParams['bot']); - $MastodonAccount->setCreatedAt($this->stringToDate($accountParams['created_at'])); - $MastodonAccount->setNote(strip_tags($accountParams['note'])); - $MastodonAccount->setUrl($accountParams['url']); - $MastodonAccount->setAvatar($accountParams['avatar']); - $MastodonAccount->setAvatarStatic($accountParams['avatar_static']); - $MastodonAccount->setHeader($accountParams['header']); - $MastodonAccount->setHeaderStatic($accountParams['header_static']); - $MastodonAccount->setFollowersCount($accountParams['followers_count']); - $MastodonAccount->setFollowingCount($accountParams['following_count']); - $MastodonAccount->setStatusesCount($accountParams['statuses_count']); - - foreach ($MastodonAccount->getEmojis() as $emoji){ - $MastodonAccount->removeEmoji($emoji); - } - if( $accountParams['emojis'] && count($accountParams['emojis']) > 0){ - foreach ($accountParams['emojis'] as $_e){ - $emoji = new Emoji(); - $emoji->setUrl($_e['url']); - $emoji->setShortcode($_e['shortcode']); - $emoji->setStaticUrl($_e['static_url']); - $emoji->setVisibleInPicker($_e['visible_in_picker']); - $emoji->setMastodonAccount($MastodonAccount); - $MastodonAccount->addEmoji($emoji); - } - } - foreach ($MastodonAccount->getFields() as $field){ - $MastodonAccount->removeField($field); - } - if( $accountParams['fields'] && count($accountParams['fields']) > 0){ - foreach ($accountParams['fields'] as $_f){ - $field = new CustomField(); - $field->setName($_f['name']); - $field->setValue(strip_tags($_f['value'])); - $field->setVerifiedAt($this->stringToDate($_f['verified_at'])); - $field->setMastodonAccount($MastodonAccount); - $MastodonAccount->addField($field); - } - } - return $MastodonAccount; - } - - public function stringToDate($string_date){ - - try { - return new \DateTime($string_date); - } catch (\Exception $e) { - } - } - - - /** - * getNotifications Hydrate an array of Notification from API reply - * @param $notificationParams - * @return array - */ - public function getNotifications($notificationParams){ - $notifications = []; - foreach ($notificationParams as $notificationParam) - $notifications[] = $this->getSingleNotification($notificationParam); - return $notifications; - } - - /** - * getStatuses Hydrate an array of Status from API reply - * @param $statusParams - * @return array - */ - public function getStatuses($statusParams){ - $statuses = []; - foreach ($statusParams as $statusParam) - $statuses[] = $this->getSingleStatus($statusParam); - return $statuses; - } - - - - /** - * getSingleNotification Hydrate a Notification from API reply - * @param $notificationParams - * @return Notification - */ - public function getSingleNotification($notificationParams){ - $notification = new Notification(); - $notification->setId($notificationParams['id']); - $notification->setType($notificationParams['type']); - $notification->setCreatedAt($this->stringToDate($notificationParams['created_at'])); - $notification->setAccount($this->getSingleAccount($notificationParams['account'])); - if( isset($notificationParams['status']) ) - $notification->setStatus($this->getSingleStatus($notificationParams['status'])); - return $notification; - } - - - /** * getSingleStatus Hydrate a Status from API reply * @param $statusParams * @return Status */ - public function getSingleStatus($statusParams){ + public function getSingleStatus($statusParams) + { $status = new Status(); $status->setId($statusParams['id']); @@ -1414,9 +1356,9 @@ class Mastodon_api { $status->setContent($statusParams['content']); $status->setCreatedAt($this->stringToDate($statusParams['created_at'])); - if( isset($statusParams['emojis']) && count($statusParams['emojis']) > 0){ + if (isset($statusParams['emojis']) && count($statusParams['emojis']) > 0) { $emojis = []; - foreach ($statusParams['emojis'] as $_e){ + foreach ($statusParams['emojis'] as $_e) { $emoji = new Emoji(); $emoji->setUrl($_e['url']); $emoji->setShortcode($_e['shortcode']); @@ -1433,30 +1375,30 @@ class Mastodon_api { $status->setFavourited($statusParams['favourited']); $status->setMuted($statusParams['muted']); $status->setSensitive($statusParams['sensitive']); - $status->setSpoilerText($statusParams['spoiler_text']);; + $status->setSpoilerText($statusParams['spoiler_text']); $status->setVisibility($statusParams['visibility']); - if( isset($statusParams['media_attachments']) && count($statusParams['media_attachments']) > 0){ + if (isset($statusParams['media_attachments']) && count($statusParams['media_attachments']) > 0) { $media_attachments = []; - foreach ($statusParams['media_attachments'] as $_m){ + foreach ($statusParams['media_attachments'] as $_m) { $attachment = new Attachment(); $attachment->setId($_m['id']); $attachment->setUrl($_m['url']); $attachment->setType($_m['type']); - if($_m['remote_url']) + if ($_m['remote_url']) $attachment->setRemoteUrl($_m['remote_url']); $attachment->setPreviewUrl($_m['preview_url']); - if($_m['text_url']) + if ($_m['text_url']) $attachment->setTextUrl($_m['text_url']); $attachment->setMeta(serialize($_m['meta'])); - if($_m['description']) + if ($_m['description']) $attachment->setDescription($_m['description']); $media_attachments[] = $attachment; } $status->setMediaAttachments($media_attachments); } - if( isset($statusParams['mentions']) && count($statusParams['mentions']) > 0){ + if (isset($statusParams['mentions']) && count($statusParams['mentions']) > 0) { $mentions = []; - foreach ($statusParams['mentions'] as $_m){ + foreach ($statusParams['mentions'] as $_m) { $mention = new Mention(); $mention->setUrl($_m['url']); $mention->setAcct($_m['acct']); @@ -1467,26 +1409,26 @@ class Mastodon_api { $status->setMentions($mentions); } - if( isset($statusParams['tags']) && count($statusParams['tags']) > 0){ + if (isset($statusParams['tags']) && count($statusParams['tags']) > 0) { $tags = []; - foreach ($statusParams['tags'] as $_t){ + foreach ($statusParams['tags'] as $_t) { $tag = new Tag(); $tag->setUrl($_t['url']); $tag->setName($_t['name']); - $tag->setHistory(isset($_t['history'])?$_t['history']:[]); + $tag->setHistory(isset($_t['history']) ? $_t['history'] : []); $tags[] = $tag; } $status->setTags($tags); } - if( isset($statusParams['application']) && count($statusParams['application']) == 1){ + if (isset($statusParams['application']) && count($statusParams['application']) == 1) { $application = new Application(); $application->setName($statusParams['application']['name']); $application->setWebsite($statusParams['application']['website']); $status->setApplication($application); } - if( isset($statusParams['poll'])) { + if (isset($statusParams['poll'])) { $poll = new Poll(); $poll->setId($statusParams['poll']['id']); $options = []; @@ -1501,9 +1443,9 @@ class Mastodon_api { $poll->setExpiresAt($this->stringToDate($statusParams['poll']['expired_at'])); $poll->setExpired($statusParams['poll']['expired']); $poll->setVotesCount($statusParams['poll']['votes_count']); - if( isset($statusParams['poll']['emojis']) && count($statusParams['poll']['emojis']) > 0){ + if (isset($statusParams['poll']['emojis']) && count($statusParams['poll']['emojis']) > 0) { $emojis = []; - foreach ($statusParams['poll']['emojis'] as $_e){ + foreach ($statusParams['poll']['emojis'] as $_e) { $emoji = new Emoji(); $emoji->setUrl($_e['url']); $emoji->setShortcode($_e['shortcode']); @@ -1521,21 +1463,33 @@ class Mastodon_api { $status->setLanguage($statusParams['language']); - $status->setPinned(isset($statusParams['pinned'])?true:false); - if( $statusParams['reblog'] ) + $status->setPinned(isset($statusParams['pinned'])); + if ($statusParams['reblog']) $status->setReblog($this->getSingleStatus($statusParams['reblog'])); return $status; } - - + /** + * getStatuses Hydrate an array of Status from API reply + * @param $statusParams + * @return array + */ + public function getStatuses($statusParams) + { + $statuses = []; + foreach ($statusParams as $statusParam) + $statuses[] = $this->getSingleStatus($statusParam); + return $statuses; + } /** * getScheduledStatuses Hydrate an array of Scheduled Status from API reply * @param $statusParams + * @param $account * @return array */ - public function getScheduledStatuses($statusParams, $account){ + public function getScheduledStatuses($statusParams, $account) + { $statuses = []; foreach ($statusParams as $statusParam) $statuses[] = $this->getSingleScheduledStatus($statusParam, $account); @@ -1546,9 +1500,11 @@ class Mastodon_api { /** * getSingleScheduledStatus Hydrate a scheduled Status from API reply * @param $statusParams + * @param $account * @return Status */ - public function getSingleScheduledStatus($statusParams, $account){ + public function getSingleScheduledStatus($statusParams, $account) + { $status = new Status(); $status->setId($statusParams['id']); @@ -1556,9 +1512,9 @@ class Mastodon_api { $status->setContent($statusParams['params']['text']); $status->setScheduledAt($this->stringToDate($statusParams['scheduled_at'])); $status->setAccount($account); - if( isset($statusParams['emojis']) && count($statusParams['emojis']) > 0){ + if (isset($statusParams['emojis']) && count($statusParams['emojis']) > 0) { $emojis = []; - foreach ($statusParams['emojis'] as $_e){ + foreach ($statusParams['emojis'] as $_e) { $emoji = new Emoji(); $emoji->setUrl($_e['url']); $emoji->setShortcode($_e['shortcode']); @@ -1568,31 +1524,31 @@ class Mastodon_api { } $status->setEmojis($emojis); } - $status->setSensitive($statusParams['params']['sensitive']?1:0); - $status->setSpoilerText($statusParams['params']['spoiler_text']);; + $status->setSensitive($statusParams['params']['sensitive'] ? 1 : 0); + $status->setSpoilerText($statusParams['params']['spoiler_text']); $status->setVisibility($statusParams['params']['visibility']); - if( isset($statusParams['media_attachments']) && count($statusParams['media_attachments']) > 0){ + if (isset($statusParams['media_attachments']) && count($statusParams['media_attachments']) > 0) { $media_attachments = []; - foreach ($statusParams['media_attachments'] as $_m){ + foreach ($statusParams['media_attachments'] as $_m) { $attachment = new Attachment(); $attachment->setId($_m['id']); $attachment->setUrl($_m['url']); $attachment->setType($_m['type']); - if($_m['remote_url']) + if ($_m['remote_url']) $attachment->setRemoteUrl($_m['remote_url']); $attachment->setPreviewUrl($_m['preview_url']); - if($_m['text_url']) + if ($_m['text_url']) $attachment->setTextUrl($_m['text_url']); $attachment->setMeta(serialize($_m['meta'])); - if($_m['description']) + if ($_m['description']) $attachment->setDescription($_m['description']); $media_attachments[] = $attachment; } $status->setMediaAttachments($media_attachments); } - if( isset($statusParams['mentions']) && count($statusParams['mentions']) > 0){ + if (isset($statusParams['mentions']) && count($statusParams['mentions']) > 0) { $mentions = []; - foreach ($statusParams['mentions'] as $_m){ + foreach ($statusParams['mentions'] as $_m) { $mention = new Mention(); $mention->setUrl($_m['url']); $mention->setAcct($_m['acct']); @@ -1603,13 +1559,13 @@ class Mastodon_api { $status->setMentions($mentions); } - if( isset($statusParams['tags']) && count($statusParams['tags']) > 0){ + if (isset($statusParams['tags']) && count($statusParams['tags']) > 0) { $tags = []; - foreach ($statusParams['tags'] as $_t){ + foreach ($statusParams['tags'] as $_t) { $tag = new Tag(); $tag->setUrl($_t['url']); $tag->setName($_t['name']); - $tag->setHistory(isset($_t['history'])?$_t['history']:[]); + $tag->setHistory(isset($_t['history']) ? $_t['history'] : []); $tags[] = $tag; } $status->setTags($tags); @@ -1622,19 +1578,20 @@ class Mastodon_api { * @param $mediaParams * @return Attachment */ - public function getSingleAttachment($mediaParams){ + public function getSingleAttachment($mediaParams) + { $attachment = new Attachment(); $attachment->setId($mediaParams['id']); $attachment->setUrl($mediaParams['url']); $attachment->setType($mediaParams['type']); - if($mediaParams['remote_url']) + if ($mediaParams['remote_url']) $attachment->setRemoteUrl($mediaParams['remote_url']); $attachment->setPreviewUrl($mediaParams['preview_url']); - if($mediaParams['text_url']) + if ($mediaParams['text_url']) $attachment->setTextUrl($mediaParams['text_url']); $attachment->setMeta(serialize($mediaParams['meta'])); - if($mediaParams['description']) + if ($mediaParams['description']) $attachment->setDescription($mediaParams['description']); return $attachment; } diff --git a/src/SocialEntity/Compose.php b/src/SocialEntity/Compose.php index fa922c0..927ac40 100644 --- a/src/SocialEntity/Compose.php +++ b/src/SocialEntity/Compose.php @@ -5,7 +5,6 @@ namespace App\SocialEntity; use DateTime; use DateTimeInterface; use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\Common\Collections\Collection; class Compose @@ -39,7 +38,6 @@ class Compose public function __construct() { - $this->attachments = new ArrayCollection(); $this->poll_options = new ArrayCollection(); } diff --git a/src/Twig/AppExtension.php b/src/Twig/AppExtension.php index c79cb83..d9567a8 100644 --- a/src/Twig/AppExtension.php +++ b/src/Twig/AppExtension.php @@ -27,19 +27,19 @@ class AppExtension extends AbstractExtension public function accountEmoji($account, $content) { - if( $account instanceof MastodonAccount){ - foreach( $account->getEmojis() as $emoji){ - $content = preg_replace("(:" . $emoji->getShortcode() .":)", "".$emoji->getShortcode()."", $content); + if ($account instanceof MastodonAccount) { + foreach ($account->getEmojis() as $emoji) { + $content = preg_replace("(:" . $emoji->getShortcode() . ":)", "" . $emoji->getShortcode() . "", $content); } } - return $content; + return $content; } public function statusEmoji($status, $content) { - if( $status instanceof Status){ - foreach( $status->getEmojis() as $emoji){ - $content = preg_replace("(:" . $emoji->getShortcode() . ":)", "".$emoji->getShortcode()."", $content); + if ($status instanceof Status) { + foreach ($status->getEmojis() as $emoji) { + $content = preg_replace("(:" . $emoji->getShortcode() . ":)", "" . $emoji->getShortcode() . "", $content); } } return $content; @@ -47,26 +47,26 @@ class AppExtension extends AbstractExtension public function language($locale) { - switch ($locale){ - case "en": - return "English"; - case "fr": - return "Français"; - case "de": - return "Deutsch"; - case "nl": - return "Nederlands"; - case "pt-PT": - return "Português"; - case "pt-BR": - return "Brasil"; - case "it": - return "Italiano"; - case "ca": - return "Català"; - case "ar": - return "العربية"; + switch ($locale) { + case "en": + return "English"; + case "fr": + return "Français"; + case "de": + return "Deutsch"; + case "nl": + return "Nederlands"; + case "pt-PT": + return "Português"; + case "pt-BR": + return "Brasil"; + case "it": + return "Italiano"; + case "ca": + return "Català"; + case "ar": + return "العربية"; - } + } } } \ No newline at end of file