]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
Add Temporal::utcNow()
[friendica-addons.git] / twitter / twitter.php
index fabdc6bd0c88a8e36b21c445ec882b4a69be0756..cc12e8de8448dad7a223358b27fde337e35e6400 100644 (file)
@@ -2,11 +2,12 @@
 /**
  * Name: Twitter Connector
  * Description: Bidirectional (posting, relaying and reading) connector for Twitter.
- * Version: 1.0.4
+ * Version: 1.1.0
  * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
+ * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
  *
- * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
+ * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -56,7 +57,7 @@
  *     setting. After this, your user can configure their Twitter account settings
  *     from "Settings -> Addon Settings".
  *
- *     Requirements: PHP5, curl [Slinky library]
+ *     Requirements: PHP5, curl
  */
 
 use Abraham\TwitterOAuth\TwitterOAuth;
@@ -71,18 +72,20 @@ use Friendica\Core\PConfig;
 use Friendica\Core\Worker;
 use Friendica\Model\GContact;
 use Friendica\Model\Group;
+use Friendica\Model\Item;
 use Friendica\Model\Photo;
 use Friendica\Model\Queue;
 use Friendica\Model\User;
 use Friendica\Object\Image;
 use Friendica\Util\Network;
+use Friendica\Util\Temporal;
 
 require_once 'boot.php';
 require_once 'include/dba.php';
 require_once 'include/enotify.php';
 require_once 'include/text.php';
 
-require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
+require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
 
 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
 
@@ -151,11 +154,17 @@ function twitter_follow(App $a, &$contact)
 
        $uid = $a->user["uid"];
 
-       $ckey    = Config::get('twitter', 'consumerkey');
+       $ckey = Config::get('twitter', 'consumerkey');
        $csecret = Config::get('twitter', 'consumersecret');
-       $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
+       $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
        $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
 
+       // If the addon is not configured (general or for this user) quit here
+       if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
+               $contact = false;
+               return;
+       }
+
        $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
        $connection->post('friendships/create', ['screen_name' => $nickname]);
 
@@ -221,7 +230,7 @@ function twitter_settings_post(App $a, $post)
                        //  form as token and token2, we need a new connection to Twitter using these token
                        //  and secret to request a Access Token with the PIN
                        $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
-                       $token = $connection->getAccessToken($_POST['twitter-pin']);
+                       $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
                        //  ok, now that we have the Access Token, save them in the user config
                        PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
                        PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
@@ -257,10 +266,10 @@ function twitter_settings(App $a, &$s)
         * 2) If no OAuthtoken & stuff is present, generate button to get some
         * 3) Checkbox for "Send public notices (280 chars only)
         */
-       $ckey    = Config::get('twitter', 'consumerkey' );
-       $csecret = Config::get('twitter', 'consumersecret' );
-       $otoken  = PConfig::get(local_user(), 'twitter', 'oauthtoken'  );
-       $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret' );
+       $ckey    = Config::get('twitter', 'consumerkey');
+       $csecret = Config::get('twitter', 'consumersecret');
+       $otoken  = PConfig::get(local_user(), 'twitter', 'oauthtoken');
+       $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
 
        $enabled            = intval(PConfig::get(local_user(), 'twitter', 'post'));
        $defenabled         = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
@@ -296,18 +305,17 @@ function twitter_settings(App $a, &$s)
                         * account at Twitter.
                         */
                        $connection = new TwitterOAuth($ckey, $csecret);
-                       $request_token = $connection->getRequestToken();
-                       $token = $request_token['oauth_token'];
+                       $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
                        /*                       * *
                         *  make some nice form
                         */
                        $s .= '<p>' . L10n::t('At this Friendica instance the Twitter addon was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to Twitter.') . '</p>';
-                       $s .= '<a href="' . $connection->getAuthorizeURL($token) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
+                       $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result->oauth_token]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
                        $s .= '<div id="twitter-pin-wrapper">';
                        $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
                        $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
-                       $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $token . '" />';
-                       $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $request_token['oauth_token_secret'] . '" />';
+                       $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result->oauth_token . '" />';
+                       $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result->oauth_token_secret . '" />';
                        $s .= '</div><div class="clear"></div>';
                        $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
                } else {
@@ -425,7 +433,10 @@ function twitter_post_hook(App $a, &$b)
                logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
 
                // Looking if its a reply to a twitter post
-               if ((substr($b["parent-uri"], 0, 9) != "twitter::") && (substr($b["extid"], 0, 9) != "twitter::") && (substr($b["thr-parent"], 0, 9) != "twitter::")) {
+               if ((substr($b["parent-uri"], 0, 9) != "twitter::")
+                       && (substr($b["extid"], 0, 9) != "twitter::")
+                       && (substr($b["thr-parent"], 0, 9) != "twitter::"))
+               {
                        logger("twitter_post_hook: no twitter post " . $b["parent"]);
                        return;
                }
@@ -474,10 +485,12 @@ function twitter_post_hook(App $a, &$b)
 
        if ($b['verb'] == ACTIVITY_LIKE) {
                logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG);
-               if ($b['deleted'])
+               if ($b['deleted']) {
                        twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
-               else
+               } else {
                        twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
+               }
+
                return;
        }
 
@@ -511,7 +524,7 @@ function twitter_post_hook(App $a, &$b)
                        return;
                }
 
-               $tweet = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
+               $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
 
                $max_char = 280;
                $msgarr = BBCode::toPlaintext($b, $max_char, true, 8);
@@ -587,7 +600,7 @@ function twitter_post_hook(App $a, &$b)
                                $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
                        }
 
-                       $result = $tweet->post($url, $post);
+                       $result = $connection->post($url, $post);
                        logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
 
                        if ($result->source) {
@@ -619,8 +632,8 @@ function twitter_post_hook(App $a, &$b)
 
 function twitter_addon_admin_post(App $a)
 {
-       $consumerkey     = x($_POST, 'consumerkey')     ? notags(trim($_POST['consumerkey']))     : '';
-       $consumersecret  = x($_POST, 'consumersecret')  ? notags(trim($_POST['consumersecret']))  : '';
+       $consumerkey    = x($_POST, 'consumerkey')    ? notags(trim($_POST['consumerkey']))    : '';
+       $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : '';
        Config::set('twitter', 'consumerkey', $consumerkey);
        Config::set('twitter', 'consumersecret', $consumersecret);
        info(L10n::t('Settings updated.') . EOL);
@@ -665,10 +678,11 @@ function twitter_cron(App $a, $b)
        }
 
        $abandon_days = intval(Config::get('system', 'account_abandon_days'));
-       if ($abandon_days < 1)
+       if ($abandon_days < 1) {
                $abandon_days = 0;
+       }
 
-       $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
+       $abandon_limit = date(Temporal::MYSQL, time() - $abandon_days * 86400);
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
        if (count($r)) {
@@ -731,7 +745,7 @@ function twitter_expire(App $a, $b)
        if (count($r)) {
                foreach ($r as $rr) {
                        logger('twitter_expire: user ' . $rr['uid']);
-                       item_expire($rr['uid'], $days, NETWORK_TWITTER, true);
+                       Item::expire($rr['uid'], $days, NETWORK_TWITTER, true);
                }
        }
 
@@ -803,7 +817,14 @@ function twitter_do_mirrorpost(App $a, $uid, $post)
                // We don't support nested shares, so we mustn't show quotes as shares on retweets
                $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
 
-               $datarray['body'] = "\n" . share_header($item['author-name'], $item['author-link'], $item['author-avatar'], "", $item['created'], $item['plink']);
+               $datarray['body'] = "\n" . share_header(
+                       $item['author-name'],
+                       $item['author-link'],
+                       $item['author-avatar'],
+                       "",
+                       $item['created'],
+                       $item['plink']
+               );
 
                $datarray['body'] .= $item['body'] . '[/share]';
        } else {
@@ -977,7 +998,8 @@ function twitter_fetch_contact($uid, $contact, $create_user)
                "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]);
 
        $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
-               intval($uid), dbesc("twitter::" . $contact->id_str));
+               intval($uid),
+               dbesc("twitter::" . $contact->id_str));
 
        if (!count($r) && !$create_user) {
                return 0;
@@ -995,7 +1017,7 @@ function twitter_fetch_contact($uid, $contact, $create_user)
                                        `location`, `about`, `writable`, `blocked`, `readonly`, `pending`)
                                        VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
                        intval($uid),
-                       dbesc(datetime_convert()),
+                       dbesc(Temporal::utcNow()),
                        dbesc("https://twitter.com/" . $contact->screen_name),
                        dbesc(normalise_link("https://twitter.com/" . $contact->screen_name)),
                        dbesc($contact->screen_name."@twitter.com"),
@@ -1039,16 +1061,16 @@ function twitter_fetch_contact($uid, $contact, $create_user)
                                dbesc($photos[0]),
                                dbesc($photos[1]),
                                dbesc($photos[2]),
-                               dbesc(datetime_convert()),
-                               dbesc(datetime_convert()),
-                               dbesc(datetime_convert()),
+                               dbesc(Temporal::utcNow()),
+                               dbesc(Temporal::utcNow()),
+                               dbesc(Temporal::utcNow()),
                                intval($contact_id)
                        );
                }
        } else {
                // update profile photos once every two weeks as we have no notification of when they change.
-               //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
-               $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
+               //$update_photo = (($r[0]['avatar-date'] < Temporal::convert('now -2 days', '', '', )) ? true : false);
+               $update_photo = ($r[0]['avatar-date'] < Temporal::convert('now -12 hours'));
 
                // check that we have all the photos, this has been known to fail on occasion
                if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
@@ -1074,9 +1096,9 @@ function twitter_fetch_contact($uid, $contact, $create_user)
                                        dbesc($photos[0]),
                                        dbesc($photos[1]),
                                        dbesc($photos[2]),
-                                       dbesc(datetime_convert()),
-                                       dbesc(datetime_convert()),
-                                       dbesc(datetime_convert()),
+                                       dbesc(Temporal::utcNow()),
+                                       dbesc(Temporal::utcNow()),
+                                       dbesc(Temporal::utcNow()),
                                        dbesc("https://twitter.com/".$contact->screen_name),
                                        dbesc(normalise_link("https://twitter.com/".$contact->screen_name)),
                                        dbesc($contact->screen_name."@twitter.com"),
@@ -1095,9 +1117,9 @@ function twitter_fetch_contact($uid, $contact, $create_user)
 
 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
 {
-       $ckey    = Config::get('twitter', 'consumerkey');
+       $ckey = Config::get('twitter', 'consumerkey');
        $csecret = Config::get('twitter', 'consumersecret');
-       $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
+       $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
        $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
 
        $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
@@ -1357,8 +1379,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis
 
        // Don't import our own comments
        $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
-                       dbesc($postarray['uri']),
-                       intval($uid)
+               dbesc($postarray['uri']),
+               intval($uid)
        );
 
        if (count($r)) {
@@ -1372,8 +1394,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis
                $parent = "twitter::" . $post->in_reply_to_status_id_str;
 
                $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-                               dbesc($parent),
-                               intval($uid)
+                       dbesc($parent),
+                       intval($uid)
                );
                if (count($r)) {
                        $postarray['thr-parent'] = $r[0]["uri"];
@@ -1382,8 +1404,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis
                        $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
                } else {
                        $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
-                                       dbesc($parent),
-                                       intval($uid)
+                               dbesc($parent),
+                               intval($uid)
                        );
                        if (count($r)) {
                                $postarray['thr-parent'] = $r[0]['uri'];
@@ -1468,8 +1490,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis
        $converted = twitter_expand_entities($a, $postarray['body'], $post, false, $picture);
        $postarray['body'] = $converted["body"];
        $postarray['tag'] = $converted["tags"];
-       $postarray['created'] = datetime_convert('UTC', 'UTC', $post->created_at);
-       $postarray['edited'] = datetime_convert('UTC', 'UTC', $post->created_at);
+       $postarray['created'] = Temporal::convert($post->created_at);
+       $postarray['edited'] = Temporal::convert($post->created_at);
 
        $statustext = $converted["plain"];
 
@@ -1504,7 +1526,14 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis
 
                $postarray['body'] = $statustext;
 
-               $postarray['body'] .= "\n" . share_header($quoted['author-name'], $quoted['author-link'], $quoted['author-avatar'], "", $quoted['created'], $quoted['plink']);
+               $postarray['body'] .= "\n" . share_header(
+                       $quoted['author-name'],
+                       $quoted['author-link'],
+                       $quoted['author-avatar'],
+                       "",
+                       $quoted['created'],
+                       $quoted['plink']
+               );
 
                $postarray['body'] .= $quoted['body'] . '[/share]';
        }
@@ -1516,7 +1545,7 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
 {
        /// TODO: this whole function doesn't seem to work. Needs complete check
        $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
-                       intval($uid)
+               intval($uid)
        );
 
        if (!count($user)) {
@@ -1529,8 +1558,8 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
        }
 
        $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
-                       intval($uid),
-                       dbesc("twitter::".$own_id)
+               intval($uid),
+               dbesc("twitter::".$own_id)
        );
 
        if (!count($own_user)) {
@@ -1543,8 +1572,8 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
        }
 
        $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
-                       dbesc($postarray['parent-uri']),
-                       intval($uid)
+               dbesc($postarray['parent-uri']),
+               intval($uid)
        );
 
        if (count($myconv)) {
@@ -1566,7 +1595,7 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
                                'to_email' => $user[0]['email'],
                                'uid' => $user[0]['uid'],
                                'item' => $postarray,
-                               'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
+                               'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($top_item)),
                                'source_name' => $postarray['author-name'],
                                'source_link' => $postarray['author-link'],
                                'source_photo' => $postarray['author-avatar'],
@@ -1598,8 +1627,8 @@ function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_
                }
 
                $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
-                               dbesc("twitter::".$post->id_str),
-                               intval($uid)
+                       dbesc("twitter::".$post->id_str),
+                       intval($uid)
                );
 
                if (count($r)) {
@@ -1617,10 +1646,11 @@ function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_
                foreach ($posts as $post) {
                        $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
 
-                       if (trim($postarray['body']) == "")
+                       if (trim($postarray['body']) == "") {
                                continue;
+                       }
 
-                       $item = item_store($postarray);
+                       $item = Item::insert($postarray);
                        $postarray["id"] = $item;
 
                        logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
@@ -1736,7 +1766,7 @@ function twitter_fetchhometimeline(App $a, $uid)
                                continue;
                        }
 
-                       $item = item_store($postarray);
+                       $item = Item::insert($postarray);
                        $postarray["id"] = $item;
 
                        logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
@@ -1788,7 +1818,7 @@ function twitter_fetchhometimeline(App $a, $uid)
                                continue;
                        }
 
-                       $item = item_store($postarray);
+                       $item = Item::insert($postarray);
                        $postarray["id"] = $item;
 
                        if ($item && function_exists("check_item_notification")) {
@@ -1810,8 +1840,9 @@ function twitter_fetchhometimeline(App $a, $uid)
                                        $item = $r[0]['id'];
                                        $parent_id = $r[0]['parent'];
                                }
-                       } else
+                       } else {
                                $parent_id = $postarray['parent'];
+                       }
 
                        if (($item != 0) && !function_exists("check_item_notification")) {
                                require_once 'include/enotify.php';
@@ -1823,7 +1854,7 @@ function twitter_fetchhometimeline(App $a, $uid)
                                        'to_email'     => $u[0]['email'],
                                        'uid'          => $u[0]['uid'],
                                        'item'         => $postarray,
-                                       'link'         => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
+                                       'link'         => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($item)),
                                        'source_name'  => $postarray['author-name'],
                                        'source_link'  => $postarray['author-link'],
                                        'source_photo' => $postarray['author-avatar'],
@@ -1917,7 +1948,6 @@ function twitter_is_retweet(App $a, $uid, $body)
        $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
 
        $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
-
        $result = $connection->post('statuses/retweet/' . $id);
 
        logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);