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 $email_notify_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 // First we'll make sure Profile_prefs exists
63 $schema = Schema::get();
64 $schema->ensureTable('profile_prefs', Profile_prefs::schemaDef());
66 // Make sure we have our own tables setup properly
67 while ($user->fetch()) {
68 $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
70 $user->emailnotifyfav = 'null'; // flag this preference as migrated
77 public function onEndUpgrade()
79 printfnq("Ensuring all faves have a URI...");
82 $fave->whereAdd('uri IS NULL');
85 while ($fave->fetch()) {
88 $fave->query(sprintf('UPDATE fave '.
91 'WHERE user_id = %d '.
93 Fave::newUri($fave->user_id, $fave->notice_id, $fave->modified),
94 common_sql_date(strtotime($fave->modified)),
97 } catch (Exception $e) {
98 common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
106 public function onRouterInitialized(URLMapper $m)
109 $m->connect('main/favor', array('action' => 'favor'));
110 $m->connect('main/disfavor', array('action' => 'disfavor'));
112 if (common_config('singleuser', 'enabled')) {
113 $nickname = User::singleUserNickname();
115 $m->connect('favorites',
116 array('action' => 'showfavorites',
117 'nickname' => $nickname));
118 $m->connect('favoritesrss',
119 array('action' => 'favoritesrss',
120 'nickname' => $nickname));
122 $m->connect('favoritedrss', array('action' => 'favoritedrss'));
123 $m->connect('favorited/', array('action' => 'favorited'));
124 $m->connect('favorited', array('action' => 'favorited'));
126 $m->connect(':nickname/favorites',
127 array('action' => 'showfavorites'),
128 array('nickname' => Nickname::DISPLAY_FMT));
129 $m->connect(':nickname/favorites/rss',
130 array('action' => 'favoritesrss'),
131 array('nickname' => Nickname::DISPLAY_FMT));
135 $m->connect('api/favorites/create.:format',
136 array('action' => 'ApiFavoriteCreate',
137 'format' => '(xml|json)'));
138 $m->connect('api/favorites/destroy.:format',
139 array('action' => 'ApiFavoriteDestroy',
140 'format' => '(xml|json)'));
141 $m->connect('api/favorites/list.:format',
142 array('action' => 'ApiTimelineFavorites',
143 'format' => '(xml|json|rss|atom|as)'));
144 $m->connect('api/favorites/:id.:format',
145 array('action' => 'ApiTimelineFavorites',
146 'id' => Nickname::INPUT_FMT,
147 'format' => '(xml|json|rss|atom|as)'));
148 $m->connect('api/favorites.:format',
149 array('action' => 'ApiTimelineFavorites',
150 'format' => '(xml|json|rss|atom|as)'));
151 $m->connect('api/favorites/create/:id.:format',
152 array('action' => 'ApiFavoriteCreate',
154 'format' => '(xml|json)'));
155 $m->connect('api/favorites/destroy/:id.:format',
156 array('action' => 'ApiFavoriteDestroy',
158 'format' => '(xml|json)'));
161 $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
162 array('action' => 'AtomPubShowFavorite'),
163 array('profile' => '[0-9]+',
164 'notice' => '[0-9]+'));
166 $m->connect('api/statusnet/app/favorites/:profile.atom',
167 array('action' => 'AtomPubFavoriteFeed'),
168 array('profile' => '[0-9]+'));
170 // Required for qvitter API
171 $m->connect('api/statuses/favs/:id.:format',
172 array('action' => 'ApiStatusesFavs',
174 'format' => '(xml|json)'));
177 // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
178 protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
180 assert($this->isMyActivity($act));
182 // If empty, we should've created it ourselves on our node.
183 if (!isset($options['created'])) {
184 $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
187 // We must have an objects[0] here because in isMyActivity we require the count to be == 1
188 $actobj = $act->objects[0];
190 $object = Fave::saveActivityObject($actobj, $stored);
194 // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
195 // with the other microapps/activityhandlers as well.
196 // Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
197 public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
199 if (!$this->isMyNotice($stored)) {
203 common_debug('Extending activity '.$stored->id.' with '.get_called_class());
204 $this->extendActivity($stored, $act, $scoped);
208 public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
210 Fave::extendActivity($stored, $act, $scoped);
213 public function activityObjectFromNotice(Notice $notice)
215 $fave = Fave::fromStored($notice);
216 return $fave->asActivityObject();
219 public function deleteRelated(Notice $notice)
222 $fave = Fave::fromStored($notice);
224 } catch (NoResultException $e) {
225 // Cool, no problem. We wanted to get rid of it anyway.
229 protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
231 require_once INSTALLDIR.'/lib/mail.php';
233 foreach ($mentioned_ids as $id) {
234 $mentioned = User::getKV('id', $id);
235 if ($mentioned instanceof User && $mentioned->id != $stored->profile_id
236 && $mentioned->email && $mentioned->getPref('email', 'notify_fave', $this->email_notify_fave)) { // do we have an email, and does user want it?
237 mail_notify_fave($mentioned, $stored->getProfile(), $stored->getParent());
245 * Typically just used to fill out Twitter-compatible API status data.
247 * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
249 public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
251 if ($scoped instanceof Profile) {
252 $status['favorited'] = Fave::existsForProfile($notice, $scoped);
254 $status['favorited'] = false;
259 public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
261 $userdata['favourites_count'] = Fave::countByProfile($profile);
265 * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
267 public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
269 if ($scoped instanceof Profile) {
270 $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
275 public function onNoticeDeleteRelated(Notice $notice)
277 parent::onNoticeDeleteRelated($notice);
279 // The below algorithm is because we want to delete fave
280 // activities on any notice which _has_ faves, and not as
281 // in the parent function only ones that _are_ faves.
284 $fave->notice_id = $notice->id;
287 while ($fave->fetch()) {
295 public function onUserDeleteRelated(User $user, array &$related)
298 $fave->user_id = $user->id;
299 $fave->delete(); // Will perform a DELETE matching "user_id = {$user->id}"
301 Fave::blowCacheForProfileId($user->id);
305 public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
307 // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
308 Fave::fillFaves($notice_ids);
311 if ($scoped instanceof Profile) {
312 Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
317 * show the "favorite" form in the notice options element
318 * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
322 public function onStartShowNoticeOptionItems($nli)
324 if (Event::handle('StartShowFaveForm', array($nli))) {
325 $scoped = Profile::current();
326 if ($scoped instanceof Profile) {
327 if (Fave::existsForProfile($nli->notice, $scoped)) {
328 $disfavor = new DisfavorForm($nli->out, $nli->notice);
331 $favor = new FavorForm($nli->out, $nli->notice);
335 Event::handle('EndShowFaveForm', array($nli));
339 public function showNoticeListItem(NoticeListItem $nli)
343 public function openNoticeListItemElement(NoticeListItem $nli)
347 public function closeNoticeListItemElement(NoticeListItem $nli)
352 public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
356 $fave->user_id = $uas->getUser()->id;
358 if (!empty($uas->after)) {
359 $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
363 while ($fave->fetch()) {
364 $faves[] = clone($fave);
371 public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
373 if ($nli instanceof ThreadedNoticeListSubItem) {
374 // The sub-items are replies to a conversation, thus we use different HTML elements etc.
375 $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
377 $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
379 $threadActive = $item->show() || $threadActive;
384 * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
385 * using the class FavCommand.
387 * @param string $cmd Command being run
388 * @param string $arg Rest of the message (including address)
389 * @param User $user User sending the message
390 * @param Command &$result The resulting command object to be run.
392 * @return boolean hook value
394 public function onStartInterpretCommand($cmd, $arg, $user, &$result)
396 if ($result === false && $cmd == 'fav') {
400 list($other, $extra) = CommandInterpreter::split_arg($arg);
401 if (!empty($extra)) {
404 $result = new FavCommand($user, $other);
412 public function onHelpCommandMessages(HelpCommand $help, array &$commands)
414 // TRANS: Help message for IM/SMS command "fav <nickname>".
415 $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
416 // TRANS: Help message for IM/SMS command "fav #<notice_id>".
417 $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
421 * Are we allowed to perform a certain command over the API?
423 public function onCommandSupportedAPI(Command $cmd, &$supported)
425 $supported = $supported || $cmd instanceof FavCommand;
428 // Form stuff (settings etc.)
430 public function onEndEmailFormData(Action $action, Profile $scoped)
432 // getConfigData will fall back on systemwide default
433 // and we only wish to save numerical true or false.
434 $emailfave = $scoped->getPref('email', 'notify_fave', $this->email_notify_fave) ? 1 : 0;
436 $action->elementStart('li');
437 $action->checkbox('email-notify_fave',
438 // TRANS: Checkbox label in e-mail preferences form.
439 _('Send me email when someone adds my notice as a favorite.'),
441 $action->elementEnd('li');
446 public function onStartEmailSaveForm(Action $action, Profile $scoped)
448 $emailfave = $action->boolean('email-notify_fave') ? 1 : 0;
450 if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
451 // No need to update setting
454 } catch (NoResultException $e) {
455 // Apparently there's no previously stored setting, then continue to save it as it is now.
458 $scoped->setPref('email', 'notify_fave', $emailfave);
465 public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
467 $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
468 // TRANS: Menu item in personal group navigation menu.
469 _m('MENU','Favorites'),
470 // @todo i18n FIXME: Need to make this two messages.
471 // TRANS: Menu item title in personal group navigation menu.
472 // TRANS: %s is a username.
473 sprintf(_('%s\'s favorite notices'), $target->getBestName()),
474 $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
475 'nav_timeline_favorites');
478 public function onEndPublicGroupNav(Menu $menu)
480 if (!common_config('singleuser', 'enabled')) {
481 // TRANS: Menu item in search group navigation panel.
482 $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
483 // TRANS: Menu item title in search group navigation panel.
484 _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
488 public function onEndShowSections(Action $action)
490 if (!$action->isAction(array('all', 'public'))) {
494 if (!common_config('performance', 'high')) {
495 $section = new PopularNoticeSection($action, $action->getScoped());
500 public function onPluginVersion(array &$versions)
502 $versions[] = array('name' => 'Favorite',
503 'version' => GNUSOCIAL_VERSION,
504 'author' => 'Mikael Nordfeldth',
505 'homepage' => 'http://gnu.io/',
507 // TRANS: Plugin description.
508 _m('Favorites (likes) using ActivityStreams.'));