]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
Merge pull request #907 from annando/twitter-logging
[friendica-addons.git] / twitter / twitter.php
index ac23b84da417a9dd3ea990fb9b495fcd271373c6..4510caefab582c9af5534f9bacdf5607ec3028e0 100644 (file)
@@ -85,6 +85,7 @@ use Friendica\Model\Item;
 use Friendica\Model\ItemContent;
 use Friendica\Model\User;
 use Friendica\Object\Image;
+use Friendica\Protocol\Activity;
 use Friendica\Util\ConfigFileLoader;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
@@ -109,7 +110,7 @@ function twitter_install()
        Hook::register('expire'                 , __FILE__, 'twitter_expire');
        Hook::register('prepare_body'           , __FILE__, 'twitter_prepare_body');
        Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
-       Logger::log("installed twitter");
+       Logger::info("installed twitter");
 }
 
 function twitter_uninstall()
@@ -154,7 +155,7 @@ function twitter_check_item_notification(App $a, array &$notification_data)
 
 function twitter_follow(App $a, array &$contact)
 {
-       Logger::log("twitter_follow: Check if contact is twitter contact. " . $contact["url"], Logger::DEBUG);
+       Logger::info('Check if contact is twitter contact', ['url' => $contact["url"]]);
 
        if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
                return;
@@ -239,7 +240,7 @@ function twitter_settings_post(App $a)
        } else {
                if (isset($_POST['twitter-pin'])) {
                        //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
-                       Logger::log('got a Twitter PIN');
+                       Logger::notice('got a Twitter PIN');
                        $ckey    = Config::get('twitter', 'consumerkey');
                        $csecret = Config::get('twitter', 'consumersecret');
                        //  the token and secret for which the PIN was generated were hidden in the settings
@@ -352,7 +353,10 @@ function twitter_settings(App $a, &$s)
 
                                $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
 
-                               $s .= '<div id="twitter-info" >
+                               if (property_exists($details, 'screen_name') &&
+                                   property_exists($details, 'description') &&
+                                   property_exists($details, 'profile_image_url')) {
+                                       $s .= '<div id="twitter-info" >
                                        <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
                                                <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
                                        </p>
@@ -361,6 +365,12 @@ function twitter_settings(App $a, &$s)
                                                <em>' . $details->description . '</em>
                                        </p>
                                </div>';
+                               } else {
+                                       $s .= '<div id="twitter-info" >
+                                       <p>Invalid Twitter info</p>
+                               </div>';
+                                       Logger::info('Invalid twitter info (verify credentials).', ['auth' => TwitterOAuth::class]);
+                               }
                                $s .= '<div class="clear"></div>';
 
                                $s .= Renderer::replaceMacros($field_checkbox, [
@@ -419,7 +429,7 @@ function twitter_hook_fork(App $a, array &$b)
        if (PConfig::get($post['uid'], 'twitter', 'import')) {
                // Don't fork if it isn't a reply to a twitter post
                if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
-                       Logger::log('No twitter parent found for item ' . $post['id']);
+                       Logger::notice('No twitter parent found', ['item' => $post['id']]);
                        $b['execute'] = false;
                        return;
                }
@@ -547,11 +557,11 @@ function twitter_post_hook(App $a, array &$b)
                }
        }
 
-       if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
+       if (($b['verb'] == Activity::POST) && $b['deleted']) {
                twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
        }
 
-       if ($b['verb'] == ACTIVITY_LIKE) {
+       if ($b['verb'] == Activity::LIKE) {
                Logger::log("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), Logger::DEBUG);
                if ($b['deleted']) {
                        twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
@@ -614,14 +624,14 @@ function twitter_post_hook(App $a, array &$b)
                $b['body'] = twitter_update_mentions($b['body']);
 
                $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
-               Logger::info('Got plaintext', $msgarr);
+               Logger::info('Got plaintext', ['id' => $b['id'], 'message' => $msgarr]);
                $msg = $msgarr["text"];
 
                if (($msg == "") && isset($msgarr["title"])) {
                        $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
                }
 
-               if (($msgarr['url'] == $b['plink']) && !empty($msgarr['images']) && (count($msgarr['images']) <= 4)) {
+               if (!empty($msgarr['url']) && ($msgarr['url'] == $b['plink']) && !empty($msgarr['images']) && (count($msgarr['images']) <= 4)) {
                        $url_added = false;
                } elseif (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
                        $msg .= "\n" . $msgarr["url"];
@@ -631,6 +641,7 @@ function twitter_post_hook(App $a, array &$b)
                }
 
                if (empty($msg)) {
+                       Logger::info('Empty message', ['id' => $b['id']]);
                        return;
                }
 
@@ -638,6 +649,7 @@ function twitter_post_hook(App $a, array &$b)
                $post = [];
 
                if (!empty($msgarr['images'])) {
+                       Logger::info('Got images', ['id' => $b['id'], 'images' => $msgarr['images']]);
                        try {
                                $media_ids = [];
                                foreach ($msgarr['images'] as $image) {
@@ -650,6 +662,7 @@ function twitter_post_hook(App $a, array &$b)
                                        $tempfile = tempnam(get_temppath(), 'cache');
                                        file_put_contents($tempfile, $img_str);
 
+                                       Logger::info('Uploading', ['id' => $b['id'], 'image' => $image['url']]);
                                        $media = $connection->upload('media/upload', ['media' => $tempfile]);
 
                                        unlink($tempfile);
@@ -661,10 +674,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', ['data' => $data, 'return' => json_encode($ret)]);
+                                                       Logger::info('Metadata create', ['id' => $b['id'], 'data' => $data, 'return' => json_encode($ret)]);
                                                }
                                        } else {
-                                               throw new Exception('Failed upload of ' . $image['url']);
+                                               throw new Exception('Failed upload', ['id' => $b['id'], 'image' => $image['url']]);
                                        }
                                }
                                $post['media_ids'] = implode(',', $media_ids);
@@ -672,7 +685,7 @@ function twitter_post_hook(App $a, array &$b)
                                        unset($post['media_ids']);
                                }
                        } catch (Exception $e) {
-                               Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
+                               Logger::info('Exception when trying to send to Twitter', ['id' => $b['id'], 'message' => $e->getMessage()]);
                        }
                }
 
@@ -684,17 +697,17 @@ function twitter_post_hook(App $a, array &$b)
 
                $url = 'statuses/update';
                $result = $connection->post($url, $post);
-               Logger::log('twitter_post send, result: ' . print_r($result, true), Logger::DEBUG);
+               Logger::info('twitter_post send', ['id' => $b['id'], 'result' => $result]);
 
                if (!empty($result->source)) {
                        Config::set("twitter", "application_name", strip_tags($result->source));
                }
 
                if (!empty($result->errors)) {
-                       Logger::log('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
+                       Logger::info('Send to Twitter failed', ['id' => $b['id'], 'error' => $result->errors]);
                        Worker::defer();
                } elseif ($iscomment) {
-                       Logger::log('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
+                       Logger::info('Update extid', ['id' => $b['id'], 'extid' => $result->id_str]);
                        Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
                }
        }
@@ -733,16 +746,16 @@ function twitter_cron(App $a)
        if ($last) {
                $next = $last + ($poll_interval * 60);
                if ($next > time()) {
-                       Logger::log('twitter: poll intervall not reached');
+                       Logger::notice('twitter: poll intervall not reached');
                        return;
                }
        }
-       Logger::log('twitter: cron_start');
+       Logger::notice('twitter: cron_start');
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
        if (DBA::isResult($r)) {
                foreach ($r as $rr) {
-                       Logger::log('twitter: fetching for user ' . $rr['uid']);
+                       Logger::notice('Fetching', ['user' => $rr['uid']]);
                        Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
                }
        }
@@ -760,12 +773,12 @@ function twitter_cron(App $a)
                        if ($abandon_days != 0) {
                                $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
                                if (!DBA::isResult($user)) {
-                                       Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
+                                       Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $rr['uid']]);
                                        continue;
                                }
                        }
 
-                       Logger::log('twitter: importing timeline from user ' . $rr['uid']);
+                       Logger::notice('importing timeline', ['user' => $rr['uid']]);
                        Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
                        /*
                          // To-Do
@@ -784,7 +797,7 @@ function twitter_cron(App $a)
                }
        }
 
-       Logger::log('twitter: cron_end');
+       Logger::notice('twitter: cron_end');
 
        Config::set('twitter', 'last_poll', time());
 }
@@ -803,17 +816,17 @@ function twitter_expire(App $a)
        }
        DBA::close($r);
 
-       Logger::log('twitter_expire: expire_start');
+       Logger::notice('twitter_expire: expire_start');
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
        if (DBA::isResult($r)) {
                foreach ($r as $rr) {
-                       Logger::log('twitter_expire: user ' . $rr['uid']);
+                       Logger::notice('twitter_expire', ['user' => $rr['uid']]);
                        Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
                }
        }
 
-       Logger::log('twitter_expire: expire_end');
+       Logger::notice('twitter_expire: expire_end');
 }
 
 function twitter_prepare_body(App $a, array &$b)
@@ -947,12 +960,12 @@ function twitter_fetchtimeline(App $a, $uid)
        try {
                $items = $connection->get('statuses/user_timeline', $parameters);
        } catch (TwitterOAuthException $e) {
-               Logger::log('Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
+               Logger::notice('Error fetching timeline', ['user' => $uid, 'message' => $e->getMessage()]);
                return;
        }
 
        if (!is_array($items)) {
-               Logger::log('No items for user ' . $uid, Logger::INFO);
+               Logger::notice('No items', ['user' => $uid]);
                return;
        }
 
@@ -1027,6 +1040,7 @@ function twitter_fetch_contact($uid, $data, $create_user)
 
        $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
        if (!DBA::isResult($contact) && !$create_user) {
+               Logger::info('User contact not found', ['uid' => $uid, 'twitter-id' => $data->id_str]);
                return 0;
        }
 
@@ -1153,7 +1167,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
 
                        if ($url->url && $url->expanded_url && $url->display_url) {
                                // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
-                               if (isset($item->quoted_status_id_str)
+                               if (!empty($item->quoted_status) && isset($item->quoted_status_id_str)
                                        && substr($url->expanded_url, -strlen($item->quoted_status_id_str)) == $item->quoted_status_id_str ) {
                                        $body = str_replace($url->url, '', $body);
                                        continue;
@@ -1330,7 +1344,7 @@ function twitter_media_entities($post, array &$postarray)
                                        $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
                                }
 
-                               $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
+                               $postarray['object-type'] = Activity\ObjectType::IMAGE;
                                break;
                        case 'video':
                        case 'animated_gif':
@@ -1341,7 +1355,7 @@ function twitter_media_entities($post, array &$postarray)
                                        $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
                                }
 
-                               $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
+                               $postarray['object-type'] = Activity\ObjectType::VIDEO;
                                if (is_array($medium->video_info->variants)) {
                                        $bitrate = 0;
                                        // We take the video with the highest bitrate
@@ -1398,11 +1412,11 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
                        $postarray['thr-parent'] = $parent_item['uri'];
                        $postarray['parent-uri'] = $parent_item['parent-uri'];
                        $postarray['parent'] = $parent_item['parent'];
-                       $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
+                       $postarray['object-type'] = Activity\ObjectType::COMMENT;
                } else {
                        $postarray['thr-parent'] = $postarray['uri'];
                        $postarray['parent-uri'] = $postarray['uri'];
-                       $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
+                       $postarray['object-type'] = Activity\ObjectType::NOTE;
                }
 
                // Is it me?
@@ -1427,7 +1441,7 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
                $create_user = false;
        } else {
                $postarray['parent-uri'] = $postarray['uri'];
-               $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
+               $postarray['object-type'] = Activity\ObjectType::NOTE;
        }
 
        if ($contactid == 0) {
@@ -1447,7 +1461,7 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
 
        $postarray['contact-id'] = $contactid;
 
-       $postarray['verb'] = ACTIVITY_POST;
+       $postarray['verb'] = Activity::POST;
        $postarray['author-name'] = $postarray['owner-name'];
        $postarray['author-link'] = $postarray['owner-link'];
        $postarray['author-avatar'] = $postarray['owner-avatar'];
@@ -1470,7 +1484,7 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
 
        // When the post contains links then use the correct object type
        if (count($post->entities->urls) > 0) {
-               $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
+               $postarray['object-type'] = Activity\ObjectType::BOOKMARK;
        }
 
        // Search for media links
@@ -1508,9 +1522,9 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
                        Item::insert($retweet);
 
                        // CHange the other post into a reshare activity
-                       $postarray['verb'] = ACTIVITY2_ANNOUNCE;
+                       $postarray['verb'] = Activity::ANNOUNCE;
                        $postarray['gravity'] = GRAVITY_ACTIVITY;
-                       $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
+                       $postarray['object-type'] = Activity\ObjectType::NOTE;
 
                        $postarray['thr-parent'] = $retweet['uri'];
                        $postarray['parent-uri'] = $retweet['uri'];
@@ -1530,20 +1544,21 @@ function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $onl
        if (!empty($post->quoted_status) && !$noquote) {
                $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
 
-               if (empty($quoted['body'])) {
-                       return [];
+               if (!empty($quoted['body'])) {
+                       $postarray['body'] .= "\n" . share_header(
+                               $quoted['author-name'],
+                               $quoted['author-link'],
+                               $quoted['author-avatar'],
+                               "",
+                               $quoted['created'],
+                               $quoted['plink']
+                       );
+
+                       $postarray['body'] .= $quoted['body'] . '[/share]';
+               } else {
+                       // Quoted post author is blocked/ignored, so we just provide the link to avoid removing quote context.
+                       $postarray['body'] .= "\n\nhttps://twitter.com/" . $post->quoted_status->user->screen_name . "/status/" . $post->quoted_status->id_str;
                }
-
-               $postarray['body'] .= "\n" . share_header(
-                       $quoted['author-name'],
-                       $quoted['author-link'],
-                       $quoted['author-avatar'],
-                       "",
-                       $quoted['created'],
-                       $quoted['plink']
-               );
-
-               $postarray['body'] .= $quoted['body'] . '[/share]';
        }
 
        return $postarray;
@@ -1588,7 +1603,7 @@ function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection,
 
        if (!empty($posts)) {
                foreach ($posts as $post) {
-                       $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
+                       $postarray = twitter_createpost($a, $uid, $post, $self, false, !PConfig::get($uid, 'twitter', 'create_user'), false);
 
                        if (empty($postarray['body'])) {
                                continue;
@@ -1770,7 +1785,7 @@ function twitter_fetchhometimeline(App $a, $uid)
                                twitter_fetchparentposts($a, $uid, $post, $connection, $self);
                        }
 
-                       $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
+                       $postarray = twitter_createpost($a, $uid, $post, $self, false, !$create_user, false);
 
                        if (empty($postarray['body'])) {
                                continue;
@@ -1900,7 +1915,7 @@ function twitter_update_mentions($body)
 function twitter_convert_share(array $attributes, array $author_contact, $content, $is_quote_share)
 {
        if ($author_contact['network'] == Protocol::TWITTER) {
-               $mention = '@' . $author_contact['nickname'];
+               $mention = '@' . $author_contact['nick'];
        } else {
                $mention = $author_contact['addr'];
        }