]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
Remove the use of app function
[friendica-addons.git] / twitter / twitter.php
index a68b5b6a98d18b279dda8e97eda6dda0b8b425e6..56b5ead84c43b6048c422a5df9eb67af7ac8875d 100644 (file)
@@ -66,8 +66,6 @@ use Abraham\TwitterOAuth\TwitterOAuth;
 use Abraham\TwitterOAuth\TwitterOAuthException;
 use Codebird\Codebird;
 use Friendica\App;
-use Friendica\Content\OEmbed;
-use Friendica\Content\PageInfo;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\Plaintext;
 use Friendica\Core\Hook;
@@ -148,7 +146,7 @@ function twitter_follow(App $a, array &$contact)
        $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
        $nickname = str_replace("@twitter.com", "", $nickname);
 
-       $uid = $a->user["uid"];
+       $uid = $a->getUserId();
 
        $ckey = DI::config()->get('twitter', 'consumerkey');
        $csecret = DI::config()->get('twitter', 'consumersecret');
@@ -268,6 +266,9 @@ function twitter_settings(App $a, &$s)
        if (!local_user()) {
                return;
        }
+
+       $user = User::getById(local_user());
+
        DI::page()['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . DI::baseUrl()->get() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
        /*       * *
         * 1) Check that we have global consumer key & secret
@@ -358,7 +359,7 @@ function twitter_settings(App $a, &$s)
                                $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-enable', DI::l10n()->t('Allow posting to Twitter'), $enabled, DI::l10n()->t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')]
                                ]);
-                               if ($a->user['hidewall']) {
+                               if ($user['hidewall']) {
                                        $s .= '<p>' . DI::l10n()->t('<strong>Note</strong>: Due to your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
                                }
                                $s .= Renderer::replaceMacros($field_checkbox, [
@@ -497,26 +498,30 @@ function twitter_action(App $a, $uid, $pid, $action)
 
        Logger::debug('before action', ['action' => $action, 'pid' => $pid, 'data' => $post]);
 
-       switch ($action) {
-               case 'delete':
-                       // To-Do: $result = $connection->post('statuses/destroy', $post);
-                       $result = [];
-                       break;
-               case 'like':
-                       $result = $connection->post('favorites/create', $post);
-                       if ($connection->getLastHttpCode() != 200) {
-                               Logger::warning('Unable to create favorite', ['result' => $result]);
-                       }
-                       break;
-               case 'unlike':
-                       $result = $connection->post('favorites/destroy', $post);
-                       if ($connection->getLastHttpCode() != 200) {
-                               Logger::warning('Unable to destroy favorite', ['result' => $result]);
-                       }
-                       break;
-               default:
-                       Logger::warning('Unhandled action', ['action' => $action]);
-                       $result = [];
+       try {
+               switch ($action) {
+                       case 'delete':
+                               // To-Do: $result = $connection->post('statuses/destroy', $post);
+                               $result = [];
+                               break;
+                       case 'like':
+                               $result = $connection->post('favorites/create', $post);
+                               if ($connection->getLastHttpCode() != 200) {
+                                       Logger::warning('Unable to create favorite', ['result' => $result]);
+                               }
+                               break;
+                       case 'unlike':
+                               $result = $connection->post('favorites/destroy', $post);
+                               if ($connection->getLastHttpCode() != 200) {
+                                       Logger::warning('Unable to destroy favorite', ['result' => $result]);
+                               }
+                               break;
+                       default:
+                               Logger::warning('Unhandled action', ['action' => $action]);
+                               $result = [];
+               }
+       } catch (TwitterOAuthException $twitterOAuthException) {
+               Logger::warning('Unable to communicate with twitter', ['action' => $action, 'data' => $post, 'code' => $twitterOAuthException->getCode(), 'exception' => $twitterOAuthException]);
        }
 
        Logger::info('after action', ['action' => $action, 'result' => $result]);
@@ -544,6 +549,8 @@ function twitter_post_hook(App $a, array &$b)
                return;
        }
 
+       $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
+
        $thr_parent = null;
 
        if ($b['parent'] != $b['id']) {
@@ -670,7 +677,7 @@ function twitter_post_hook(App $a, array &$b)
                $msg = $msgarr["text"];
 
                if (($msg == "") && isset($msgarr["title"])) {
-                       $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
+                       $msg = Plaintext::shorten($msgarr["title"], $max_char - 50, $b['uid']);
                }
 
                // Add the link to the body if the type isn't a photo or there are more than 4 images in the post
@@ -712,10 +719,10 @@ function twitter_post_hook(App $a, array &$b)
                                                        $data = ['media_id' => $media->media_id_string,
                                                                'alt_text' => ['text' => substr($image['description'], 0, 420)]];
                                                        $ret = $cb->media_metadata_create($data);
-                                                       Logger::info('Metadata create', ['id' => $b['id'], 'data' => $data, 'return' => json_encode($ret)]);
+                                                       Logger::info('Metadata create', ['id' => $b['id'], 'data' => $data, 'return' => $ret]);
                                                }
                                        } else {
-                                               Logger::error('Failed upload', ['id' => $b['id'], 'image' => $image['url']]);
+                                               Logger::error('Failed upload', ['id' => $b['id'], 'image' => $image['url'], 'return' => $media]);
                                                throw new Exception('Failed upload of ' . $image['url']);
                                        }
                                }
@@ -1213,6 +1220,7 @@ function twitter_user_to_contact($data)
                'location' => $data->location,
                'about'    => $data->description,
                'photo'    => twitter_fix_avatar($data->profile_image_url_https),
+               'header'   => $data->profile_banner_url ?? $data->profile_background_image_url_https,
        ];
 
        return $fields;
@@ -1356,13 +1364,13 @@ function twitter_fetchuser($screen_name)
  *
  * @param string   $body
  * @param stdClass $status
- * @param string   $picture
  * @return array
  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  */
-function twitter_expand_entities($body, stdClass $status, $picture)
+function twitter_expand_entities($body, stdClass $status)
 {
        $plain = $body;
+       $contains_urls = false;
 
        $taglist = [];
 
@@ -1403,40 +1411,17 @@ function twitter_expand_entities($body, stdClass $status, $picture)
                                continue;
                        }
 
-                       $expanded_url = $url->expanded_url;
-
-                       $final_url = DI::httpRequest()->finalUrl($url->expanded_url);
-
-                       $oembed_data = OEmbed::fetchURL($final_url);
+                       $contains_urls = true;
 
-                       $type = $oembed_data->type ?? '';
+                       $expanded_url = $url->expanded_url;
 
                        // Quickfix: Workaround for URL with '[' and ']' in it
                        if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
                                $expanded_url = $url->url;
                        }
 
-                       if ($type === 'photo' && !empty($oembed_data->url)) {
-                               $replace = '[url=' . $expanded_url . '][img]' . $oembed_data->url . '[/img][/url]';
-                       } elseif ($type === 'link') {
-                               $curlResult = DI::httpRequest()->head($final_url, ['timeout' => 4]);
-                               if ($curlResult->isSuccess()) {
-                                       $mimetype = $curlResult->getHeader('Content-Type');
-                               } else {
-                                       $mimetype = '';
-                               }
-
-                               if (substr($mimetype, 0, 6) == 'image/') {
-                                       $replace = '[img]' . $final_url . '[/img]';
-                               } else {
-                                       $replace = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
-                               }
-                       } else {
-                               $replace = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
-                       }
-
                        $replacementList[$url->indices[0]] = [
-                               'replace' => $replace,
+                               'replace' => '[url=' . $expanded_url . ']' . $url->display_url . '[/url]',
                                'length' => $url->indices[1] - $url->indices[0],
                        ];
                }
@@ -1450,14 +1435,7 @@ function twitter_expand_entities($body, stdClass $status, $picture)
 
        $body = trim($body);
 
-       // Footer will be taken care of with a share block in the case of a quote
-       if (empty($status->quoted_status)) {
-               if ($picture) {
-                       $body .= "\n\n[img]" . $picture . "[/img]\n";
-               }
-       }
-
-       return ['body' => trim($body), 'plain' => trim($plain), 'taglist' => $taglist];
+       return ['body' => trim($body), 'plain' => trim($plain), 'taglist' => $taglist, 'urls' => $contains_urls];
 }
 
 /**
@@ -1474,15 +1452,9 @@ function twitter_store_attachments(int $uriid, $post)
                                case 'photo':
                                        $attachment = ['uri-id' => $uriid, 'type' => Post\Media::IMAGE];
 
-                                       // @todo In the future store the large picture.
-                                       // This can be done when we don't embed the pictures in the body anymore.
-                                       //$attachment['url'] = $medium->media_url_https . '?name=large';
-                                       //$attachment['width'] = $medium->sizes->large->w;
-                                       //$attachment['height'] = $medium->sizes->large->h;
-
-                                       $attachment['url'] = $medium->media_url_https;
-                                       $attachment['width'] = $medium->sizes->medium->w;
-                                       $attachment['height'] = $medium->sizes->medium->h;
+                                       $attachment['url'] = $medium->media_url_https . '?name=large';
+                                       $attachment['width'] = $medium->sizes->large->w;
+                                       $attachment['height'] = $medium->sizes->large->h;
 
                                        if ($medium->sizes->small->w != $attachment['width']) {
                                                $attachment['preview'] = $medium->media_url_https . '?name=small';
@@ -1535,35 +1507,17 @@ function twitter_store_attachments(int $uriid, $post)
 /**
  * @brief Fetch media entities and add media links to the body
  *
- * @param object $post Twitter object with the post
- * @param array $postarray Array of the item that is about to be posted
- *
- * @return $picture string Image URL or empty string
+ * @param object  $post      Twitter object with the post
+ * @param array   $postarray Array of the item that is about to be posted
+ * @param integer $uriid URI Id used to store tags. -1 = don't store tags for this post.
  */
-function twitter_media_entities($post, array &$postarray)
+function twitter_media_entities($post, array &$postarray, int $uriid = -1)
 {
        // There are no media entities? So we quit.
        if (empty($post->extended_entities->media)) {
-               return '';
-       }
-
-       // When the post links to an external page, we only take one picture.
-       // We only do this when there is exactly one media.
-       if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
-               $medium = $post->extended_entities->media[0];
-               $picture = '';
-               foreach ($post->entities->urls as $link) {
-                       // Let's make sure the external link url matches the media url
-                       if ($medium->url == $link->url && isset($medium->media_url_https)) {
-                               $picture = $medium->media_url_https;
-                               $postarray['body'] = str_replace($medium->url, '', $postarray['body']);
-                               return $picture;
-                       }
-               }
+               return;
        }
 
-
-
        // This is a pure media post, first search for all media urls
        $media = [];
        foreach ($post->extended_entities->media AS $medium) {
@@ -1583,7 +1537,9 @@ function twitter_media_entities($post, array &$postarray)
                                $postarray['post-type'] = Item::PT_IMAGE;
                                break;
                        case 'video':
-                               $postarray['post-type'] = Item::PT_VIDEO;
+                               // Currently deactivated, since this causes the video to be display before the content
+                               // We have to figure out a better way for declaring the post type and the display style.
+                               //$postarray['post-type'] = Item::PT_VIDEO;
                        case 'animated_gif':
                                if (!empty($medium->ext_alt_text)) {
                                        Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
@@ -1604,18 +1560,20 @@ function twitter_media_entities($post, array &$postarray)
                                        }
                                }
                                break;
-                       // The following code will only be activated for test reasons
-                       //default:
-                       //      $postarray['body'] .= print_r($medium, true);
                }
        }
 
+       if ($uriid != -1) {
+               foreach ($media AS $key => $value) {
+                       $postarray['body'] = str_replace($key, '', $postarray['body']);
+               }
+               return;
+       }
+
        // Now we replace the media urls.
        foreach ($media AS $key => $value) {
                $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
        }
-
-       return '';
 }
 
 /**
@@ -1718,10 +1676,10 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
        $postarray['app'] = strip_tags($post->source);
 
        if ($post->user->protected) {
-               $postarray['private'] = 1;
+               $postarray['private'] = Item::PRIVATE;
                $postarray['allow_cid'] = '<' . $self['id'] . '>';
        } else {
-               $postarray['private'] = 0;
+               $postarray['private'] = Item::UNLISTED;
                $postarray['allow_cid'] = '';
        }
 
@@ -1737,9 +1695,15 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
        }
 
        // Search for media links
-       $picture = twitter_media_entities($post, $postarray);
+       twitter_media_entities($post, $postarray, $uriid);
+
+       $converted = twitter_expand_entities($postarray['body'], $post);
+
+       // When the post contains external links then images or videos are just "decorations".
+       if (!empty($converted['urls'])) {
+               $postarray['post-type'] = Item::PT_NOTE;
+       }
 
-       $converted = twitter_expand_entities($postarray['body'], $post, $picture);
        $postarray['body'] = $converted['body'];
        $postarray['created'] = DateTimeFormat::utc($post->created_at);
        $postarray['edited'] = DateTimeFormat::utc($post->created_at);