wrong indent
[friendica-addons.git/.git] / twitter / twitter.php
index 77a3a26..bb2d38a 100644 (file)
  *     we do not need "Twitter as login". When you've registered the app you get the
  *     OAuth Consumer key and secret pair for your application/site.
  *
- *     Add this key pair to your global config/addon.ini.php or use the admin panel.
+ *     Add this key pair to your global config/addon.config.php or use the admin panel.
  *
- *     [twitter]
- *     consumerkey = your consumer_key here
- *     consumersecret = your consumer_secret here
+ *             'twitter' => [
+ *                 'consumerkey' => '',
+ *             'consumersecret' => '',
+ *      ],
  *
- *     To activate the addon itself add it to the [system] addon
+ *     To activate the addon itself add it to the system.addon
  *     setting. After this, your user can configure their Twitter account settings
  *     from "Settings -> Addon Settings".
  *
@@ -65,13 +66,16 @@ use Abraham\TwitterOAuth\TwitterOAuth;
 use Abraham\TwitterOAuth\TwitterOAuthException;
 use Friendica\App;
 use Friendica\Content\OEmbed;
+use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\Plaintext;
-use Friendica\Core\Addon;
 use Friendica\Core\Config;
+use Friendica\Core\Hook;
 use Friendica\Core\L10n;
 use Friendica\Core\Logger;
 use Friendica\Core\PConfig;
 use Friendica\Core\Protocol;
+use Friendica\Core\Renderer;
+use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\Model\Contact;
@@ -85,11 +89,7 @@ use Friendica\Model\User;
 use Friendica\Object\Image;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
-
-require_once 'boot.php';
-require_once 'include/dba.php';
-require_once 'include/enotify.php';
-require_once 'include/text.php';
+use Friendica\Util\Strings;
 
 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
 
@@ -98,45 +98,47 @@ define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
 function twitter_install()
 {
        //  we need some hooks, for the configuration and for sending tweets
-       Addon::registerHook('load_config'            , __FILE__, 'twitter_load_config');
-       Addon::registerHook('connector_settings'     , __FILE__, 'twitter_settings');
-       Addon::registerHook('connector_settings_post', __FILE__, 'twitter_settings_post');
-       Addon::registerHook('post_local'             , __FILE__, 'twitter_post_local');
-       Addon::registerHook('notifier_normal'        , __FILE__, 'twitter_post_hook');
-       Addon::registerHook('jot_networks'           , __FILE__, 'twitter_jot_nets');
-       Addon::registerHook('cron'                   , __FILE__, 'twitter_cron');
-       Addon::registerHook('queue_predeliver'       , __FILE__, 'twitter_queue_hook');
-       Addon::registerHook('follow'                 , __FILE__, 'twitter_follow');
-       Addon::registerHook('expire'                 , __FILE__, 'twitter_expire');
-       Addon::registerHook('prepare_body'           , __FILE__, 'twitter_prepare_body');
-       Addon::registerHook('check_item_notification', __FILE__, 'twitter_check_item_notification');
+       Hook::register('load_config'            , __FILE__, 'twitter_load_config');
+       Hook::register('connector_settings'     , __FILE__, 'twitter_settings');
+       Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
+       Hook::register('hook_fork'              , __FILE__, 'twitter_hook_fork');
+       Hook::register('post_local'             , __FILE__, 'twitter_post_local');
+       Hook::register('notifier_normal'        , __FILE__, 'twitter_post_hook');
+       Hook::register('jot_networks'           , __FILE__, 'twitter_jot_nets');
+       Hook::register('cron'                   , __FILE__, 'twitter_cron');
+       Hook::register('queue_predeliver'       , __FILE__, 'twitter_queue_hook');
+       Hook::register('follow'                 , __FILE__, 'twitter_follow');
+       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");
 }
 
 function twitter_uninstall()
 {
-       Addon::unregisterHook('load_config'            , __FILE__, 'twitter_load_config');
-       Addon::unregisterHook('connector_settings'     , __FILE__, 'twitter_settings');
-       Addon::unregisterHook('connector_settings_post', __FILE__, 'twitter_settings_post');
-       Addon::unregisterHook('post_local'             , __FILE__, 'twitter_post_local');
-       Addon::unregisterHook('notifier_normal'        , __FILE__, 'twitter_post_hook');
-       Addon::unregisterHook('jot_networks'           , __FILE__, 'twitter_jot_nets');
-       Addon::unregisterHook('cron'                   , __FILE__, 'twitter_cron');
-       Addon::unregisterHook('queue_predeliver'       , __FILE__, 'twitter_queue_hook');
-       Addon::unregisterHook('follow'                 , __FILE__, 'twitter_follow');
-       Addon::unregisterHook('expire'                 , __FILE__, 'twitter_expire');
-       Addon::unregisterHook('prepare_body'           , __FILE__, 'twitter_prepare_body');
-       Addon::unregisterHook('check_item_notification', __FILE__, 'twitter_check_item_notification');
+       Hook::unregister('load_config'            , __FILE__, 'twitter_load_config');
+       Hook::unregister('connector_settings'     , __FILE__, 'twitter_settings');
+       Hook::unregister('connector_settings_post', __FILE__, 'twitter_settings_post');
+       Hook::unregister('hook_fork'              , __FILE__, 'twitter_hook_fork');
+       Hook::unregister('post_local'             , __FILE__, 'twitter_post_local');
+       Hook::unregister('notifier_normal'        , __FILE__, 'twitter_post_hook');
+       Hook::unregister('jot_networks'           , __FILE__, 'twitter_jot_nets');
+       Hook::unregister('cron'                   , __FILE__, 'twitter_cron');
+       Hook::unregister('queue_predeliver'       , __FILE__, 'twitter_queue_hook');
+       Hook::unregister('follow'                 , __FILE__, 'twitter_follow');
+       Hook::unregister('expire'                 , __FILE__, 'twitter_expire');
+       Hook::unregister('prepare_body'           , __FILE__, 'twitter_prepare_body');
+       Hook::unregister('check_item_notification', __FILE__, 'twitter_check_item_notification');
 
        // old setting - remove only
-       Addon::unregisterHook('post_local_end'     , __FILE__, 'twitter_post_hook');
-       Addon::unregisterHook('addon_settings'     , __FILE__, 'twitter_settings');
-       Addon::unregisterHook('addon_settings_post', __FILE__, 'twitter_settings_post');
+       Hook::unregister('post_local_end'     , __FILE__, 'twitter_post_hook');
+       Hook::unregister('addon_settings'     , __FILE__, 'twitter_settings');
+       Hook::unregister('addon_settings_post', __FILE__, 'twitter_settings_post');
 }
 
 function twitter_load_config(App $a)
 {
-       $a->loadConfigFile(__DIR__ . '/config/twitter.ini.php');
+       $a->loadConfigFile(__DIR__ . '/config/twitter.config.php');
 }
 
 function twitter_check_item_notification(App $a, array &$notification_data)
@@ -259,7 +261,7 @@ function twitter_settings_post(App $a)
                                info($e->getMessage());
                        }
                        //  reload the Addon Settings page, if we don't do it see Bug #42
-                       $a->internalRedirect('settings/connectors');
+                       System::redirectTo('settings/connectors');
                } else {
                        //  if no PIN is supplied in the POST variables, the user has changed the setting
                        //  to post a tweet for every new __public__ posting to the wall
@@ -347,7 +349,7 @@ function twitter_settings(App $a, &$s)
                        try {
                                $details = $connection->get('account/verify_credentials');
 
-                               $field_checkbox = get_markup_template('field_checkbox.tpl');
+                               $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
 
                                $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>
@@ -360,22 +362,22 @@ function twitter_settings(App $a, &$s)
                                </div>';
                                $s .= '<div class="clear"></div>';
 
-                               $s .= replace_macros($field_checkbox, [
+                               $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-enable', L10n::t('Allow posting to Twitter'), $enabled, 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']) {
                                        $s .= '<p>' . 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 .= replace_macros($field_checkbox, [
+                               $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
                                ]);
-                               $s .= replace_macros($field_checkbox, [
+                               $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
                                ]);
-                               $s .= replace_macros($field_checkbox, [
+                               $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
                                ]);
-                               $s .= replace_macros($field_checkbox, [
+                               $s .= Renderer::replaceMacros($field_checkbox, [
                                        '$field' => ['twitter-create_user', L10n::t('Automatically create contacts'), $create_userenabled, L10n::t('This will automatically create a contact in Friendica as soon as you receive a message from an existing contact via the Twitter network. If you do not enable this, you need to manually add those Twitter contacts in Friendica from whom you would like to see posts here. However if enabled, you cannot merely remove a twitter contact from the Friendica contact list, as it will recreate this contact when they post again.')]
                                ]);
                                $s .= '<div class="clear"></div>';
@@ -388,6 +390,47 @@ function twitter_settings(App $a, &$s)
        $s .= '</div><div class="clear"></div>';
 }
 
+function twitter_hook_fork(App $a, array &$b)
+{
+       if ($b['name'] != 'notifier_normal') {
+               return;
+       }
+
+       $post = $b['data'];
+
+       // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
+       if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
+               $b['execute'] = false;
+               return;
+       }
+
+       // if post comes from twitter don't send it back
+       if ($post['extid'] == Protocol::TWITTER) {
+               $b['execute'] = false;
+               return;
+       }
+
+       if ($post['app'] == 'Twitter') {
+               $b['execute'] = false;
+               return;
+       }
+
+       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']);
+                       $b['execute'] = false;
+                       return;
+               }
+       } else {
+               // Comments are never exported when we don't import the twitter timeline
+               if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
+                       $b['execute'] = false;
+                       return;
+               }
+        }
+}
+
 function twitter_post_local(App $a, array &$b)
 {
        if ($b['edit']) {
@@ -399,7 +442,7 @@ function twitter_post_local(App $a, array &$b)
        }
 
        $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
-       $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
+       $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
 
        // if API is used, default to the chosen settings
        if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
@@ -656,8 +699,8 @@ function twitter_post_hook(App $a, array &$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    = !empty($_POST['consumerkey'])    ? Strings::escapeTags(trim($_POST['consumerkey']))    : '';
+       $consumersecret = !empty($_POST['consumersecret']) ? Strings::escapeTags(trim($_POST['consumersecret'])) : '';
        Config::set('twitter', 'consumerkey', $consumerkey);
        Config::set('twitter', 'consumersecret', $consumersecret);
        info(L10n::t('Settings updated.') . EOL);
@@ -665,9 +708,9 @@ function twitter_addon_admin_post(App $a)
 
 function twitter_addon_admin(App $a, &$o)
 {
-       $t = get_markup_template("admin.tpl", "addon/twitter/");
+       $t = Renderer::getMarkupTemplate("admin.tpl", "addon/twitter/");
 
-       $o = replace_macros($t, [
+       $o = Renderer::replaceMacros($t, [
                '$submit' => L10n::t('Save Settings'),
                // name, label, value, help, [extra values]
                '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
@@ -757,8 +800,6 @@ function twitter_expire(App $a)
        }
        DBA::close($r);
 
-       require_once "include/items.php";
-
        Logger::log('twitter_expire: expire_start');
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
@@ -888,7 +929,6 @@ function twitter_fetchtimeline(App $a, $uid)
        $has_picture = false;
 
        require_once 'mod/item.php';
-       require_once 'include/items.php';
        require_once 'mod/share.php';
 
        $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
@@ -1057,7 +1097,7 @@ function twitter_fetch_contact($uid, $data, $create_user)
                // create contact record
                $fields['uid'] = $uid;
                $fields['created'] = DateTimeFormat::utcNow();
-               $fields['nurl'] = normalise_link($url);
+               $fields['nurl'] = Strings::normaliseLink($url);
                $fields['alias'] = 'twitter::' . $data->id_str;
                $fields['poll'] = 'twitter::' . $data->id_str;
                $fields['rel'] = Contact::FRIEND;
@@ -1154,7 +1194,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
        $tags_arr = [];
 
        foreach ($item->entities->hashtags AS $hashtag) {
-               $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . rawurlencode($hashtag->text) . ']' . $hashtag->text . '[/url]';
+               $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
                $tags_arr['#' . $hashtag->text] = $url;
                $body = str_replace('#' . $hashtag->text, $url, $body);
        }
@@ -1182,9 +1222,11 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
                                        continue;
                                }
 
-                               $expanded_url = Network::finalUrl($url->expanded_url);
+                               $expanded_url = $url->expanded_url;
+
+                               $final_url = Network::finalUrl($url->expanded_url);
 
-                               $oembed_data = OEmbed::fetchURL($expanded_url);
+                               $oembed_data = OEmbed::fetchURL($final_url);
 
                                if (empty($oembed_data) || empty($oembed_data->type)) {
                                        continue;
@@ -1210,7 +1252,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
                                } elseif ($oembed_data->type != 'link') {
                                        $body = str_replace($url->url, '[url=' . $expanded_url . ']' . $url->display_url . '[/url]', $body);
                                } else {
-                                       $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
+                                       $img_str = Network::fetchUrl($final_url, true, $redirects, 4);
 
                                        $tempfile = tempnam(get_temppath(), 'cache');
                                        file_put_contents($tempfile, $img_str);
@@ -1226,7 +1268,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
 
                                        if (substr($mime, 0, 6) == 'image/') {
                                                $type = 'photo';
-                                               $body = str_replace($url->url, '[img]' . $expanded_url . '[/img]', $body);
+                                               $body = str_replace($url->url, '[img]' . $final_url . '[/img]', $body);
                                        } else {
                                                $type = $oembed_data->type;
                                                $footerurl = $expanded_url;
@@ -1263,7 +1305,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
        }
 
        // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
-       $tags = get_tags($body);
+       $tags = BBCode::getTags($body);
 
        if (count($tags)) {
                foreach ($tags as $tag) {
@@ -1285,7 +1327,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
                                }
 
                                $basetag = str_replace('_', ' ', substr($tag, 1));
-                               $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
+                               $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
                                $body = str_replace($tag, $url, $body);
                                $tags_arr['#' . $basetag] = $url;
                        } elseif (strpos($tag, '@') === 0) {
@@ -1616,8 +1658,6 @@ function twitter_fetchhometimeline(App $a, $uid)
                $application_name = $a->getHostName();
        }
 
-       require_once 'include/items.php';
-
        $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
 
        try {
@@ -1802,6 +1842,9 @@ function twitter_fetch_own_contact(App $a, $uid)
                // Fetching user data
                // get() may throw TwitterOAuthException, but we will catch it later
                $user = $connection->get('account/verify_credentials');
+               if (empty($user) || empty($user->id_str)) {
+                       return false;
+               }
 
                PConfig::set($uid, 'twitter', 'own_id', $user->id_str);