]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - plugins/Bookmark/BookmarkPlugin.php
Properly parse incoming bookmarks
[quix0rs-gnu-social.git] / plugins / Bookmark / BookmarkPlugin.php
index befc4f22910990f5d5583c14470f5111ecf3df21..e6afa0b6daf466e295b786b5aca997a1479aa457 100644 (file)
@@ -28,9 +28,7 @@
  * @link      http://status.net/
  */
 
-if (!defined('STATUSNET')) {
-    exit(1);
-}
+if (!defined('GNUSOCIAL')) { exit(1); }
 
 /**
  * Bookmark plugin main class
@@ -94,7 +92,7 @@ class BookmarkPlugin extends MicroAppPlugin
      */
     function onEndShowStyles($action)
     {
-        $action->cssLink($this->path('bookmark.css'));
+        $action->cssLink($this->path('css/bookmark.css'));
         return true;
     }
 
@@ -107,11 +105,11 @@ class BookmarkPlugin extends MicroAppPlugin
     /**
      * Map URLs to actions
      *
-     * @param Net_URL_Mapper $m path-to-action mapper
+     * @param URLMapper $m path-to-action mapper
      *
      * @return boolean hook value; true means continue processing, false means stop.
      */
-    function onRouterInitialized($m)
+    public function onRouterInitialized(URLMapper $m)
     {
         if (common_config('singleuser', 'enabled')) {
             $nickname = User::singleUserNickname();
@@ -179,15 +177,15 @@ class BookmarkPlugin extends MicroAppPlugin
      *
      * @return value
      */
-    function onPluginVersion(&$versions)
+    function onPluginVersion(array &$versions)
     {
         $versions[] = array('name' => 'Bookmark',
-                            'version' => self::VERSION,
-                            'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
-                            'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
+                            'version' => GNUSOCIAL_VERSION,
+                            'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre, Mikael Nordfeldth',
+                            'homepage' => 'https://gnu.io/social',
                             'description' =>
                             // TRANS: Plugin description.
-                            _m('Simple extension for supporting bookmarks. ') .
+                            _m('Plugin for posting bookmarks. ') .
                             'BookmarkList feature has been developped by Stephane Berube. ' .
                             'Integration has been done by Jean Baptiste Favre.');
         return true;
@@ -237,39 +235,6 @@ class BookmarkPlugin extends MicroAppPlugin
         return true;
     }
 
-    /**
-     * Output our CSS class for bookmark notice list elements
-     *
-     * @param NoticeListItem $nli The item being shown
-     *
-     * @return boolean hook value
-     */
-
-    function onStartOpenNoticeListItemElement($nli)
-    {
-       if (!$this->isMyNotice($nli->notice)) {
-               return true;
-       }
-       
-        $nb = Bookmark::getByNotice($nli->notice);
-        
-        if (empty($nb)) {
-               $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
-               return true;
-        }
-               
-           $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
-           $class = 'hentry notice bookmark';
-           if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
-               $class .= ' limited-scope';
-           }
-           $nli->out->elementStart('li', array('class' => $class,
-                                               'id' => 'notice-' . $id));
-                                               
-           Event::handle('EndOpenNoticeListItemElement', array($nli));
-           return false;
-    }
-
     /**
      * Modify the default menu to link to our custom action
      *
@@ -287,16 +252,9 @@ class BookmarkPlugin extends MicroAppPlugin
      *
      * @see Action
      */
-    function onEndPersonalGroupNav($action)
+    function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
     {
-        $this->user = common_current_user();
-
-        if (!$this->user) {
-            // TRANS: Client error displayed when trying to display bookmarks for a non-existing user.
-            $this->clientError(_('No such user.'));
-        }
-
-        $action->menuItem(common_local_url('bookmarks', array('nickname' => $this->user->nickname)),
+        $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
                           // TRANS: Menu item in sample plugin.
                           _m('Bookmarks'),
                           // TRANS: Menu item title in sample plugin.
@@ -304,40 +262,6 @@ class BookmarkPlugin extends MicroAppPlugin
         return true;
     }
 
-    /**
-     * Save a remote bookmark (from Salmon or PuSH)
-     *
-     * @param Ostatus_profile $author   Author of the bookmark
-     * @param Activity        $activity Activity to save
-     *
-     * @return Notice resulting notice.
-     */
-    static private function _postRemoteBookmark(Ostatus_profile $author,
-                                                Activity $activity)
-    {
-        $bookmark = $activity->objects[0];
-
-        $options = array('uri' => $bookmark->id,
-                         'url' => $bookmark->link,
-                         'is_local' => Notice::REMOTE,
-                         'source' => 'ostatus');
-
-        return self::_postBookmark($author->localProfile(), $activity, $options);
-    }
-
-    /**
-     * Test if an activity represents posting a bookmark
-     *
-     * @param Activity $activity Activity to test
-     *
-     * @return true if it's a Post of a Bookmark, else false
-     */
-    static private function _isPostBookmark($activity)
-    {
-        return ($activity->verb == ActivityVerb::POST &&
-                $activity->objects[0]->type == ActivityObject::BOOKMARK);
-    }
-
     function types()
     {
         return array(ActivityObject::BOOKMARK);
@@ -350,16 +274,14 @@ class BookmarkPlugin extends MicroAppPlugin
      *
      * @return boolean hook value
      */
-    function deleteRelated($notice)
+    function deleteRelated(Notice $notice)
     {
-       if ($this->isMyNotice($notice)) {
-               
-               $nb = Bookmark::getByNotice($notice);
-
-               if (!empty($nb)) {
-               $nb->delete();
-               }
-       }
+        try {
+            $nb = Bookmark::fromStored($notice);
+        } catch (NoResultException $e) {
+            throw new AlreadyFulfilledException('Bookmark already gone when deleting: '.$e->getMessage());
+        }
+        $nb->delete();
        
         return true;
     }
@@ -368,162 +290,43 @@ class BookmarkPlugin extends MicroAppPlugin
      * Save a bookmark from an activity
      *
      * @param Activity $activity Activity to save
-     * @param Profile  $profile  Profile to use as author
+     * @param Profile  $actor    Profile to use as author
      * @param array    $options  Options to pass to bookmark-saving code
      *
      * @return Notice resulting notice
      */
-    function saveNoticeFromActivity($activity, $profile, $options=array())
+    protected function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
     {
-        $bookmark = $activity->objects[0];
-
-        $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
-
-        if (count($relLinkEls) < 1) {
-            // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
-            throw new ClientException(_m('Expected exactly 1 link '.
-                                        'rel=related in a Bookmark.'));
-        }
-
-        if (count($relLinkEls) > 1) {
-            common_log(LOG_WARNING,
-                       "Got too many link rel=related in a Bookmark.");
-        }
-
-        $linkEl = $relLinkEls[0];
-
-        $url = $linkEl->getAttribute('href');
-
-        $tags = array();
-
-        foreach ($activity->categories as $category) {
-            $tags[] = common_canonical_tag($category->term);
-        }
-
-        if (!empty($activity->time)) {
-            $options['created'] = common_sql_date($activity->time);
-        }
-
-        // Fill in location if available
-
-        $location = $activity->context->location;
-
-        if ($location) {
-            $options['lat'] = $location->lat;
-            $options['lon'] = $location->lon;
-            if ($location->location_id) {
-                $options['location_ns'] = $location->location_ns;
-                $options['location_id'] = $location->location_id;
-            }
-        }
-
-        $options['groups']  = array();
-        $options['replies'] = array();  // TODO: context->attention
-
-        foreach ($activity->context->attention as $attnUrl=>$type) {
-            $other = Profile::fromURI($attnUrl);
-            if ($other instanceof Profile) {
-                $options['replies'][] = $attnUrl;
-            } else {
-                // Maybe we can get rid of this since every User_group got a Profile?
-                // TODO: Make sure the above replies get sorted properly for groups (or handled afterwards)
-                $group = User_group::getKV('uri', $attnUrl);
-                if ($group instanceof User_group) {
-                    $options['groups'][] = $attnUrl;
-                }
-            }
-        }
-
-        // Maintain direct reply associations
-        // @fixme what about conversation ID?
-
-        if (!empty($activity->context->replyToID)) {
-            $orig = Notice::getKV('uri',
-                                      $activity->context->replyToID);
-            if (!empty($orig)) {
-                $options['reply_to'] = $orig->id;
-            }
-        }
-
-        return Bookmark::saveNew($profile,
-                                 $bookmark->title,
-                                 $url,
-                                 $tags,
-                                 $bookmark->summary,
-                                 $options);
+        return Bookmark::saveActivityObject($activity->objects[0], $stored);
     }
 
-    function activityObjectFromNotice($notice)
+    public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
     {
-        assert($this->isMyNotice($notice));
-
-        common_log(LOG_INFO,
-                   "Formatting notice {$notice->uri} as a bookmark.");
-
-        $object = new ActivityObject();
-        $nb = Bookmark::getByNotice($notice);
-
-        $object->id      = $notice->uri;
-        $object->type    = ActivityObject::BOOKMARK;
-        $object->title   = $nb->title;
-        $object->summary = $nb->description;
-        $object->link    = $notice->bestUrl();
-
-        // Attributes of the URL
-
-        $attachments = $notice->attachments();
-
-        if (count($attachments) != 1) {
-            // TRANS: Server exception thrown when a bookmark has multiple attachments.
-            throw new ServerException(_m('Bookmark notice with the '.
-                                        'wrong number of attachments.'));
+        if (!$this->isMyNotice($stored)) {
+            return true;
         }
 
-        $target = $attachments[0];
-
-        $attrs = array('rel' => 'related',
-                       'href' => $target->url);
-
-        if (!empty($target->title)) {
-            $attrs['title'] = $target->title;
-        }
-
-        $object->extra[] = array('link', $attrs, null);
-
-        // Attributes of the thumbnail, if any
-
-        try {
-            $thumbnail = $target->getThumbnail();
-            $tattrs = array('rel' => 'preview',
-                            'href' => $thumbnail->url);
-
-            if (!empty($thumbnail->width)) {
-                $tattrs['media:width'] = $thumbnail->width;
-            }
-
-            if (!empty($thumbnail->height)) {
-                $tattrs['media:height'] = $thumbnail->height;
-            }
-
-            $object->extra[] = array('link', $tattrs, null);
-        } catch (UnsupportedMediaException $e) {
-            // No image thumbnail metadata available
-        }
+        $this->extendActivity($stored, $act, $scoped);
+        return false;
+    }
 
-        return $object;
+    public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
+    {
+        /*$hashtags = array();
+        $taglinks = array();
+
+        foreach ($tags as $tag) {
+            $hashtags[] = '#'.$tag;
+            $attrs      = array('href' => Notice_tag::url($tag),
+                                'rel'  => $tag,
+                                'class' => 'tag');
+            $taglinks[] = XMLStringer::estring('a', $attrs, $tag);
+        }*/
     }
 
-    /**
-     * Given a notice list item, returns an adapter specific
-     * to this plugin.
-     *
-     * @param NoticeListItem $nli item to adapt
-     *
-     * @return NoticeListItemAdapter adapter or null
-     */
-    function adaptNoticeListItem($nli)
+    function activityObjectFromNotice(Notice $notice)
     {
-        return new BookmarkListItem($nli);
+        return Bookmark::fromStored($notice)->asActivityObject();
     }
 
     function entryForm($out)
@@ -544,14 +347,16 @@ class BookmarkPlugin extends MicroAppPlugin
 
     function onEndUpgrade()
     {
+        printfnq('Making sure Bookmark notices have correct verb and object_type...');
+
         // Version 0.9.x of the plugin didn't stamp notices
         // with verb and object-type (for obvious reasons). Update
         // those notices here.
 
         $notice = new Notice();
         
-        $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
-        $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
+        $notice->joinAdd(array('uri', 'bookmark:uri'));
+        $notice->whereAdd('object_type IS NULL OR object_type = '.$notice->_quote(ActivityObject::NOTE));
 
         $notice->find();
 
@@ -561,21 +366,81 @@ class BookmarkPlugin extends MicroAppPlugin
             $notice->object_type = ActivityObject::BOOKMARK;
             $notice->update($original);
         }
+
+        printfnq("DONE.\n");
     }
 
     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
     {
         assert($obj->type == ActivityObject::BOOKMARK);
 
-        $bm = Bookmark::getKV('uri', $obj->id);
+        $bm = Bookmark::getByPK(array('uri' => $obj->id));
+
+        $out['displayName'] = $bm->getTitle();
+        $out['targetUrl']   = $bm->getUrl();
+
+        return true;
+    }
+
+    protected function showNoticeContent(Notice $stored, HTMLOutputter $out, Profile $scoped=null)
+    {
+        $nb = Bookmark::fromStored($stored);
 
-        if (empty($bm)) {
-            throw new ServerException("Unknown bookmark: " . $obj->id);
+        // Whether to nofollow
+        $attrs = array('href' => $nb->getUrl(), 'class' => 'bookmark-title');
+
+        $nf = common_config('nofollow', 'external');
+
+        if ($nf == 'never' || ($nf == 'sometimes' and $out instanceof ShowstreamAction)) {
+            $attrs['rel'] = 'external';
+        } else {
+            $attrs['rel'] = 'nofollow external';
         }
 
-        $out['displayName'] = $bm->title;
-        $out['targetUrl']   = $bm->url;
+        $out->elementStart('h3');
+        $out->element('a', $attrs, $nb->getTitle());
+        $out->elementEnd('h3');
+
+        // Replies look like "for:" tags
+        $replies = $stored->getReplies();
+        $tags = $stored->getTags();
+
+        if (!empty($nb->description)) {
+            $out->element('p',
+                          array('class' => 'bookmark-description'),
+                          $nb->description);
+        }
+
+        if (!empty($replies) || !empty($tags)) {
+
+            $out->elementStart('ul', array('class' => 'bookmark-tags'));
+
+            foreach ($replies as $reply) {
+                $other = Profile::getByPK($reply);
+                $out->elementStart('li');
+                $out->element('a', array('rel' => 'tag',
+                                         'href' => $other->getUrl(),
+                                         'title' => $other->getBestName()),
+                              sprintf('for:%s', $other->getNickname()));
+                $out->elementEnd('li');
+                $out->text(' ');
+            }
+
+            foreach ($tags as $tag) {
+                $tag = trim($tag);
+                if (!empty($tag)) {
+                    $out->elementStart('li');
+                    $out->element('a',
+                                  array('rel' => 'tag',
+                                        'href' => Notice_tag::url($tag)),
+                                  $tag);
+                    $out->elementEnd('li');
+                    $out->text(' ');
+                }
+            }
+
+            $out->elementEnd('ul');
+        }
 
-        return true;
     }
 }