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
28 protected $notify_email_fave = 1;
35 public function types()
40 public function verbs()
42 return array(ActivityVerb::FAVORITE);
45 public function onCheckSchema()
47 $schema = Schema::get();
48 $schema->ensureTable('fave', Fave::schemaDef());
52 public function onStartUpgrade()
54 // This is a migration feature that will make sure we move
55 // certain User preferences to the Profile_prefs table.
56 // Introduced after commit b5fd2a048fc621ea05d756caba17275ab3dd0af4
57 // on Sun Jul 13 16:30:37 2014 +0200
59 $user->whereAdd('emailnotifyfav IS NOT NULL');
61 printfnq("Detected old User table (emailnotifyfav IS NOT NULL). Moving 'emailnotifyfav' property to Profile_prefs...");
62 // Make sure we have our own tables setup properly
63 while ($user->fetch()) {
64 $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
66 $user->emailnotifyfav = 'null'; // flag this preference as migrated
73 public function onEndUpgrade()
75 printfnq("Ensuring all faves have a URI...");
78 $fave->whereAdd('uri IS NULL');
81 while ($fave->fetch()) {
84 $fave->query(sprintf('UPDATE fave '.
87 'WHERE user_id = %d '.
89 Fave::newUri($fave->user_id, $fave->notice_id, $fave->modified),
90 common_sql_date(strtotime($fave->modified)),
93 } catch (Exception $e) {
94 common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
102 public function onRouterInitialized(URLMapper $m)
105 $m->connect('main/favor', array('action' => 'favor'));
106 $m->connect('main/disfavor', array('action' => 'disfavor'));
108 if (common_config('singleuser', 'enabled')) {
109 $nickname = User::singleUserNickname();
111 $m->connect('favorites',
112 array('action' => 'showfavorites',
113 'nickname' => $nickname));
114 $m->connect('favoritesrss',
115 array('action' => 'favoritesrss',
116 'nickname' => $nickname));
118 $m->connect('favoritedrss', array('action' => 'favoritedrss'));
119 $m->connect('favorited/', array('action' => 'favorited'));
120 $m->connect('favorited', array('action' => 'favorited'));
122 $m->connect(':nickname/favorites',
123 array('action' => 'showfavorites'),
124 array('nickname' => Nickname::DISPLAY_FMT));
125 $m->connect(':nickname/favorites/rss',
126 array('action' => 'favoritesrss'),
127 array('nickname' => Nickname::DISPLAY_FMT));
131 $m->connect('api/favorites/create.:format',
132 array('action' => 'ApiFavoriteCreate',
133 'format' => '(xml|json)'));
134 $m->connect('api/favorites/destroy.:format',
135 array('action' => 'ApiFavoriteDestroy',
136 'format' => '(xml|json)'));
137 $m->connect('api/favorites/list.:format',
138 array('action' => 'ApiTimelineFavorites',
139 'format' => '(xml|json|rss|atom|as)'));
140 $m->connect('api/favorites/:id.:format',
141 array('action' => 'ApiTimelineFavorites',
142 'id' => Nickname::INPUT_FMT,
143 'format' => '(xml|json|rss|atom|as)'));
144 $m->connect('api/favorites.:format',
145 array('action' => 'ApiTimelineFavorites',
146 'format' => '(xml|json|rss|atom|as)'));
147 $m->connect('api/favorites/create/:id.:format',
148 array('action' => 'ApiFavoriteCreate',
150 'format' => '(xml|json)'));
151 $m->connect('api/favorites/destroy/:id.:format',
152 array('action' => 'ApiFavoriteDestroy',
154 'format' => '(xml|json)'));
157 $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
158 array('action' => 'AtomPubShowFavorite'),
159 array('profile' => '[0-9]+',
160 'notice' => '[0-9]+'));
162 $m->connect('api/statusnet/app/favorites/:profile.atom',
163 array('action' => 'AtomPubFavoriteFeed'),
164 array('profile' => '[0-9]+'));
166 // Required for qvitter API
167 $m->connect('api/statuses/favs/:id.:format',
168 array('action' => 'ApiStatusesFavs',
170 'format' => '(xml|json)'));
173 // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
174 protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
176 assert($this->isMyActivity($act));
178 // If empty, we should've created it ourselves on our node.
179 if (!isset($options['created'])) {
180 $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
183 // We must have an objects[0] here because in isMyActivity we require the count to be == 1
184 $actobj = $act->objects[0];
187 $object = Fave::saveActivityObject($actobj, $stored);
188 } catch (ServerException $e) {
189 // Probably that the favored notice doesn't exist in our local database
190 // but may also be some missing profile or so, which we could catch in a
191 // more explicit catch-statement.
198 public function activityObjectFromNotice(Notice $notice)
200 $fave = Fave::fromStored($notice);
201 return $fave->asActivityObject();
204 public function deleteRelated(Notice $notice)
207 $fave = Fave::fromStored($notice);
209 } catch (NoResultException $e) {
210 // Cool, no problem. We wanted to get rid of it anyway.
214 protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
216 require_once INSTALLDIR.'/lib/mail.php';
218 foreach ($mentioned_ids as $id) {
219 $mentioned = User::getKV('id', $id);
220 if ($mentioned instanceof User && $mentioned->id != $stored->profile_id
221 && $mentioned->email && $mentioned->getPref('email', 'notify_fave', $this->notify_email_fave)) { // do we have an email, and does user want it?
222 mail_notify_fave($mentioned, $stored->getProfile(), $stored->getParent());
230 * Typically just used to fill out Twitter-compatible API status data.
232 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
234 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
236 if ($scoped instanceof Profile) {
237 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
239 $status['favorited'] = false;
244 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
246 $userdata['favourites_count'] = Fave::countByProfile($profile);
250 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
252 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
254 if ($scoped instanceof Profile) {
255 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
260 public function onNoticeDeleteRelated(Notice $notice)
262 parent::onNoticeDeleteRelated($notice);
264 // The below algorithm is because we want to delete fave
265 // activities on any notice which _has_ faves, and not as
266 // in the parent function only ones that _are_ faves.
269 $fave->notice_id = $notice->id;
272 while ($fave->fetch()) {
280 public function onUserDeleteRelated(User $user, array &$related)
283 $fave->user_id = $user->id;
284 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
286 Fave::blowCacheForProfileId($user->id);
290 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
292 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
293 Fave::fillFaves($notice_ids);
296 if ($scoped instanceof Profile) {
297 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
302 * show the "favorite" form in the notice options element
303 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
307 public function onStartShowNoticeOptionItems($nli)
309 if (Event::handle('StartShowFaveForm', array($nli))) {
310 $scoped = Profile::current();
311 if ($scoped instanceof Profile) {
312 if (Fave::existsForProfile($nli->notice, $scoped)) {
313 $disfavor = new DisfavorForm($nli->out, $nli->notice);
316 $favor = new FavorForm($nli->out, $nli->notice);
320 Event::handle('EndShowFaveForm', array($nli));
324 public function showNoticeListItem(NoticeListItem $nli)
328 public function openNoticeListItemElement(NoticeListItem $nli)
332 public function closeNoticeListItemElement(NoticeListItem $nli)
337 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
341 $fave->user_id = $uas->user->id;
343 if (!empty($uas->after)) {
344 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
348 while ($fave->fetch()) {
349 $faves[] = clone($fave);
356 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
358 if ($nli instanceof ThreadedNoticeListSubItem) {
359 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
360 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
362 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
364 $threadActive = $item->show() || $threadActive;
369 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
370 * using the class FavCommand.
372 * @param string $cmd Command being run
373 * @param string $arg Rest of the message (including address)
374 * @param User $user User sending the message
375 * @param Command &$result The resulting command object to be run.
377 * @return boolean hook value
379 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
381 if ($result === false && $cmd == 'fav') {
385 list($other, $extra) = $this->split_arg($arg);
386 if (!empty($extra)) {
389 $result = new FavCommand($user, $other);
397 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
399 // TRANS: Help message for IM/SMS command "fav <nickname>".
400 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
401 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
402 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
406 * Are we allowed to perform a certain command over the API?
408 public function onCommandSupportedAPI(Command $cmd, array &$supported)
410 $supported = $supported || $cmd instanceof FavCommand;
413 // Form stuff (settings etc.)
415 public function onEndEmailFormData(Action $action, Profile $scoped)
417 // getConfigData will fall back on systemwide default
418 // and we only wish to save numerical true or false.
419 $emailfave = $scoped->getPref('email', 'notify_fave', $this->notify_email_fave) ? 1 : 0;
421 $action->elementStart('li');
422 $action->checkbox('email-notify_fave',
423 // TRANS: Checkbox label in e-mail preferences form.
424 _('Send me email when someone adds my notice as a favorite.'),
426 $action->elementEnd('li');
431 public function onStartEmailSaveForm(Action $action, Profile $scoped)
433 $emailfave = $action->boolean('email-notify_fave') ? 1 : 0;
435 if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
436 // No need to update setting
439 } catch (NoResultException $e) {
440 // Apparently there's no previously stored setting, then continue to save it as it is now.
443 $scoped->setPref('email', 'notify_fave', $emailfave);
450 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
452 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
453 // TRANS: Menu item in personal group navigation menu.
454 _m('MENU','Favorites'),
455 // @todo i18n FIXME: Need to make this two messages.
456 // TRANS: Menu item title in personal group navigation menu.
457 // TRANS: %s is a username.
458 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
459 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
460 'nav_timeline_favorites');
463 public function onEndPublicGroupNav(Menu $menu)
465 if (!common_config('singleuser', 'enabled')) {
466 // TRANS: Menu item in search group navigation panel.
467 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
468 // TRANS: Menu item title in search group navigation panel.
469 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
473 public function onEndShowSections(Action $action)
475 if (!$action->isAction(array('all', 'public'))) {
479 if (!common_config('performance', 'high')) {
480 $section = new PopularNoticeSection($action, $action->getScoped());
485 public function onPluginVersion(array &$versions)
487 $versions[] = array('name' => 'Favorite',
488 'version' => GNUSOCIAL_VERSION,
489 'author' => 'Mikael Nordfeldth',
490 'homepage' => 'http://gnu.io/',
492 // TRANS: Plugin description.
493 _m('Favorites (likes) using ActivityStreams.'));