3 * Name: Twitter Post Connector
4 * Description: Post to Twitter
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8 * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
9 * Maintainer: Michael Vogel <https://pirati.ca/profile/heluecht>
11 * Copyright (c) 2011-2023 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
12 * All rights reserved.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are met:
16 * * Redistributions of source code must retain the above copyright notice,
17 * this list of conditions and the following disclaimer.
18 * * Redistributions in binary form must reproduce the above
19 * * copyright notice, this list of conditions and the following disclaimer in
20 * the documentation and/or other materials provided with the distribution.
21 * * Neither the name of the <organization> nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
27 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
29 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
33 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
34 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 use Friendica\Content\Text\BBCode;
39 use Friendica\Content\Text\Plaintext;
40 use Friendica\Core\Hook;
41 use Friendica\Core\Logger;
42 use Friendica\Core\Renderer;
43 use Friendica\Core\Worker;
45 use Friendica\Model\Item;
46 use Friendica\Model\Post;
47 use Friendica\Core\Config\Util\ConfigFileManager;
48 use Friendica\Model\Photo;
49 use Friendica\Object\Image;
50 use GuzzleHttp\Client;
51 use GuzzleHttp\Exception\RequestException;
52 use GuzzleHttp\HandlerStack;
53 use GuzzleHttp\Subscriber\Oauth\Oauth1;
55 const TWITTER_IMAGE_SIZE = [2000000, 1000000, 500000, 100000, 50000];
57 function twitter_install()
59 Hook::register('load_config', __FILE__, 'twitter_load_config');
60 Hook::register('connector_settings', __FILE__, 'twitter_settings');
61 Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
62 Hook::register('hook_fork', __FILE__, 'twitter_hook_fork');
63 Hook::register('post_local', __FILE__, 'twitter_post_local');
64 Hook::register('notifier_normal', __FILE__, 'twitter_post_hook');
65 Hook::register('jot_networks', __FILE__, 'twitter_jot_nets');
68 function twitter_load_config(ConfigFileManager $loader)
70 DI::app()->getConfigCache()->load($loader->loadAddonConfig('twitter'), \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC);
73 function twitter_jot_nets(array &$jotnets_fields)
75 if (!DI::userSession()->getLocalUserId()) {
79 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post')) {
84 DI::l10n()->t('Post to Twitter'),
85 DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post_by_default')
91 function twitter_settings_post()
93 if (!DI::userSession()->getLocalUserId() || empty($_POST['twitter-submit'])) {
97 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'post', (bool)$_POST['twitter-enable']);
98 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'post_by_default', (bool)$_POST['twitter-default']);
99 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'api_key', $_POST['twitter-api-key']);
100 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'api_secret', $_POST['twitter-api-secret']);
101 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'access_token', $_POST['twitter-access-token']);
102 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'twitter', 'access_secret', $_POST['twitter-access-secret']);
105 function twitter_settings(array &$data)
107 if (!DI::userSession()->getLocalUserId()) {
111 $enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post') ?? false;
112 $def_enabled = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post_by_default') ?? false;
114 $api_key = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'api_key');
115 $api_secret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'api_secret');
116 $access_token = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'access_token');
117 $access_secret = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'access_secret');
119 $last_status = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'last_status');
120 if (empty($last_status)) {
121 $status = DI::l10n()->t('No status.');
122 } elseif (!empty($last_status['code'])) {
123 $status = print_r($last_status, true);
125 $status = print_r($last_status, true);
128 $t = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/twitter/');
129 $html = Renderer::replaceMacros($t, [
130 '$enable' => ['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.')],
131 '$default' => ['twitter-default', DI::l10n()->t('Send public postings to Twitter by default'), $def_enabled],
132 '$api_key' => ['twitter-api-key', DI::l10n()->t('API Key'), $api_key],
133 '$api_secret' => ['twitter-api-secret', DI::l10n()->t('API Secret'), $api_secret],
134 '$access_token' => ['twitter-access-token', DI::l10n()->t('Access Token'), $access_token],
135 '$access_secret' => ['twitter-access-secret', DI::l10n()->t('Access Secret'), $access_secret],
136 '$help' => DI::l10n()->t('Each user needs to register their own app to be able to post to Twitter. Please visit https://developer.twitter.com/en/portal/projects-and-apps to register a project. Inside the project you then have to register an app. You will find the needed data for the connector on the page "Keys and token" in the app settings.'),
137 '$status' => ['twitter-status', DI::l10n()->t('Last Status'), $status, '', '', 'readonly'],
141 'connector' => 'twitter',
142 'title' => DI::l10n()->t('Twitter Export'),
143 'enabled' => $enabled,
144 'image' => 'images/twitter.png',
149 function twitter_hook_fork(array &$b)
151 DI::logger()->debug('twitter_hook_fork', $b);
153 if ($b['name'] != 'notifier_normal') {
160 $post['deleted'] || $post['private'] || ($post['created'] !== $post['edited']) ||
161 !strstr($post['postopts'], 'twitter') || ($post['gravity'] != Item::GRAVITY_PARENT)
163 $b['execute'] = false;
168 function twitter_post_local(array &$b)
170 if (!DI::userSession()->getLocalUserId() || (DI::userSession()->getLocalUserId() != $b['uid'])) {
174 if ($b['edit'] || $b['private'] || $b['parent']) {
178 $twitter_post = (bool)DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post');
179 $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? (bool)$_REQUEST['twitter_enable'] : false);
181 // if API is used, default to the chosen settings
182 if ($b['api_source'] && intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'twitter', 'post_by_default'))) {
183 $twitter_enable = true;
186 if (!$twitter_enable) {
190 if (strlen($b['postopts'])) {
191 $b['postopts'] .= ',';
194 $b['postopts'] .= 'twitter';
197 function twitter_post_hook(array &$b)
199 DI::logger()->debug('Invoke post hook', $b);
201 if (($b['gravity'] != Item::GRAVITY_PARENT) || !strstr($b['postopts'], 'twitter') || $b['private'] || $b['deleted'] || ($b['created'] !== $b['edited'])) {
205 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], DI::contentItem()->addSharedPost($b));
207 Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
209 DI::pConfig()->load($b['uid'], 'twitter');
211 $api_key = DI::pConfig()->get($b['uid'], 'twitter', 'api_key');
212 $api_secret = DI::pConfig()->get($b['uid'], 'twitter', 'api_secret');
213 $access_token = DI::pConfig()->get($b['uid'], 'twitter', 'access_token');
214 $access_secret = DI::pConfig()->get($b['uid'], 'twitter', 'access_secret');
216 if (empty($api_key) || empty($api_secret) || empty($access_token) || empty($access_secret)) {
217 Logger::info('Missing keys, secrets or tokens.');
221 $msgarr = Plaintext::getPost($b, 280, true, BBCode::TWITTER);
222 Logger::debug('Got plaintext', ['id' => $b['id'], 'message' => $msgarr]);
226 if (!empty($msgarr['images']) || !empty($msgarr['remote_images'])) {
227 Logger::info('Got images', ['id' => $b['id'], 'images' => $msgarr['images'] ?? []]);
229 $retrial = Worker::getRetrial();
233 foreach ($msgarr['images'] ?? [] as $image) {
234 if (count($media_ids) == 4) {
238 $media_ids[] = twitter_upload_image($b['uid'], $image, $retrial);
239 } catch (RequestException $exception) {
240 Logger::warning('Error while uploading image', ['image' => $image, 'code' => $exception->getCode(), 'message' => $exception->getMessage()]);
247 $in_reply_to_tweet_id = 0;
249 Logger::debug('Post message', ['id' => $b['id'], 'parts' => count($msgarr['parts'])]);
250 foreach ($msgarr['parts'] as $key => $part) {
252 $id = twitter_post_status($b['uid'], $part, $media_ids, $in_reply_to_tweet_id);
253 Logger::info('twitter_post send', ['part' => $key, 'id' => $b['id'], 'result' => $id]);
254 } catch (RequestException $exception) {
255 Logger::warning('Error while posting message', ['part' => $key, 'id' => $b['id'], 'code' => $exception->getCode(), 'message' => $exception->getMessage()]);
257 'code' => $exception->getCode(),
258 'reason' => $exception->getResponse()->getReasonPhrase(),
259 'content' => $exception->getMessage()
261 DI::pConfig()->set($b['uid'], 'twitter', 'last_status', $status);
268 $in_reply_to_tweet_id = $id;
273 function twitter_post_status(int $uid, string $status, array $media_ids = [], string $in_reply_to_tweet_id = ''): string
275 $parameters = ['text' => $status];
276 if (!empty($media_ids)) {
277 $parameters['media'] = ['media_ids' => $media_ids];
279 if (!empty($in_reply_to_tweet_id)) {
280 $parameters['reply'] = ['in_reply_to_tweet_id' => $in_reply_to_tweet_id];
283 $response = twitter_post($uid, 'https://api.twitter.com/2/tweets', 'json', $parameters);
285 return $response->data->id;
288 function twitter_upload_image(int $uid, array $image, int $retrial)
290 if (!empty($image['id'])) {
291 $photo = Photo::selectFirst([], ['id' => $image['id']]);
293 $photo = Photo::createPhotoForExternalResource($image['url']);
296 $picturedata = Photo::getImageForPhoto($photo);
298 $picture = new Image($picturedata, $photo['type']);
299 $height = $picture->getHeight();
300 $width = $picture->getWidth();
301 $size = strlen($picturedata);
303 $picture = Photo::resizeToFileSize($picture, TWITTER_IMAGE_SIZE[$retrial]);
304 $new_height = $picture->getHeight();
305 $new_width = $picture->getWidth();
306 $picturedata = $picture->asString();
307 $new_size = strlen($picturedata);
309 Logger::info('Uploading', ['uid' => $uid, 'retrial' => $retrial, 'height' => $new_height, 'width' => $new_width, 'size' => $new_size, 'orig-height' => $height, 'orig-width' => $width, 'orig-size' => $size, 'image' => $image]);
310 $media = twitter_post($uid, 'https://upload.twitter.com/1.1/media/upload.json', 'form_params', ['media' => base64_encode($picturedata)]);
311 Logger::info('Uploading done', ['uid' => $uid, 'retrial' => $retrial, 'height' => $new_height, 'width' => $new_width, 'size' => $new_size, 'orig-height' => $height, 'orig-width' => $width, 'orig-size' => $size, 'image' => $image]);
313 if (isset($media->media_id_string)) {
314 $media_id = $media->media_id_string;
316 if (!empty($image['description'])) {
318 'media_id' => $media->media_id_string,
320 'text' => substr($image['description'], 0, 1000)
323 $ret = twitter_post($uid, 'https://upload.twitter.com/1.1/media/metadata/create.json', 'json', $data);
324 Logger::info('Metadata create', ['uid' => $uid, 'data' => $data, 'return' => $ret]);
327 Logger::error('Failed upload', ['uid' => $uid, 'size' => strlen($picturedata), 'image' => $image['url'], 'return' => $media]);
328 throw new Exception('Failed upload of ' . $image['url']);
334 function twitter_post(int $uid, string $url, string $type, array $data): stdClass
336 $stack = HandlerStack::create();
338 $middleware = new Oauth1([
339 'consumer_key' => DI::pConfig()->get($uid, 'twitter', 'api_key'),
340 'consumer_secret' => DI::pConfig()->get($uid, 'twitter', 'api_secret'),
341 'token' => DI::pConfig()->get($uid, 'twitter', 'access_token'),
342 'token_secret' => DI::pConfig()->get($uid, 'twitter', 'access_secret'),
345 $stack->push($middleware);
347 $client = new Client([
351 $response = $client->post($url, ['auth' => 'oauth', $type => $data]);
354 'code' => $response->getStatusCode(),
355 'reason' => $response->getReasonPhrase(),
356 'content' => $response->getBody()->getContents()
359 DI::pConfig()->set($uid, 'twitter', 'last_status', $status);
361 $content = json_decode($response->getBody()->getContents()) ?? new stdClass;
362 Logger::debug('Success', ['content' => $content]);