]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/BookmarkPlugin.php
checkAuthorship events, Ostatus_profile rewrite to handle it
[quix0rs-gnu-social.git] / plugins / Bookmark / BookmarkPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * A plugin to enable social-bookmarking functionality
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  SocialBookmark
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Bookmark plugin main class
37  *
38  * @category  Bookmark
39  * @package   StatusNet
40  * @author    Brion Vibber <brionv@status.net>
41  * @author    Evan Prodromou <evan@status.net>
42  * @copyright 2010 StatusNet, Inc.
43  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
44  * @link      http://status.net/
45  */
46 class BookmarkPlugin extends MicroAppPlugin
47 {
48     const VERSION         = '0.1';
49     const IMPORTDELICIOUS = 'BookmarkPlugin:IMPORTDELICIOUS';
50
51     var $oldSaveNew = true;
52
53     /**
54      * Authorization for importing delicious bookmarks
55      *
56      * By default, everyone can import bookmarks except silenced people.
57      *
58      * @param Profile $profile Person whose rights to check
59      * @param string  $right   Right to check; const value
60      * @param boolean &$result Result of the check, writeable
61      *
62      * @return boolean hook value
63      */
64     function onUserRightsCheck($profile, $right, &$result)
65     {
66         if ($right == self::IMPORTDELICIOUS) {
67             $result = !$profile->isSilenced();
68             return false;
69         }
70         return true;
71     }
72
73     /**
74      * Database schema setup
75      *
76      * @see Schema
77      * @see ColumnDef
78      *
79      * @return boolean hook value; true means continue processing, false means stop.
80      */
81     function onCheckSchema()
82     {
83         $schema = Schema::get();
84
85         $schema->ensureTable('bookmark', Bookmark::schemaDef());
86
87         return true;
88     }
89
90     /**
91      * Show the CSS necessary for this plugin
92      *
93      * @param Action $action the action being run
94      *
95      * @return boolean hook value
96      */
97     function onEndShowStyles($action)
98     {
99         $action->cssLink($this->path('css/bookmark.css'));
100         return true;
101     }
102
103     function onEndShowScripts($action)
104     {
105         $action->script($this->path('js/bookmark.js'));
106         return true;
107     }
108
109     /**
110      * Map URLs to actions
111      *
112      * @param Net_URL_Mapper $m path-to-action mapper
113      *
114      * @return boolean hook value; true means continue processing, false means stop.
115      */
116     function onRouterInitialized($m)
117     {
118         if (common_config('singleuser', 'enabled')) {
119             $nickname = User::singleUserNickname();
120             $m->connect('bookmarks',
121                         array('action' => 'bookmarks', 'nickname' => $nickname));
122             $m->connect('bookmarks/rss',
123                         array('action' => 'bookmarksrss', 'nickname' => $nickname));
124         } else {
125             $m->connect(':nickname/bookmarks',
126                         array('action' => 'bookmarks'),
127                         array('nickname' => Nickname::DISPLAY_FMT));
128             $m->connect(':nickname/bookmarks/rss',
129                         array('action' => 'bookmarksrss'),
130                         array('nickname' => Nickname::DISPLAY_FMT));
131         }
132
133         $m->connect('api/bookmarks/:id.:format',
134                     array('action' => 'ApiTimelineBookmarks',
135                           'id' => Nickname::INPUT_FMT,
136                           'format' => '(xml|json|rss|atom|as)'));
137
138         $m->connect('main/bookmark/new',
139                     array('action' => 'newbookmark'),
140                     array('id' => '[0-9]+'));
141
142         $m->connect('main/bookmark/popup',
143                     array('action' => 'bookmarkpopup'));
144
145         $m->connect('main/bookmark/import',
146                     array('action' => 'importdelicious'));
147
148         $m->connect('main/bookmark/forurl',
149                     array('action' => 'bookmarkforurl'));
150
151         $m->connect('bookmark/:id',
152                     array('action' => 'showbookmark'),
153                     array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
154
155         $m->connect('notice/by-url/:id',
156                     array('action' => 'noticebyurl'),
157                     array('id' => '[0-9]+'));
158
159         return true;
160     }
161
162
163     /**
164      * Add our two queue handlers to the queue manager
165      *
166      * @param QueueManager $qm current queue manager
167      *
168      * @return boolean hook value
169      */
170     function onEndInitializeQueueManager($qm)
171     {
172         $qm->connect('dlcsback', 'DeliciousBackupImporter');
173         $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
174         return true;
175     }
176
177     /**
178      * Plugin version data
179      *
180      * @param array &$versions array of version data
181      *
182      * @return value
183      */
184     function onPluginVersion(&$versions)
185     {
186         $versions[] = array('name' => 'Bookmark',
187                             'version' => self::VERSION,
188                             'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
189                             'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
190                             'description' =>
191                             // TRANS: Plugin description.
192                             _m('Simple extension for supporting bookmarks. ') .
193                             'BookmarkList feature has been developped by Stephane Berube. ' .
194                             'Integration has been done by Jean Baptiste Favre.');
195         return true;
196     }
197
198     /**
199      * Load our document if requested
200      *
201      * @param string &$title  Title to fetch
202      * @param string &$output HTML to output
203      *
204      * @return boolean hook value
205      */
206     function onStartLoadDoc(&$title, &$output)
207     {
208         if ($title == 'bookmarklet') {
209             $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
210
211             $c      = file_get_contents($filename);
212             $output = common_markup_to_html($c);
213             return false; // success!
214         }
215
216         return true;
217     }
218
219     /**
220      * Show a link to our delicious import page on profile settings form
221      *
222      * @param Action $action Profile settings action being shown
223      *
224      * @return boolean hook value
225      */
226     function onEndProfileSettingsActions($action)
227     {
228         $user = common_current_user();
229
230         if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
231             $action->elementStart('li');
232             $action->element('a',
233                              array('href' => common_local_url('importdelicious')),
234                              // TRANS: Link text in proile leading to import form.
235                              _m('Import del.icio.us bookmarks'));
236             $action->elementEnd('li');
237         }
238
239         return true;
240     }
241
242     /**
243      * Output our CSS class for bookmark notice list elements
244      *
245      * @param NoticeListItem $nli The item being shown
246      *
247      * @return boolean hook value
248      */
249
250     function onStartOpenNoticeListItemElement($nli)
251     {
252         if (!$this->isMyNotice($nli->notice)) {
253                 return true;
254         }
255         
256         $nb = Bookmark::getByNotice($nli->notice);
257         
258         if (empty($nb)) {
259                 $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
260                 return true;
261         }
262                 
263             $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
264             $class = 'h-entry notice bookmark';
265             if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
266                 $class .= ' limited-scope';
267             }
268             $nli->out->elementStart('li', array('class' => $class,
269                                                 'id' => 'notice-' . $id));
270                                                 
271             Event::handle('EndOpenNoticeListItemElement', array($nli));
272             return false;
273     }
274
275     /**
276      * Modify the default menu to link to our custom action
277      *
278      * Using event handlers, it's possible to modify the default UI for pages
279      * almost without limit. In this method, we add a menu item to the default
280      * primary menu for the interface to link to our action.
281      *
282      * The Action class provides a rich set of events to hook, as well as output
283      * methods.
284      *
285      * @param Action $action The current action handler. Use this to
286      * do any output.
287      *
288      * @return boolean hook value; true means continue processing, false means stop.
289      *
290      * @see Action
291      */
292     function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
293     {
294         $menu->menuItem(common_local_url('bookmarks', array('nickname' => $target->getNickname())),
295                           // TRANS: Menu item in sample plugin.
296                           _m('Bookmarks'),
297                           // TRANS: Menu item title in sample plugin.
298                           _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
299         return true;
300     }
301
302     function types()
303     {
304         return array(ActivityObject::BOOKMARK);
305     }
306
307     /**
308      * When a notice is deleted, delete the related Bookmark
309      *
310      * @param Notice $notice Notice being deleted
311      *
312      * @return boolean hook value
313      */
314     function deleteRelated(Notice $notice)
315     {
316         if ($this->isMyNotice($notice)) {
317                 
318                 $nb = Bookmark::getByNotice($notice);
319
320                 if (!empty($nb)) {
321                 $nb->delete();
322                 }
323         }
324         
325         return true;
326     }
327
328     /**
329      * Save a bookmark from an activity
330      *
331      * @param Activity $activity Activity to save
332      * @param Profile  $actor    Profile to use as author
333      * @param array    $options  Options to pass to bookmark-saving code
334      *
335      * @return Notice resulting notice
336      */
337     function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
338     {
339         $bookmark = $activity->objects[0];
340
341         $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
342
343         if (count($relLinkEls) < 1) {
344             // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
345             throw new ClientException(_m('Expected exactly 1 link '.
346                                         'rel=related in a Bookmark.'));
347         }
348
349         if (count($relLinkEls) > 1) {
350             common_log(LOG_WARNING,
351                        "Got too many link rel=related in a Bookmark.");
352         }
353
354         $linkEl = $relLinkEls[0];
355
356         $url = $linkEl->getAttribute('href');
357
358         $tags = array();
359
360         foreach ($activity->categories as $category) {
361             $tags[] = common_canonical_tag($category->term);
362         }
363
364         if (!empty($activity->time)) {
365             $options['created'] = common_sql_date($activity->time);
366         }
367
368         // Fill in location if available
369
370         $location = $activity->context->location;
371
372         if ($location) {
373             $options['lat'] = $location->lat;
374             $options['lon'] = $location->lon;
375             if ($location->location_id) {
376                 $options['location_ns'] = $location->location_ns;
377                 $options['location_id'] = $location->location_id;
378             }
379         }
380
381         $options['groups']  = array();
382         $options['replies'] = array();  // TODO: context->attention
383
384         foreach ($activity->context->attention as $attnUrl=>$type) {
385             try {
386                 $other = Profile::fromUri($attnUrl);
387                 if ($other->isGroup()) {
388                     $options['groups'][] = $other->id;
389                 } else {
390                     $options['replies'][] = $attnUrl;
391                 }
392             } catch (UnknownUriException $e) {
393                 // We simply don't know this URI, despite lookup attempts.
394             }
395         }
396
397         // Maintain direct reply associations
398         // @fixme what about conversation ID?
399
400         if (!empty($activity->context->replyToID)) {
401             $orig = Notice::getKV('uri',
402                                       $activity->context->replyToID);
403             if (!empty($orig)) {
404                 $options['reply_to'] = $orig->id;
405             }
406         }
407
408         return Bookmark::saveNew($actor,
409                                  $bookmark->title,
410                                  $url,
411                                  $tags,
412                                  $bookmark->summary,
413                                  $options);
414     }
415
416     function activityObjectFromNotice(Notice $notice)
417     {
418         assert($this->isMyNotice($notice));
419
420         common_log(LOG_INFO,
421                    "Formatting notice {$notice->uri} as a bookmark.");
422
423         $object = new ActivityObject();
424         $nb = Bookmark::getByNotice($notice);
425
426         $object->id      = $notice->uri;
427         $object->type    = ActivityObject::BOOKMARK;
428         $object->title   = $nb->title;
429         $object->summary = $nb->description;
430         $object->link    = $notice->getUrl();
431
432         // Attributes of the URL
433
434         $attachments = $notice->attachments();
435
436         if (count($attachments) != 1) {
437             // TRANS: Server exception thrown when a bookmark has multiple attachments.
438             throw new ServerException(_m('Bookmark notice with the '.
439                                         'wrong number of attachments.'));
440         }
441
442         $target = $attachments[0];
443
444         $attrs = array('rel' => 'related',
445                        'href' => $target->url);
446
447         if (!empty($target->title)) {
448             $attrs['title'] = $target->title;
449         }
450
451         $object->extra[] = array('link', $attrs, null);
452
453         // Attributes of the thumbnail, if any
454
455         try {
456             $thumbnail = $target->getThumbnail();
457             $tattrs = array('rel' => 'preview',
458                             'href' => $thumbnail->url);
459
460             if (!empty($thumbnail->width)) {
461                 $tattrs['media:width'] = $thumbnail->width;
462             }
463
464             if (!empty($thumbnail->height)) {
465                 $tattrs['media:height'] = $thumbnail->height;
466             }
467
468             $object->extra[] = array('link', $tattrs, null);
469         } catch (UnsupportedMediaException $e) {
470             // No image thumbnail metadata available
471         }
472
473         return $object;
474     }
475
476     /**
477      * Given a notice list item, returns an adapter specific
478      * to this plugin.
479      *
480      * @param NoticeListItem $nli item to adapt
481      *
482      * @return NoticeListItemAdapter adapter or null
483      */
484     function adaptNoticeListItem($nli)
485     {
486         return new BookmarkListItem($nli);
487     }
488
489     function entryForm($out)
490     {
491         return new InitialBookmarkForm($out);
492     }
493
494     function tag()
495     {
496         return 'bookmark';
497     }
498
499     function appTitle()
500     {
501         // TRANS: Application title.
502         return _m('TITLE','Bookmark');
503     }
504
505     function onEndUpgrade()
506     {
507         // Version 0.9.x of the plugin didn't stamp notices
508         // with verb and object-type (for obvious reasons). Update
509         // those notices here.
510
511         $notice = new Notice();
512         
513         $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
514         $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
515
516         $notice->find();
517
518         while ($notice->fetch()) {
519             $original = clone($notice);
520             $notice->verb        = ActivityVerb::POST;
521             $notice->object_type = ActivityObject::BOOKMARK;
522             $notice->update($original);
523         }
524     }
525
526     public function activityObjectOutputJson(ActivityObject $obj, array &$out)
527     {
528         assert($obj->type == ActivityObject::BOOKMARK);
529
530         $bm = Bookmark::getKV('uri', $obj->id);
531
532         if (empty($bm)) {
533             throw new ServerException("Unknown bookmark: " . $obj->id);
534         }
535
536         $out['displayName'] = $bm->title;
537         $out['targetUrl']   = $bm->url;
538
539         return true;
540     }
541 }