]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/OStatus.php
Merge pull request #4194 from MrPetovan/task/fix-scrutinizer-issues
[friendica.git] / src / Protocol / OStatus.php
index ed762084c2668d83d55cd4e113006d9b16bf4213..242af46045ec983525035e32f50727f41c2897fe 100644 (file)
@@ -9,23 +9,23 @@ use Friendica\Core\Cache;
 use Friendica\Core\Config;
 use Friendica\Core\System;
 use Friendica\Database\DBM;
-use Friendica\Model\GlobalContact;
+use Friendica\Model\Contact;
+use Friendica\Model\GContact;
 use Friendica\Network\Probe;
-use Friendica\Object\Contact;
+use Friendica\Object\Image;
 use Friendica\Util\Lock;
 use Friendica\Util\XML;
 use dba;
 use DOMDocument;
-use DomXPath;
+use DOMXPath;
 
+require_once 'include/dba.php';
 require_once 'include/threads.php';
 require_once 'include/html2bbcode.php';
 require_once 'include/bbcode.php';
 require_once 'include/items.php';
 require_once 'mod/share.php';
 require_once 'include/enotify.php';
-require_once 'include/Photo.php';
-require_once 'include/follow.php';
 require_once 'include/api.php';
 require_once 'mod/proxy.php';
 
@@ -70,9 +70,9 @@ class OStatus
                $found = false;
 
                if ($aliaslink != '') {
-                       $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?",
-                                       $importer["uid"], $aliaslink, NETWORK_STATUSNET);
-                       $r = dba::select('contact', array(), $condition, array('limit' => 1));
+                       $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?",
+                                       $importer["uid"], $aliaslink, NETWORK_STATUSNET];
+                       $r = dba::selectFirst('contact', [], $condition);
 
                        if (DBM::is_result($r)) {
                                $found = true;
@@ -89,9 +89,9 @@ class OStatus
                                $aliaslink = $author["author-link"];
                        }
 
-                       $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
-                                       normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET);
-                       $r = dba::select('contact', array(), $condition, array('limit' => 1));
+                       $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"],
+                                       normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET];
+                       $r = dba::selectFirst('contact', [], $condition);
 
                        if (DBM::is_result($r)) {
                                $found = true;
@@ -104,9 +104,9 @@ class OStatus
                }
 
                if (!$found && ($addr != "")) {
-                       $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?",
-                                       $importer["uid"], $addr, NETWORK_STATUSNET);
-                       $r = dba::select('contact', array(), $condition, array('limit' => 1));
+                       $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?",
+                                       $importer["uid"], $addr, NETWORK_STATUSNET];
+                       $r = dba::selectFirst('contact', [], $condition);
 
                        if (DBM::is_result($r)) {
                                $found = true;
@@ -151,11 +151,8 @@ class OStatus
 
                // Only update the contacts if it is an OStatus contact
                if ($r && ($r['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
-                       // This contact is vital, so we awake it from the dead
-                       Contact::unmarkForArchival($contact);
 
                        // Update contact data
-
                        $current = $contact;
                        unset($current['name-date']);
 
@@ -203,15 +200,15 @@ class OStatus
 
                        if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
                                logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
-                               update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
+                               Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
                        }
 
                        // Ensure that we are having this contact (with uid=0)
                        $cid = Contact::getIdForURL($aliaslink, 0);
 
                        if ($cid) {
-                               $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location');
-                               $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1));
+                               $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
+                               $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
 
                                // Update it with the current values
                                $fields = array('url' => $author["author-link"], 'name' => $contact["name"],
@@ -223,15 +220,15 @@ class OStatus
                                dba::update('contact', $fields, array('id' => $cid), $old_contact);
 
                                // Update the avatar
-                               update_contact_avatar($author["author-avatar"], 0, $cid);
+                               Contact::updateAvatar($author["author-avatar"], 0, $cid);
                        }
 
                        $contact["generation"] = 2;
                        $contact["hide"] = false; // OStatus contacts are never hidden
                        $contact["photo"] = $author["author-avatar"];
-                       $gcid = GlobalContact::update($contact);
+                       $gcid = GContact::update($contact);
 
-                       GlobalContact::link($gcid, $contact["uid"], $contact["id"]);
+                       GContact::link($gcid, $contact["uid"], $contact["id"]);
                }
 
                return $author;
@@ -254,7 +251,7 @@ class OStatus
                $doc = new DOMDocument();
                @$doc->loadXML($xml);
 
-               $xpath = new DomXPath($doc);
+               $xpath = new DOMXPath($doc);
                $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
                $xpath->registerNamespace('thr', NAMESPACE_THREAD);
                $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
@@ -332,7 +329,7 @@ class OStatus
                $doc = new DOMDocument();
                @$doc->loadXML($xml);
 
-               $xpath = new DomXPath($doc);
+               $xpath = new DOMXPath($doc);
                $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
                $xpath->registerNamespace('thr', NAMESPACE_THREAD);
                $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
@@ -544,8 +541,8 @@ class OStatus
         */
        private static function deleteNotice($item)
        {
-               $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']);
-               $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1));
+               $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
+               $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition);
                if (!DBM::is_result($deleted)) {
                        logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. ");
                        return;
@@ -742,7 +739,7 @@ class OStatus
                        if (!@$doc->loadHTML($conversation_data['body'])) {
                                return;
                        }
-                       $xpath = new DomXPath($doc);
+                       $xpath = new DOMXPath($doc);
 
                        $links = $xpath->query('//link');
                        if ($links) {
@@ -782,7 +779,7 @@ class OStatus
                $doc = new DOMDocument();
                @$doc->loadXML($xml);
 
-               $xpath = new DomXPath($doc);
+               $xpath = new DOMXPath($doc);
                $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
                $xpath->registerNamespace('thr', NAMESPACE_THREAD);
                $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
@@ -898,8 +895,8 @@ class OStatus
         */
        private static function fetchRelated($related, $related_uri, $importer)
        {
-               $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON);
-               $conversation = dba::select('conversation', array('source', 'protocol'), $condition,  array('limit' => 1));
+               $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
+               $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
                if (DBM::is_result($conversation)) {
                        $stored = true;
                        $xml = $conversation['source'];
@@ -932,7 +929,7 @@ class OStatus
                        if (!@$doc->loadHTML($related_data['body'])) {
                                return;
                        }
-                       $xpath = new DomXPath($doc);
+                       $xpath = new DOMXPath($doc);
 
                        $atom_file = '';
 
@@ -978,8 +975,8 @@ class OStatus
 
                // Finally we take the data that we fetched from "ostatus:conversation"
                if ($xml == '') {
-                       $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV);
-                       $conversation = dba::select('conversation', array('source'), $condition,  array('limit' => 1));
+                       $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
+                       $conversation = dba::selectFirst('conversation', ['source'], $condition);
                        if (DBM::is_result($conversation)) {
                                $stored = true;
                                logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
@@ -1026,8 +1023,7 @@ class OStatus
                $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
                $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
 
-               $orig_contact = $contact;
-               $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $orig_contact, false);
+               $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
 
                $item["author-name"] = $orig_author["author-name"];
                $item["author-link"] = $orig_author["author-link"];
@@ -1238,12 +1234,13 @@ class OStatus
        /**
         * @brief Adds the header elements to the XML document
         *
-        * @param object $doc   XML document
-        * @param array  $owner Contact data of the poster
+        * @param object $doc    XML document
+        * @param array  $owner  Contact data of the poster
+        * @param string $filter The related feed filter (activity, posts or comments)
         *
         * @return object header root element
         */
-       private static function addHeader($doc, $owner)
+       private static function addHeader($doc, $owner, $filter)
        {
                $a = get_app();
 
@@ -1259,10 +1256,16 @@ class OStatus
                $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
                $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
 
-               $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
+               switch ($filter) {
+                       case 'activity': $title = t('%s\'s timeline', $owner['name']); break;
+                       case 'posts'   : $title = t('%s\'s posts'   , $owner['name']); break;
+                       case 'comments': $title = t('%s\'s comments', $owner['name']); break;
+               }
+
+               $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION);
                XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
-               XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
-               XML::addElement($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
+               XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
+               XML::addElement($doc, $root, "title", $title);
                XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
                XML::addElement($doc, $root, "logo", $owner["photo"]);
                XML::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
@@ -1281,17 +1284,17 @@ class OStatus
 
                self::hublinks($doc, $root, $owner["nick"]);
 
-               $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "salmon");
+               $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon");
                XML::addElement($doc, $root, "link", "", $attributes);
 
-               $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
+               $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
                XML::addElement($doc, $root, "link", "", $attributes);
 
-               $attributes = array("href" => System::baseUrl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
+               $attributes = array("href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
                XML::addElement($doc, $root, "link", "", $attributes);
 
-               $attributes = array("href" => System::baseUrl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
-                               "rel" => "self", "type" => "application/atom+xml");
+               $attributes = array("href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
+                       "rel" => "self", "type" => "application/atom+xml");
                XML::addElement($doc, $root, "link", "", $attributes);
 
                return $root;
@@ -1326,7 +1329,7 @@ class OStatus
 
                switch ($siteinfo["type"]) {
                        case 'photo':
-                               $imgdata = get_photo_info($siteinfo["image"]);
+                               $imgdata = Image::getInfoFromURL($siteinfo["image"]);
                                $attributes = array("rel" => "enclosure",
                                                "href" => $siteinfo["image"],
                                                "type" => $imgdata["mime"],
@@ -1346,7 +1349,7 @@ class OStatus
                }
 
                if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
-                       $imgdata = get_photo_info($siteinfo["image"]);
+                       $imgdata = Image::getInfoFromURL($siteinfo["image"]);
                        $attributes = array("rel" => "enclosure",
                                        "href" => $siteinfo["image"],
                                        "type" => $imgdata["mime"],
@@ -2070,42 +2073,51 @@ class OStatus
        }
 
        /**
+        * Creates the XML feed for a given nickname
+        *
+        * Supported filters:
+        * - activity (default): all the public posts
+        * - posts: all the public top-level posts
+        * - comments: all the public replies
+        *
+        * Updates the provided last_update parameter if the result comes from the
+        * cache or it is empty
+        *
         * @brief Creates the XML feed for a given nickname
         *
-        * @param object  $a           The application class
         * @param string  $owner_nick  Nickname of the feed owner
         * @param string  $last_update Date of the last update
         * @param integer $max_items   Number of maximum items to fetch
+        * @param string  $filter      Feed items filter (activity, posts or comments)
+        * @param boolean $nocache     Wether to bypass caching
         *
         * @return string XML feed
         */
-       public static function feed(App $a, $owner_nick, &$last_update, $max_items = 300)
+       public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
        {
                $stamp = microtime(true);
 
-               $cachekey = "ostatus:feed:".$owner_nick.":".$last_update;
+               $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
 
                $previous_created = $last_update;
 
                $result = Cache::get($cachekey);
-               if (!is_null($result)) {
-                       logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created.' (cached)', LOGGER_DEBUG);
+               if (!$nocache && !is_null($result)) {
+                       logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
                        $last_update = $result['last_update'];
                        return $result['feed'];
                }
 
-               $r = q(
+               $owner = dba::fetch_first(
                        "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
                                FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
-                               WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
-                       dbesc($owner_nick)
+                               WHERE `contact`.`self` AND `user`.`nickname` = ? LIMIT 1",
+                       $owner_nick
                );
-               if (!DBM::is_result($r)) {
+               if (!DBM::is_result($owner)) {
                        return;
                }
 
-               $owner = $r[0];
-
                if (!strlen($last_update)) {
                        $last_update = 'now -30 days';
                }
@@ -2113,23 +2125,40 @@ class OStatus
                $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
                $authorid = Contact::getIdForURL($owner["url"], 0);
 
+               $sql_extra = '';
+               if ($filter === 'posts') {
+                       $sql_extra .= ' AND `item`.`id` = `item`.`parent` ';
+               }
+
+               if ($filter === 'comments') {
+                       $sql_extra .= sprintf(" AND `item`.`object-type` = '%s' ", dbesc(ACTIVITY_OBJ_COMMENT));
+               }
+
                $items = q(
                        "SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
                                STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
-                               WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
-                                       `item`.`author-id` = %d AND `item`.`created` > '%s' AND
-                                       NOT `item`.`deleted` AND NOT `item`.`private` AND
-                                       `thread`.`network` IN ('%s', '%s')
+                               WHERE `item`.`uid` = %d
+                               AND `item`.`contact-id` = %d
+                               AND `item`.`author-id` = %d
+                               AND `item`.`created` > '%s'
+                               AND NOT `item`.`deleted`
+                               AND NOT `item`.`private`
+                               AND `thread`.`network` IN ('%s', '%s')
+                               $sql_extra
                                ORDER BY `item`.`created` DESC LIMIT %d",
-                       intval($owner["uid"]), intval($owner["id"]),
-                       intval($authorid), dbesc($check_date),
-                       dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN), intval($max_items)
+                       intval($owner["uid"]),
+                       intval($owner["id"]),
+                       intval($authorid),
+                       dbesc($check_date),
+                       dbesc(NETWORK_OSTATUS),
+                       dbesc(NETWORK_DFRN),
+                       intval($max_items)
                );
 
                $doc = new DOMDocument('1.0', 'utf-8');
                $doc->formatOutput = true;
 
-               $root = self::addHeader($doc, $owner);
+               $root = self::addHeader($doc, $owner, $filter);
 
                foreach ($items as $item) {
                        if (Config::get('system', 'ostatus_debug')) {
@@ -2148,7 +2177,7 @@ class OStatus
                $msg = array('feed' => $feeddata, 'last_update' => $last_update);
                Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
 
-               logger('Feed duration: '.number_format(microtime(true) - $stamp, 3).' - '.$owner_nick.' - '.$previous_created, LOGGER_DEBUG);
+               logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
 
                return $feeddata;
        }