Avoid some notices in the statusnet addon
[friendica-addons.git/.git] / statusnet / statusnet.php
index 6fc5b8a..bc4ef36 100644 (file)
 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
 
 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'statusnetoauth.php';
-require_once 'include/enotify.php';
-
 use CodebirdSN\CodebirdSN;
 use Friendica\App;
 use Friendica\Content\OEmbed;
 use Friendica\Content\Text\HTML;
 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\Database\DBA;
+use Friendica\Model\Contact;
 use Friendica\Model\GContact;
 use Friendica\Model\Group;
 use Friendica\Model\Item;
@@ -55,42 +59,46 @@ use Friendica\Model\Photo;
 use Friendica\Model\User;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
-use Friendica\Database\DBM;
+use Friendica\Util\Strings;
 
 function statusnet_install()
 {
        //  we need some hooks, for the configuration and for sending tweets
-       Addon::registerHook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
-       Addon::registerHook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
-       Addon::registerHook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
-       Addon::registerHook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
-       Addon::registerHook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
-       Addon::registerHook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
-       Addon::registerHook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
-       Addon::registerHook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
-       logger("installed GNU Social");
+       Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
+       Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
+       Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
+       Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
+       Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
+       Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
+       Hook::register('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
+       Hook::register('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
+       Hook::register('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
+       Logger::log("installed GNU Social");
 }
 
 function statusnet_uninstall()
 {
-       Addon::unregisterHook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
-       Addon::unregisterHook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
-       Addon::unregisterHook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
-       Addon::unregisterHook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
-       Addon::unregisterHook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
-       Addon::unregisterHook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
-       Addon::unregisterHook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
-       Addon::unregisterHook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
+       Hook::unregister('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
+       Hook::unregister('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
+       Hook::unregister('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
+       Hook::unregister('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
+       Hook::unregister('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
+       Hook::unregister('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
+       Hook::unregister('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
+       Hook::unregister('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
+       Hook::unregister('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
 
        // old setting - remove only
-       Addon::unregisterHook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
-       Addon::unregisterHook('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
-       Addon::unregisterHook('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
+       Hook::unregister('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
+       Hook::unregister('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
+       Hook::unregister('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
 }
 
 function statusnet_check_item_notification(App $a, &$notification_data)
 {
-       $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
+       if (PConfig::get($notification_data["uid"], 'statusnet', 'post')) {
+               $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
+       }
 }
 
 function statusnet_jot_nets(App $a, &$b)
@@ -114,7 +122,7 @@ function statusnet_settings_post(App $a, $post)
                return;
        }
        // don't check GNU Social settings if GNU Social submit button is not clicked
-       if (!x($_POST, 'statusnet-submit')) {
+       if (empty($_POST['statusnet-submit'])) {
                return;
        }
 
@@ -133,7 +141,7 @@ function statusnet_settings_post(App $a, $post)
                PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
                PConfig::delete(local_user(), 'statusnet', 'import');
                PConfig::delete(local_user(), 'statusnet', 'create_user');
-               PConfig::delete(local_user(), 'statusnet', 'own_id');
+               PConfig::delete(local_user(), 'statusnet', 'own_url');
        } else {
                if (isset($_POST['statusnet-preconf-apiurl'])) {
                        /*                       * *
@@ -156,7 +164,7 @@ function statusnet_settings_post(App $a, $post)
                                        }
                                }
                        }
-                       goaway('settings/connectors');
+                       $a->internalRedirect('settings/connectors');
                } else {
                        if (isset($_POST['statusnet-consumersecret'])) {
                                //  check if we can reach the API of the GNU Social server
@@ -184,7 +192,7 @@ function statusnet_settings_post(App $a, $post)
                                                notice(L10n::t('We could not contact the GNU Social API with the Path you entered.') . EOL);
                                        }
                                }
-                               goaway('settings/connectors');
+                               $a->internalRedirect('settings/connectors');
                        } else {
                                if (isset($_POST['statusnet-pin'])) {
                                        //  if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
@@ -202,7 +210,7 @@ function statusnet_settings_post(App $a, $post)
                                        PConfig::set(local_user(), 'statusnet', 'post', 1);
                                        PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
                                        //  reload the Addon Settings page, if we don't do it see Bug #42
-                                       goaway('settings/connectors');
+                                       $a->internalRedirect('settings/connectors');
                                } else {
                                        //  if no PIN is supplied in the POST variables, the user has changed the setting
                                        //  to post a dent for every new __public__ posting to the wall
@@ -227,7 +235,7 @@ function statusnet_settings(App $a, &$s)
        if (!local_user()) {
                return;
        }
-       $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
+       $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->getBaseURL() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
        /*       * *
         * 1) Check that we have a base api url and a consumer key & secret
         * 2) If no OAuthtoken & stuff is present, generate button to get some
@@ -341,7 +349,9 @@ function statusnet_settings(App $a, &$s)
                         */
                        $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
                        $details = $connection->get('account/verify_credentials');
-                       $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="' . $details->profile_image_url . '" /><p id="statusnet-info-block">' . L10n::t('Currently connected to: ') . '<a href="' . $details->statusnet_profile_url . '" target="_statusnet">' . $details->screen_name . '</a><br /><em>' . $details->description . '</em></p></div>';
+                       if (!empty($details)) {
+                               $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="' . $details->profile_image_url . '" /><p id="statusnet-info-block">' . L10n::t('Currently connected to: ') . '<a href="' . $details->statusnet_profile_url . '" target="_statusnet">' . $details->screen_name . '</a><br /><em>' . $details->description . '</em></p></div>';
+                       }
                        $s .= '<p>' . L10n::t('If enabled all your <strong>public</strong> postings can be posted to the associated GNU Social account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') . '</p>';
                        if ($a->user['hidewall']) {
                                $s .= '<p>' . L10n::t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
@@ -384,6 +394,47 @@ function statusnet_settings(App $a, &$s)
        $s .= '</div><div class="clear"></div>';
 }
 
+function statusnet_hook_fork(App $a, array &$b)
+{
+       if ($b['name'] != 'notifier_normal') {
+               return;
+       }
+
+       $post = $b['data'];
+
+       // Deleting and editing is not supported by the addon
+       if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
+               $b['execute'] = false;
+               return;
+       }
+
+       // if post comes from GNU Social don't send it back
+       if ($post['extid'] == Protocol::STATUSNET) {
+               $b['execute'] = false;
+               return;
+       }
+
+       if ($post['app'] == 'StatusNet') {
+               $b['execute'] = false;
+               return;
+       }
+
+       if (PConfig::get($post['uid'], 'statusnet', 'import')) {
+               // Don't fork if it isn't a reply to a GNU Social post
+               if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::STATUSNET])) {
+                       Logger::log('No GNU Social parent found for item ' . $post['id']);
+                       $b['execute'] = false;
+                       return;
+               }
+       } else {
+               // Comments are never exported when we don't import the GNU Social timeline
+               if (!strstr($post['postopts'], 'statusnet') || ($post['parent'] != $post['id']) || $post['private']) {
+                       $b['execute'] = false;
+                       return;
+               }
+       }
+}
+
 function statusnet_post_local(App $a, &$b)
 {
        if ($b['edit']) {
@@ -395,7 +446,7 @@ function statusnet_post_local(App $a, &$b)
        }
 
        $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
-       $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
+       $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
 
        // if API is used, default to the chosen settings
        if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
@@ -423,7 +474,7 @@ function statusnet_action(App $a, $uid, $pid, $action)
 
        $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
 
-       logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA);
+       Logger::log("statusnet_action '" . $action . "' ID: " . $pid, Logger::DATA);
 
        switch ($action) {
                case "delete":
@@ -436,7 +487,7 @@ function statusnet_action(App $a, $uid, $pid, $action)
                        $result = $connection->post("favorites/destroy/" . $pid);
                        break;
        }
-       logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
+       Logger::log("statusnet_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
 }
 
 function statusnet_post_hook(App $a, &$b)
@@ -453,19 +504,19 @@ function statusnet_post_hook(App $a, &$b)
        $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
 
        if ($b['parent'] != $b['id']) {
-               logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
+               Logger::log("statusnet_post_hook: parameter " . print_r($b, true), Logger::DATA);
 
                // Looking if its a reply to a GNU Social post
                $hostlength = strlen($hostname) + 2;
                if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
-                       logger("statusnet_post_hook: no GNU Social post " . $b["parent"]);
+                       Logger::log("statusnet_post_hook: no GNU Social post " . $b["parent"]);
                        return;
                }
 
                $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
                $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
-               if (!DBM::is_result($orig_post)) {
-                       logger("statusnet_post_hook: no parent found " . $b["thr-parent"]);
+               if (!DBA::isResult($orig_post)) {
+                       Logger::log("statusnet_post_hook: no parent found " . $b["thr-parent"]);
                        return;
                } else {
                        $iscomment = true;
@@ -476,12 +527,12 @@ function statusnet_post_hook(App $a, &$b)
                $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
                $nicknameplain = "@" . $nick;
 
-               logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
+               Logger::log("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
                if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
                        $b["body"] = $nickname . " " . $b["body"];
                }
 
-               logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
+               Logger::log("statusnet_post_hook: parent found " . print_r($orig_post, true), Logger::DEBUG);
        } else {
                $iscomment = false;
 
@@ -491,7 +542,7 @@ function statusnet_post_hook(App $a, &$b)
 
                // Dont't post if the post doesn't belong to us.
                // This is a check for forum postings
-               $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
+               $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
                if ($b['contact-id'] != $self['id']) {
                        return;
                }
@@ -502,7 +553,7 @@ function statusnet_post_hook(App $a, &$b)
        }
 
        if ($b['verb'] == ACTIVITY_LIKE) {
-               logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
+               Logger::log("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), Logger::DEBUG);
                if ($b['deleted'])
                        statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
                else
@@ -515,7 +566,7 @@ function statusnet_post_hook(App $a, &$b)
        }
 
        // if posts comes from GNU Social don't send it back
-       if ($b['extid'] == NETWORK_STATUSNET) {
+       if ($b['extid'] == Protocol::STATUSNET) {
                return;
        }
 
@@ -523,7 +574,7 @@ function statusnet_post_hook(App $a, &$b)
                return;
        }
 
-       logger('GNU Socialpost invoked');
+       Logger::log('GNU Socialpost invoked');
 
        PConfig::load($b['uid'], 'statusnet');
 
@@ -572,7 +623,7 @@ function statusnet_post_hook(App $a, &$b)
                if (strlen($msg)) {
                        if ($iscomment) {
                                $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
-                               logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
+                               Logger::log('statusnet_post send reply ' . print_r($postdata, true), Logger::DEBUG);
                        }
 
                        // New code that is able to post pictures
@@ -583,17 +634,17 @@ function statusnet_post_hook(App $a, &$b)
                        $cb->setToken($otoken, $osecret);
                        $result = $cb->statuses_update($postdata);
                        //$result = $dent->post('statuses/update', $postdata);
-                       logger('statusnet_post send, result: ' . print_r($result, true) .
-                               "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
+                       Logger::log('statusnet_post send, result: ' . print_r($result, true) .
+                               "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true), Logger::DEBUG);
 
-                       if ($result->source) {
+                       if (!empty($result->source)) {
                                PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
                        }
 
-                       if ($result->error) {
-                               logger('Send to GNU Social failed: "' . $result->error . '"');
+                       if (!empty($result->error)) {
+                               Logger::log('Send to GNU Social failed: "' . $result->error . '"');
                        } elseif ($iscomment) {
-                               logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
+                               Logger::log('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
                                Item::update(['extid' => $hostname . "::" . $result->id, 'body' => $result->text], ['id' => $b['id']]);
                        }
                }
@@ -615,12 +666,12 @@ function statusnet_addon_admin_post(App $a)
                }
                $secret = trim($_POST['secret'][$id]);
                $key = trim($_POST['key'][$id]);
-               //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
+               //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
                if ($sitename != "" &&
                        $apiurl != "" &&
                        $secret != "" &&
                        $key != "" &&
-                       !x($_POST['delete'][$id])) {
+                       empty($_POST['delete'][$id])) {
 
                        $sites[] = [
                                'sitename' => $sitename,
@@ -652,7 +703,7 @@ function statusnet_addon_admin(App $a, &$o)
                }
        }
        /* empty form to add new site */
-       $id++;
+       $id = count($sitesform);
        $sitesform[] = [
                'sitename' => ["sitename[$id]", L10n::t("Site name"), "", ""],
                'apiurl' => ["apiurl[$id]", "Api url", "", L10n::t("Base API Path \x28remember the trailing /\x29")],
@@ -661,8 +712,8 @@ function statusnet_addon_admin(App $a, &$o)
                //'applicationname' => Array("applicationname[$id]", L10n::t("Application name"), "", ""),
        ];
 
-       $t = get_markup_template("admin.tpl", "addon/statusnet/");
-       $o = replace_macros($t, [
+       $t = Renderer::getMarkupTemplate("admin.tpl", "addon/statusnet/");
+       $o = Renderer::replaceMacros($t, [
                '$submit' => L10n::t('Save Settings'),
                '$sites' => $sitesform,
        ]);
@@ -670,7 +721,7 @@ function statusnet_addon_admin(App $a, &$o)
 
 function statusnet_prepare_body(App $a, &$b)
 {
-       if ($b["item"]["network"] != NETWORK_STATUSNET) {
+       if ($b["item"]["network"] != Protocol::STATUSNET) {
                return;
        }
 
@@ -681,11 +732,11 @@ function statusnet_prepare_body(App $a, &$b)
                }
 
                $item = $b["item"];
-               $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
+               $item["plink"] = $a->getBaseURL() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
 
                $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
                $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
-               if (DBM::is_result($orig_post)) {
+               if (DBA::isResult($orig_post)) {
                        $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
 
                        $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
@@ -723,16 +774,16 @@ function statusnet_cron(App $a, $b)
        if ($last) {
                $next = $last + ($poll_interval * 60);
                if ($next > time()) {
-                       logger('statusnet: poll intervall not reached');
+                       Logger::log('statusnet: poll intervall not reached');
                        return;
                }
        }
-       logger('statusnet: cron_start');
+       Logger::log('statusnet: cron_start');
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
-       if (DBM::is_result($r)) {
+       if (DBA::isResult($r)) {
                foreach ($r as $rr) {
-                       logger('statusnet: fetching for user ' . $rr['uid']);
+                       Logger::log('statusnet: fetching for user ' . $rr['uid']);
                        statusnet_fetchtimeline($a, $rr['uid']);
                }
        }
@@ -745,22 +796,22 @@ function statusnet_cron(App $a, $b)
        $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
 
        $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
-       if (DBM::is_result($r)) {
+       if (DBA::isResult($r)) {
                foreach ($r as $rr) {
                        if ($abandon_days != 0) {
                                $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
-                               if (!DBM::is_result($user)) {
-                                       logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
+                               if (!DBA::isResult($user)) {
+                                       Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
                                        continue;
                                }
                        }
 
-                       logger('statusnet: importing timeline from user ' . $rr['uid']);
+                       Logger::log('statusnet: importing timeline from user ' . $rr['uid']);
                        statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
                }
        }
 
-       logger('statusnet: cron_end');
+       Logger::log('statusnet: cron_end');
 
        Config::set('statusnet', 'last_poll', time());
 }
@@ -775,8 +826,6 @@ function statusnet_fetchtimeline(App $a, $uid)
        $lastid  = PConfig::get($uid, 'statusnet', 'lastid');
 
        require_once 'mod/item.php';
-       require_once 'include/items.php';
-
        //  get the application name for the SN app
        //  1st try personal config, then system config and fallback to the
        //  hostname of the node if neither one is set.
@@ -785,7 +834,7 @@ function statusnet_fetchtimeline(App $a, $uid)
                $application_name = Config::get('statusnet', 'application_name');
        }
        if ($application_name == "") {
-               $application_name = $a->get_hostname();
+               $application_name = $a->getHostName();
        }
 
        $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
@@ -819,7 +868,7 @@ function statusnet_fetchtimeline(App $a, $uid)
                                continue;
                        }
 
-                       if (is_object($post->retweeted_status)) {
+                       if (!empty($post->retweeted_status)) {
                                continue;
                        }
 
@@ -832,15 +881,14 @@ function statusnet_fetchtimeline(App $a, $uid)
                                $_SESSION["uid"] = $uid;
 
                                unset($_REQUEST);
-                               $_REQUEST["type"] = "wall";
                                $_REQUEST["api_source"] = true;
                                $_REQUEST["profile_uid"] = $uid;
                                //$_REQUEST["source"] = "StatusNet";
                                $_REQUEST["source"] = $post->source;
-                               $_REQUEST["extid"] = NETWORK_STATUSNET;
+                               $_REQUEST["extid"] = Protocol::STATUSNET;
 
                                if (isset($post->id)) {
-                                       $_REQUEST['message_id'] = Item::newURI($uid, NETWORK_STATUSNET . ":" . $post->id);
+                                       $_REQUEST['message_id'] = Item::newURI($uid, Protocol::STATUSNET . ":" . $post->id);
                                }
 
                                //$_REQUEST["date"] = $post->created_at;
@@ -866,7 +914,7 @@ function statusnet_fetchtimeline(App $a, $uid)
 
                                //print_r($_REQUEST);
                                if ($_REQUEST["body"] != "") {
-                                       logger('statusnet: posting for user ' . $uid);
+                                       Logger::log('statusnet: posting for user ' . $uid);
 
                                        item_post($a);
                                }
@@ -878,7 +926,7 @@ function statusnet_fetchtimeline(App $a, $uid)
 
 function statusnet_address($contact)
 {
-       $hostname = normalise_link($contact->statusnet_profile_url);
+       $hostname = Strings::normaliseLink($contact->statusnet_profile_url);
        $nickname = $contact->screen_name;
 
        $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
@@ -890,58 +938,58 @@ function statusnet_address($contact)
 
 function statusnet_fetch_contact($uid, $contact, $create_user)
 {
-       if ($contact->statusnet_profile_url == "") {
+       if (empty($contact->statusnet_profile_url)) {
                return -1;
        }
 
        GContact::update(["url" => $contact->statusnet_profile_url,
-               "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
+               "network" => Protocol::STATUSNET, "photo" => $contact->profile_image_url,
                "name" => $contact->name, "nick" => $contact->screen_name,
                "location" => $contact->location, "about" => $contact->description,
                "addr" => statusnet_address($contact), "generation" => 3]);
 
-       $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
+       $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)), DBA::escape(Protocol::STATUSNET));
 
-       if (!DBM::is_result($r) && !$create_user) {
+       if (!DBA::isResult($r) && !$create_user) {
                return 0;
        }
 
-       if (DBM::is_result($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
-               logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
+       if (DBA::isResult($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
+               Logger::log("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", Logger::DEBUG);
                return -1;
        }
 
-       if (!DBM::is_result($r)) {
+       if (!DBA::isResult($r)) {
                // create contact record
                q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
                                        `name`, `nick`, `photo`, `network`, `rel`, `priority`,
                                        `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(DateTimeFormat::utcNow()),
-                       dbesc($contact->statusnet_profile_url),
-                       dbesc(normalise_link($contact->statusnet_profile_url)),
-                       dbesc(statusnet_address($contact)),
-                       dbesc(normalise_link($contact->statusnet_profile_url)),
-                       dbesc(''),
-                       dbesc(''),
-                       dbesc($contact->name),
-                       dbesc($contact->screen_name),
-                       dbesc($contact->profile_image_url),
-                       dbesc(NETWORK_STATUSNET),
-                       intval(CONTACT_IS_FRIEND),
+                       DBA::escape(DateTimeFormat::utcNow()),
+                       DBA::escape($contact->statusnet_profile_url),
+                       DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
+                       DBA::escape(statusnet_address($contact)),
+                       DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
+                       DBA::escape(''),
+                       DBA::escape(''),
+                       DBA::escape($contact->name),
+                       DBA::escape($contact->screen_name),
+                       DBA::escape($contact->profile_image_url),
+                       DBA::escape(Protocol::STATUSNET),
+                       intval(Contact::FRIEND),
                        intval(1),
-                       dbesc($contact->location),
-                       dbesc($contact->description),
+                       DBA::escape($contact->location),
+                       DBA::escape($contact->description),
                        intval(1)
                );
 
                $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
-                       dbesc($contact->statusnet_profile_url),
+                       DBA::escape($contact->statusnet_profile_url),
                        intval($uid),
-                       dbesc(NETWORK_STATUSNET));
+                       DBA::escape(Protocol::STATUSNET));
 
-               if (!DBM::is_result($r)) {
+               if (!DBA::isResult($r)) {
                        return false;
                }
 
@@ -956,10 +1004,10 @@ function statusnet_fetch_contact($uid, $contact, $create_user)
                                        `micro` = '%s',
                                        `avatar-date` = '%s'
                                WHERE `id` = %d",
-                       dbesc($photos[0]),
-                       dbesc($photos[1]),
-                       dbesc($photos[2]),
-                       dbesc(DateTimeFormat::utcNow()),
+                       DBA::escape($photos[0]),
+                       DBA::escape($photos[1]),
+                       DBA::escape($photos[2]),
+                       DBA::escape(DateTimeFormat::utcNow()),
                        intval($contact_id)
                );
        } else {
@@ -969,7 +1017,7 @@ function statusnet_fetch_contact($uid, $contact, $create_user)
 
                // 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)) {
-                       logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
+                       Logger::log("statusnet_fetch_contact: Updating contact " . $contact->screen_name, Logger::DEBUG);
 
                        $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
 
@@ -987,19 +1035,19 @@ function statusnet_fetch_contact($uid, $contact, $create_user)
                                                `location` = '%s',
                                                `about` = '%s'
                                        WHERE `id` = %d",
-                               dbesc($photos[0]),
-                               dbesc($photos[1]),
-                               dbesc($photos[2]),
-                               dbesc(DateTimeFormat::utcNow()),
-                               dbesc(DateTimeFormat::utcNow()),
-                               dbesc(DateTimeFormat::utcNow()),
-                               dbesc($contact->statusnet_profile_url),
-                               dbesc(normalise_link($contact->statusnet_profile_url)),
-                               dbesc(statusnet_address($contact)),
-                               dbesc($contact->name),
-                               dbesc($contact->screen_name),
-                               dbesc($contact->location),
-                               dbesc($contact->description),
+                               DBA::escape($photos[0]),
+                               DBA::escape($photos[1]),
+                               DBA::escape($photos[2]),
+                               DBA::escape(DateTimeFormat::utcNow()),
+                               DBA::escape(DateTimeFormat::utcNow()),
+                               DBA::escape(DateTimeFormat::utcNow()),
+                               DBA::escape($contact->statusnet_profile_url),
+                               DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
+                               DBA::escape(statusnet_address($contact)),
+                               DBA::escape($contact->name),
+                               DBA::escape($contact->screen_name),
+                               DBA::escape($contact->location),
+                               DBA::escape($contact->description),
                                intval($r[0]['id'])
                        );
                }
@@ -1025,7 +1073,7 @@ function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
        $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
                intval($uid));
 
-       if (DBM::is_result($r)) {
+       if (DBA::isResult($r)) {
                $self = $r[0];
        } else {
                return;
@@ -1055,13 +1103,13 @@ function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
 
 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
 {
-       logger("statusnet_createpost: start", LOGGER_DEBUG);
+       Logger::log("statusnet_createpost: start", Logger::DEBUG);
 
        $api = PConfig::get($uid, 'statusnet', 'baseapi');
        $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
 
        $postarray = [];
-       $postarray['network'] = NETWORK_STATUSNET;
+       $postarray['network'] = Protocol::STATUSNET;
        $postarray['uid'] = $uid;
        $postarray['wall'] = 0;
 
@@ -1074,7 +1122,7 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex
 
        $postarray['uri'] = $hostname . "::" . $content->id;
 
-       if (dba::exists('item', ['extid' => $postarray['uri'], 'uid' => $uid])) {
+       if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
                return [];
        }
 
@@ -1087,11 +1135,11 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex
                $fields = ['uri', 'parent-uri', 'parent'];
                $item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
 
-               if (!DBM::is_result($item)) {
+               if (!DBA::isResult($item)) {
                        $item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
                }
 
-               if (DBM::is_result($item)) {
+               if (DBA::isResult($item)) {
                        $postarray['thr-parent'] = $item['uri'];
                        $postarray['parent-uri'] = $item['parent-uri'];
                        $postarray['parent'] = $item['parent'];
@@ -1109,7 +1157,7 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex
                        $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
                                intval($uid));
 
-                       if (DBM::is_result($r)) {
+                       if (DBA::isResult($r)) {
                                $contactid = $r[0]["id"];
 
                                $postarray['owner-name'] = $r[0]["name"];
@@ -1182,7 +1230,7 @@ function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_ex
                $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
        }
 
-       logger("statusnet_createpost: end", LOGGER_DEBUG);
+       Logger::log("statusnet_createpost: end", Logger::DEBUG);
 
        return $postarray;
 }
@@ -1201,39 +1249,41 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
        // "create_user" is deactivated, since currently you cannot add users manually by now
        $create_user = true;
 
-       logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
-
-       require_once 'include/items.php';
+       Logger::log("statusnet_fetchhometimeline: Fetching for user " . $uid, Logger::DEBUG);
 
        $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
 
        $own_contact = statusnet_fetch_own_contact($a, $uid);
 
+       if (empty($own_contact)) {
+               return;
+       }
+
        $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
                intval($own_contact),
                intval($uid));
 
-       if (DBM::is_result($r)) {
+       if (DBA::isResult($r)) {
                $nick = $r[0]["nick"];
        } else {
-               logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
+               Logger::log("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, Logger::DEBUG);
                return;
        }
 
        $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
                intval($uid));
 
-       if (DBM::is_result($r)) {
+       if (DBA::isResult($r)) {
                $self = $r[0];
        } else {
-               logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
+               Logger::log("statusnet_fetchhometimeline: Own contact not found for user " . $uid, Logger::DEBUG);
                return;
        }
 
        $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
                intval($uid));
-       if (!DBM::is_result($u)) {
-               logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
+       if (!DBA::isResult($u)) {
+               Logger::log("statusnet_fetchhometimeline: Own user not found for user " . $uid, Logger::DEBUG);
                return;
        }
 
@@ -1264,13 +1314,13 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
                                $errormsg = "Unknown error";
                        }
 
-                       logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
+                       Logger::log("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, Logger::DEBUG);
                        return;
                }
 
                $posts = array_reverse($items);
 
-               logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
+               Logger::log("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
 
                if (count($posts)) {
                        foreach ($posts as $post) {
@@ -1298,7 +1348,7 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
                                        $item = Item::insert($postarray);
                                        $postarray["id"] = $item;
 
-                                       logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
+                                       Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
                                }
                        }
                }
@@ -1316,13 +1366,13 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
        $items = $connection->get('statuses/mentions_timeline', $parameters);
 
        if (!is_array($items)) {
-               logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
+               Logger::log("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
                return;
        }
 
        $posts = array_reverse($items);
 
-       logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
+       Logger::log("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
 
        if (count($posts)) {
                foreach ($posts as $post) {
@@ -1348,7 +1398,7 @@ function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
 
                                $item = Item::insert($postarray);
 
-                               logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
+                               Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
                        }
                }
        }
@@ -1376,22 +1426,20 @@ function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nic
                foreach ($posts as $post) {
                        $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
 
-                       if (trim($postarray['body']) == "") {
+                       if (empty($postarray['body'])) {
                                continue;
                        }
 
                        $item = Item::insert($postarray);
                        $postarray["id"] = $item;
 
-                       logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
+                       Logger::log('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
                }
        }
 }
 
 function statusnet_convertmsg(App $a, $body, $no_tags = false)
 {
-       require_once "include/items.php";
-
        $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
 
        $URLSearchString = "^\[\]";
@@ -1406,15 +1454,15 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false)
                foreach ($matches AS $match) {
                        $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
 
-                       logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
+                       Logger::log("statusnet_convertmsg: expanding url " . $match[1], Logger::DEBUG);
 
                        $expanded_url = Network::finalUrl($match[1]);
 
-                       logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
+                       Logger::log("statusnet_convertmsg: fetching data for " . $expanded_url, Logger::DEBUG);
 
                        $oembed_data = OEmbed::fetchURL($expanded_url, true);
 
-                       logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
+                       Logger::log("statusnet_convertmsg: fetching data: done", Logger::DEBUG);
 
                        if ($type == "") {
                                $type = $oembed_data->type;
@@ -1427,7 +1475,7 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false)
                                $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
 
                                $body = str_replace($search, $footerlink, $body);
-                       } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
+                       } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
                                $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
                        } elseif ($oembed_data->type != "link") {
                                $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
@@ -1436,7 +1484,7 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false)
 
                                $tempfile = tempnam(get_temppath(), "cache");
                                file_put_contents($tempfile, $img_str);
-                               $mime = image_type_to_mime_type(exif_imagetype($tempfile));
+                               $mime = mime_content_type($tempfile);
                                unlink($tempfile);
 
                                if (substr($mime, 0, 6) == "image/") {
@@ -1483,7 +1531,7 @@ function statusnet_convertmsg(App $a, $body, $no_tags = false)
                        if ($mtch[1] == "#") {
                                // Replacing the hash tags that are directed to the GNU Social server with internal links
                                $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
-                               $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
+                               $frdchash = '#[url=' . $a->getBaseURL() . '/search?tag=' . $mtch[3] . ']' . $mtch[3] . '[/url]';
                                $body = str_replace($snhash, $frdchash, $body);
 
                                $str_tags .= $frdchash;
@@ -1516,13 +1564,17 @@ function statusnet_fetch_own_contact(App $a, $uid)
                // Fetching user data
                $user = $connection->get('account/verify_credentials');
 
-               PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
+               if (empty($user)) {
+                       return false;
+               }
+
+               PConfig::set($uid, 'statusnet', 'own_url', Strings::normaliseLink($user->statusnet_profile_url));
 
                $contact_id = statusnet_fetch_contact($uid, $user, true);
        } else {
                $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
-                       intval($uid), dbesc($own_url));
-               if (DBM::is_result($r)) {
+                       intval($uid), DBA::escape($own_url));
+               if (DBA::isResult($r)) {
                        $contact_id = $r[0]["id"];
                } else {
                        PConfig::delete($uid, 'statusnet', 'own_url');
@@ -1554,12 +1606,12 @@ function statusnet_is_retweet(App $a, $uid, $body)
 
        $link = "";
        preg_match("/link='(.*?)'/ism", $attributes, $matches);
-       if ($matches[1] != "") {
+       if (!empty($matches[1])) {
                $link = $matches[1];
        }
 
        preg_match('/link="(.*?)"/ism', $attributes, $matches);
-       if ($matches[1] != "") {
+       if (!empty($matches[1])) {
                $link = $matches[1];
        }
 
@@ -1576,13 +1628,13 @@ function statusnet_is_retweet(App $a, $uid, $body)
                return false;
        }
 
-       logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
+       Logger::log('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
 
        $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
 
        $result = $connection->post('statuses/retweet/' . $id);
 
-       logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
+       Logger::log('statusnet_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
 
        return isset($result->id);
 }