3 * GNU Social - a federating social network
4 * Copyright (C) 2014, Free Software Foundation, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('GNUSOCIAL')) { exit(1); }
24 * @maintainer Mikael Nordfeldth <mmn@hethane.se>
26 class FavoritePlugin extends ActivityHandlerPlugin
33 public function types()
38 public function verbs()
40 return array(ActivityVerb::FAVORITE);
43 public function onCheckSchema()
45 $schema = Schema::get();
46 $schema->ensureTable('fave', Fave::schemaDef());
50 public function onEndUpgrade()
52 printfnq("Ensuring all faves have a URI...");
55 $fave->whereAdd('uri IS NULL');
58 while ($fave->fetch()) {
61 $fave->query(sprintf('UPDATE fave '.
64 'WHERE user_id = %d '.
66 Fave::newURI($fave->user_id, $fave->notice_id, $fave->modified),
67 common_sql_date(strtotime($fave->modified)),
70 } catch (Exception $e) {
71 common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
79 public function onRouterInitialized(URLMapper $m)
82 $m->connect('main/favor', array('action' => 'favor'));
83 $m->connect('main/disfavor', array('action' => 'disfavor'));
85 if (common_config('singleuser', 'enabled')) {
86 $nickname = User::singleUserNickname();
88 $m->connect('favorites',
89 array('action' => 'showfavorites',
90 'nickname' => $nickname));
91 $m->connect('favoritesrss',
92 array('action' => 'favoritesrss',
93 'nickname' => $nickname));
95 $m->connect('favoritedrss', array('action' => 'favoritedrss'));
96 $m->connect('favorited/', array('action' => 'favorited'));
97 $m->connect('favorited', array('action' => 'favorited'));
99 $m->connect(':nickname/favorites',
100 array('action' => 'showfavorites'),
101 array('nickname' => Nickname::DISPLAY_FMT));
102 $m->connect(':nickname/favorites/rss',
103 array('action' => 'favoritesrss'),
104 array('nickname' => Nickname::DISPLAY_FMT));
108 $m->connect('api/favorites/create.:format',
109 array('action' => 'ApiFavoriteCreate',
110 'format' => '(xml|json)'));
111 $m->connect('api/favorites/destroy.:format',
112 array('action' => 'ApiFavoriteDestroy',
113 'format' => '(xml|json)'));
114 $m->connect('api/favorites/list.:format',
115 array('action' => 'ApiTimelineFavorites',
116 'format' => '(xml|json|rss|atom|as)'));
117 $m->connect('api/favorites/:id.:format',
118 array('action' => 'ApiTimelineFavorites',
119 'id' => Nickname::INPUT_FMT,
120 'format' => '(xml|json|rss|atom|as)'));
121 $m->connect('api/favorites.:format',
122 array('action' => 'ApiTimelineFavorites',
123 'format' => '(xml|json|rss|atom|as)'));
124 $m->connect('api/favorites/create/:id.:format',
125 array('action' => 'ApiFavoriteCreate',
127 'format' => '(xml|json)'));
128 $m->connect('api/favorites/destroy/:id.:format',
129 array('action' => 'ApiFavoriteDestroy',
131 'format' => '(xml|json)'));
134 $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
135 array('action' => 'AtomPubShowFavorite'),
136 array('profile' => '[0-9]+',
137 'notice' => '[0-9]+'));
139 $m->connect('api/statusnet/app/favorites/:profile.atom',
140 array('action' => 'AtomPubFavoriteFeed'),
141 array('profile' => '[0-9]+'));
143 // Required for qvitter API
144 $m->connect('api/statuses/favs/:id.:format',
145 array('action' => 'ApiStatusesFavs',
147 'format' => '(xml|json)'));
150 public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
154 // FIXME: Set this to abstract public when all plugins have migrated!
155 public function saveObjectFromActivity(Activity $activity, Notice $stored, array $options=array())
157 assert($this->isMyActivity($act));
158 $actor = $stored->getProfile();
160 if (count($act->objects) != 1) {
161 // TRANS: Exception thrown when a favor activity has anything but 1 object
162 throw new ClientException(_('Favoring activites can only be done one at a time'));
165 $obj = $act->objects[0];
166 $type = isset($obj->type) ? ActivityUtils::resolveUri($obj->type, true) : ActivityObject::NOTE;
167 $uris = $obj->getIdentifiers();
169 $local = ActivityUtils::findLocalObject($uris, $type);
170 } catch (Exception $e) {
171 // TODO: if it's not available locally, we should import the favorited object!
172 common_debug('Could not find favored notice locally: '.var_export($uris,true));
176 if (!empty($act->time)) {
177 // This should reasonably mean that it was created on our instance.
178 $options['created'] = common_sql_date($act->time);
181 $options['uri'] = !empty($act->id) ? $act->id : $act->selfLink;
182 $object = Fave::saveNew($actor, $local, $type, $options);
187 public function activityObjectFromNotice(Notice $notice)
189 $fave = Fave::fromStored($notice);
190 return $fave->asActivityObject();
193 public function deleteRelated(Notice $notice)
196 $fave = Fave::fromStored($notice);
198 } catch (NoResultException $e) {
199 // Cool, no problem. We wanted to get rid of it anyway.
206 * Typically just used to fill out Twitter-compatible API status data.
208 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
210 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
212 if ($scoped instanceof Profile) {
213 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
215 $status['favorited'] = false;
220 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
222 $userdata['favourites_count'] = Fave::countByProfile($profile);
226 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
228 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
230 if ($scoped instanceof Profile) {
231 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
236 public function onNoticeDeleteRelated(Notice $notice)
238 parent::onNoticeDeleteRelated($notice);
240 // The below algorithm is because we want to delete fave
241 // activities on any notice which _has_ faves, and not as
242 // in the parent function only ones that _are_ faves.
245 $fave->notice_id = $notice->id;
248 while ($fave->fetch()) {
256 public function onUserDeleteRelated(User $user, array &$related)
259 $fave->user_id = $user->id;
260 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
262 Fave::blowCacheForProfileId($user->id);
266 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
268 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
269 Fave::fillFaves($notice_ids);
272 if ($scoped instanceof Profile) {
273 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
278 * show the "favorite" form in the notice options element
279 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
283 public function onStartShowNoticeOptionItems($nli)
285 if (Event::handle('StartShowFaveForm', array($nli))) {
286 $scoped = Profile::current();
287 if ($scoped instanceof Profile) {
288 if (Fave::existsForProfile($nli->notice, $scoped)) {
289 $disfavor = new DisfavorForm($nli->out, $nli->notice);
292 $favor = new FavorForm($nli->out, $nli->notice);
296 Event::handle('EndShowFaveForm', array($nli));
300 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
304 $fave->user_id = $uas->user->id;
306 if (!empty($uas->after)) {
307 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
311 while ($fave->fetch()) {
312 $faves[] = clone($fave);
319 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
321 if ($nli instanceof ThreadedNoticeListSubItem) {
322 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
323 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
325 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
327 $threadActive = $item->show() || $threadActive;
332 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
333 * using the class FavCommand.
335 * @param string $cmd Command being run
336 * @param string $arg Rest of the message (including address)
337 * @param User $user User sending the message
338 * @param Command &$result The resulting command object to be run.
340 * @return boolean hook value
342 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
344 if ($result === false && $cmd == 'fav') {
348 list($other, $extra) = $this->split_arg($arg);
349 if (!empty($extra)) {
352 $result = new FavCommand($user, $other);
360 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
362 // TRANS: Help message for IM/SMS command "fav <nickname>".
363 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
364 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
365 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
369 * Are we allowed to perform a certain command over the API?
371 public function onCommandSupportedAPI(Command $cmd, array &$supported)
373 $supported = $supported || $cmd instanceof FavCommand;
378 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
380 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
381 // TRANS: Menu item in personal group navigation menu.
382 _m('MENU','Favorites'),
383 // @todo i18n FIXME: Need to make this two messages.
384 // TRANS: Menu item title in personal group navigation menu.
385 // TRANS: %s is a username.
386 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
387 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
388 'nav_timeline_favorites');
391 public function onEndPublicGroupNav(Menu $menu)
393 if (!common_config('singleuser', 'enabled')) {
394 // TRANS: Menu item in search group navigation panel.
395 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
396 // TRANS: Menu item title in search group navigation panel.
397 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
401 public function onEndShowSections(Action $action)
403 if (!$action->isAction(array('all', 'public'))) {
407 if (!common_config('performance', 'high')) {
408 $section = new PopularNoticeSection($action, $action->getScoped());
413 public function onPluginVersion(array &$versions)
415 $versions[] = array('name' => 'Favorite',
416 'version' => GNUSOCIAL_VERSION,
417 'author' => 'Mikael Nordfeldth',
418 'homepage' => 'http://gnu.io/',
420 // TRANS: Plugin description.
421 _m('Favorites (likes) using ActivityStreams.'));