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