]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
Merge branch 'master' into nightly
[quix0rs-gnu-social.git] / plugins / Favorite / FavoritePlugin.php
1 <?php
2 /*
3  * GNU Social - a federating social network
4  * Copyright (C) 2014, Free Software Foundation, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * @package     Activity
24  * @maintainer  Mikael Nordfeldth <mmn@hethane.se>
25  */
26 class FavoritePlugin extends ActivityVerbHandlerPlugin
27 {
28     protected $email_notify_fave = 1;
29
30     public function tag()
31     {
32         return 'favorite';
33     }
34
35     public function types()
36     {
37         return array();
38     }
39
40     public function verbs()
41     {
42         return array(ActivityVerb::FAVORITE, ActivityVerb::LIKE,
43                     ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE);
44     }
45
46     public function onCheckSchema()
47     {
48         $schema = Schema::get();
49         $schema->ensureTable('fave', Fave::schemaDef());
50         return true;
51     }
52
53     public function initialize()
54     {
55         common_config_set('email', 'notify_fave', $this->email_notify_fave);
56     }
57
58     public function onStartUpgrade()
59     {
60         // This is a migration feature that will make sure we move
61         // certain User preferences to the Profile_prefs table.
62         // Introduced after commit b5fd2a048fc621ea05d756caba17275ab3dd0af4
63         // on Sun Jul 13 16:30:37 2014 +0200
64         $user = new User();
65         $user->whereAdd('emailnotifyfav IS NOT NULL');
66         if ($user->find()) {
67             printfnq("Detected old User table (emailnotifyfav IS NOT NULL). Moving 'emailnotifyfav' property to Profile_prefs...");
68             // First we'll make sure Profile_prefs exists
69             $schema = Schema::get();
70             $schema->ensureTable('profile_prefs', Profile_prefs::schemaDef());
71
72             // Make sure we have our own tables setup properly
73             while ($user->fetch()) {
74                 $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
75                 $orig = clone($user);
76                 $user->emailnotifyfav = 'null';   // flag this preference as migrated
77                 $user->update($orig);
78             }
79             printfnq("DONE.\n");
80         }
81     }
82
83     public function onEndUpgrade()
84     {
85         printfnq("Ensuring all faves have a URI...");
86
87         $fave = new Fave();
88         $fave->whereAdd('uri IS NULL');
89
90         if ($fave->find()) {
91             while ($fave->fetch()) {
92                 try {
93                     $fave->decache();
94                     $fave->query(sprintf('UPDATE fave '.
95                                          'SET uri = "%s", '.
96                                          '    modified = "%s" '.
97                                          'WHERE user_id = %d '.
98                                          'AND notice_id = %d',
99                                          Fave::newUri($fave->getActor(), $fave->getTarget(), $fave->modified),
100                                          common_sql_date(strtotime($fave->modified)),
101                                          $fave->user_id,
102                                          $fave->notice_id));
103                 } catch (Exception $e) {
104                     common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
105                 }
106             }
107         }
108
109         printfnq("DONE.\n");
110     }
111
112     public function onRouterInitialized(URLMapper $m)
113     {
114         // Web UI actions
115         $m->connect('main/favor', array('action' => 'favor'));
116         $m->connect('main/disfavor', array('action' => 'disfavor'));
117
118         if (common_config('singleuser', 'enabled')) {
119             $nickname = User::singleUserNickname();
120
121             $m->connect('favorites',
122                         array('action' => 'showfavorites',
123                               'nickname' => $nickname));
124             $m->connect('favoritesrss',
125                         array('action' => 'favoritesrss',
126                               'nickname' => $nickname));
127         } else {
128             $m->connect('favoritedrss', array('action' => 'favoritedrss'));
129             $m->connect('favorited/', array('action' => 'favorited'));
130             $m->connect('favorited', array('action' => 'favorited'));
131
132             $m->connect(':nickname/favorites',
133                         array('action' => 'showfavorites'),
134                         array('nickname' => Nickname::DISPLAY_FMT));
135             $m->connect(':nickname/favorites/rss',
136                         array('action' => 'favoritesrss'),
137                         array('nickname' => Nickname::DISPLAY_FMT));
138         }
139
140         // Favorites for API
141         $m->connect('api/favorites/create.:format',
142                     array('action' => 'ApiFavoriteCreate'),
143                     array('format' => '(xml|json)'));
144         $m->connect('api/favorites/destroy.:format',
145                     array('action' => 'ApiFavoriteDestroy'),
146                     array('format' => '(xml|json)'));
147         $m->connect('api/favorites/list.:format',
148                     array('action' => 'ApiTimelineFavorites'),
149                     array('format' => '(xml|json|rss|atom|as)'));
150         $m->connect('api/favorites/:id.:format',
151                     array('action' => 'ApiTimelineFavorites'),
152                     array('id' => Nickname::INPUT_FMT,
153                           'format' => '(xml|json|rss|atom|as)'));
154         $m->connect('api/favorites.:format',
155                     array('action' => 'ApiTimelineFavorites'),
156                     array('format' => '(xml|json|rss|atom|as)'));
157         $m->connect('api/favorites/create/:id.:format',
158                     array('action' => 'ApiFavoriteCreate'),
159                     array('id' => '[0-9]+',
160                           'format' => '(xml|json)'));
161         $m->connect('api/favorites/destroy/:id.:format',
162                     array('action' => 'ApiFavoriteDestroy'),
163                     array('id' => '[0-9]+',
164                           'format' => '(xml|json)'));
165
166         // AtomPub API
167         $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
168                     array('action' => 'AtomPubShowFavorite'),
169                     array('profile' => '[0-9]+',
170                           'notice' => '[0-9]+'));
171
172         $m->connect('api/statusnet/app/favorites/:profile.atom',
173                     array('action' => 'AtomPubFavoriteFeed'),
174                     array('profile' => '[0-9]+'));
175
176         // Required for qvitter API
177         $m->connect('api/statuses/favs/:id.:format',
178                     array('action' => 'ApiStatusesFavs'),
179                     array('id' => '[0-9]+',
180                           'format' => '(xml|json)'));
181     }
182
183     // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
184     protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())
185     {
186         assert($this->isMyActivity($act));
187
188         // We must have an objects[0] here because in isMyActivity we require the count to be == 1
189         $actobj = $act->objects[0];
190
191         $object = Fave::saveActivityObject($actobj, $stored);
192
193         return $object;
194     }
195
196     // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
197     //          with the other microapps/activityhandlers as well.
198     //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
199     public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
200     {
201         if (!$this->isMyNotice($stored)) {
202             return true;
203         }
204
205         $this->extendActivity($stored, $act, $scoped);
206         return false;
207     }
208
209     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
210     {
211         Fave::extendActivity($stored, $act, $scoped);
212     }
213
214     public function activityObjectFromNotice(Notice $notice)
215     {
216         $fave = Fave::fromStored($notice);
217         return $fave->asActivityObject();
218     }
219
220     public function deleteRelated(Notice $notice)
221     {
222         try {
223             $fave = Fave::fromStored($notice);
224             $fave->delete();
225         } catch (NoResultException $e) {
226             // Cool, no problem. We wanted to get rid of it anyway.
227         }
228     }
229
230     // API stuff
231
232     /**
233      * Typically just used to fill out Twitter-compatible API status data.
234      *
235      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
236      */
237     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
238     {
239         if ($scoped instanceof Profile) {
240             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
241         } else {
242             $status['favorited'] = false;
243         }
244         return true;
245     }
246
247     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
248     {
249         $userdata['favourites_count'] = Fave::countByProfile($profile);
250     }
251
252     /**
253      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
254      */
255     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
256     {
257         if ($scoped instanceof Profile) {
258             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
259         }
260         return true;
261     }
262
263     public function onNoticeDeleteRelated(Notice $notice)
264     {
265         parent::onNoticeDeleteRelated($notice);
266
267         // The below algorithm is because we want to delete fave
268         // activities on any notice which _has_ faves, and not as
269         // in the parent function only ones that _are_ faves.
270
271         $fave = new Fave();
272         $fave->notice_id = $notice->id;
273
274         if ($fave->find()) {
275             while ($fave->fetch()) {
276                 $fave->delete();
277             }
278         }
279
280         $fave->free();
281     }
282
283     public function onProfileDeleteRelated(Profile $profile, array &$related)
284     {
285         $fave = new Fave();
286         $fave->user_id = $profile->id;
287         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
288         $fave->free();
289
290         Fave::blowCacheForProfileId($profile->id);
291         return true;
292     }
293
294     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
295     {
296         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
297         Fave::fillFaves($notice_ids);
298
299         // DB caching
300         if ($scoped instanceof Profile) {
301             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
302         }
303     }
304
305     /**
306      * show the "favorite" form in the notice options element
307      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
308      *
309      * @return void
310      */
311     public function onStartShowNoticeOptionItems($nli)
312     {
313         if (Event::handle('StartShowFaveForm', array($nli))) {
314             $scoped = Profile::current();
315             if ($scoped instanceof Profile) {
316                 if (Fave::existsForProfile($nli->notice, $scoped)) {
317                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
318                     $disfavor->show();
319                 } else {
320                     $favor = new FavorForm($nli->out, $nli->notice);
321                     $favor->show();
322                 }
323             }
324             Event::handle('EndShowFaveForm', array($nli));
325         }
326     }
327
328     protected function showNoticeListItem(NoticeListItem $nli)
329     {
330         // pass
331     }
332     public function openNoticeListItemElement(NoticeListItem $nli)
333     {
334         // pass
335     }
336     public function closeNoticeListItemElement(NoticeListItem $nli)
337     {
338         // pass
339     }
340
341     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
342     {
343         $fave = new Fave();
344         $fave->user_id = $uas->getUser()->id;
345
346         if (!empty($uas->after)) {
347             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
348         }
349
350         if ($fave->find()) {
351             while ($fave->fetch()) {
352                 $objs[] = clone($fave);
353             }
354         }
355
356         return true;
357     }
358
359     public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
360     {
361         if ($nli instanceof ThreadedNoticeListSubItem) {
362             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
363             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
364         } else {
365             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
366         }
367         $threadActive = $item->show() || $threadActive;
368         return true;
369     }
370
371     public function onEndFavorNotice(Profile $actor, Notice $target)
372     {
373         try {
374             $notice_author = $target->getProfile();
375             // Don't notify ourselves of our own favorite on our own notice,
376             // or if it's a remote user (since we don't know their email addresses etc.)
377             if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
378                 return true;
379             }
380             $local_user = $notice_author->getUser();
381             mail_notify_fave($local_user, $actor, $target);
382         } catch (Exception $e) {
383             // Mm'kay, probably not a local user. Let's skip this favor notification.
384         }
385     }
386
387     /**
388      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
389      * using the class FavCommand.
390      *
391      * @param string  $cmd     Command being run
392      * @param string  $arg     Rest of the message (including address)
393      * @param User    $user    User sending the message
394      * @param Command &$result The resulting command object to be run.
395      *
396      * @return boolean hook value
397      */
398     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
399     {
400         if ($result === false && $cmd == 'fav') {
401             if (empty($arg)) {
402                 $result = null;
403             } else {
404                 list($other, $extra) = CommandInterpreter::split_arg($arg);
405                 if (!empty($extra)) {
406                     $result = null;
407                 } else {
408                     $result = new FavCommand($user, $other);
409                 }
410             }
411             return false;
412         }
413         return true;
414     }
415
416     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
417     {
418         // TRANS: Help message for IM/SMS command "fav <nickname>".
419         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
420         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
421         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
422     }
423
424     /**
425      * Are we allowed to perform a certain command over the API?
426      */
427     public function onCommandSupportedAPI(Command $cmd, &$supported)
428     {
429         $supported = $supported || $cmd instanceof FavCommand;
430     }
431
432     // Form stuff (settings etc.)
433
434     public function onEndEmailFormData(Action $action, Profile $scoped)
435     {
436         $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
437
438         $action->elementStart('li');
439         $action->checkbox('email-notify_fave',
440                         // TRANS: Checkbox label in e-mail preferences form.
441                         _('Send me email when someone adds my notice as a favorite.'),
442                         $emailfave);
443         $action->elementEnd('li');
444
445         return true;
446     }
447
448     public function onStartEmailSaveForm(Action $action, Profile $scoped)
449     {
450         $emailfave = $action->booleanintstring('email-notify_fave');
451         try {
452             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
453                 // No need to update setting
454                 return true;
455             }
456         } catch (NoResultException $e) {
457             // Apparently there's no previously stored setting, then continue to save it as it is now.
458         }
459
460         $scoped->setPref('email', 'notify_fave', $emailfave);
461
462         return true;
463     }
464
465     // Layout stuff
466
467     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
468     {
469         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
470                              // TRANS: Menu item in personal group navigation menu.
471                              _m('MENU','Favorites'),
472                              // @todo i18n FIXME: Need to make this two messages.
473                              // TRANS: Menu item title in personal group navigation menu.
474                              // TRANS: %s is a username.
475                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
476                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
477                             'nav_timeline_favorites');
478     }
479
480     public function onEndPublicGroupNav(Menu $menu)
481     {
482         if (!common_config('singleuser', 'enabled')) {
483             // TRANS: Menu item in search group navigation panel.
484             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
485                                  // TRANS: Menu item title in search group navigation panel.
486                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
487         }
488     }
489
490     public function onEndShowSections(Action $action)
491     {
492         if (!$action->isAction(array('all', 'public'))) {
493             return true;
494         }
495
496         if (!common_config('performance', 'high')) {
497             $section = new PopularNoticeSection($action, $action->getScoped());
498             $section->show();
499         }
500     }
501
502     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
503     {
504         return Fave::existsForProfile($target, $scoped)
505                 // TRANS: Page/dialog box title when a notice is marked as favorite already
506                 ? _m('TITLE', 'Unmark notice as favorite')
507                 // TRANS: Page/dialog box title when a notice is not marked as favorite
508                 : _m('TITLE', 'Mark notice as favorite');
509     }
510
511     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
512     {
513         if ($action->isPost()) {
514             // The below tests are only for presenting to the user. POSTs which inflict
515             // duplicate favorite entries are handled with AlreadyFulfilledException. 
516             return false;
517         }
518
519         $exists = Fave::existsForProfile($target, $scoped);
520         $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
521
522         switch (true) {
523         case $exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
524         case !$exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
525             common_redirect(common_local_url('activityverb',
526                                 array('id'   => $target->getID(),
527                                       'verb' => ActivityUtils::resolveUri($expected_verb, true))));
528             break;
529         default:
530             // No need to redirect as we are on the correct action already.
531         }
532
533         return false;
534     }
535
536     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
537     {
538         switch (true) {
539         case ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
540             Fave::addNew($scoped, $target);
541             break;
542         case ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
543             Fave::removeEntry($scoped, $target);
544             break;
545         default:
546             throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
547         }
548         return false;
549     }
550
551     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
552     {
553         return Fave::existsForProfile($target, $scoped)
554                 ? new DisfavorForm($action, $target)
555                 : new FavorForm($action, $target);
556     }
557
558     public function onPluginVersion(array &$versions)
559     {
560         $versions[] = array('name' => 'Favorite',
561                             'version' => GNUSOCIAL_VERSION,
562                             'author' => 'Mikael Nordfeldth',
563                             'homepage' => 'http://gnu.io/',
564                             'rawdescription' =>
565                             // TRANS: Plugin description.
566                             _m('Favorites (likes) using ActivityStreams.'));
567
568         return true;
569     }
570 }
571
572 /**
573  * Notify a user that one of their notices has been chosen as a 'fave'
574  *
575  * @param User    $rcpt   The user whose notice was faved
576  * @param Profile $sender The user who faved the notice
577  * @param Notice  $notice The notice that was faved
578  *
579  * @return void
580  */
581 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
582 {
583     if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
584         return;
585     }
586
587     // This test is actually "if the sender is sandboxed"
588     if (!$sender->hasRight(Right::EMAILONFAVE)) {
589         return;
590     }
591
592     if ($rcpt->hasBlocked($sender)) {
593         // If the author has blocked us, don't spam them with a notification.
594         return;
595     }
596
597     // We need the global mail.php for various mail related functions below.
598     require_once INSTALLDIR.'/lib/mail.php';
599
600     $bestname = $sender->getBestName();
601
602     common_switch_locale($rcpt->language);
603
604     // TRANS: Subject for favorite notification e-mail.
605     // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
606     $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
607
608     // TRANS: Body for favorite notification e-mail.
609     // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
610     // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
611     // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
612     // TRANS: %7$s is the adding user's nickname.
613     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
614                       " as one of their favorites.\n\n" .
615                       "The URL of your notice is:\n\n" .
616                       "%3\$s\n\n" .
617                       "The text of your notice is:\n\n" .
618                       "%4\$s\n\n" .
619                       "You can see the list of %1\$s's favorites here:\n\n" .
620                       "%5\$s"),
621                     $bestname,
622                     common_exact_date($notice->created),
623                     common_local_url('shownotice',
624                                      array('notice' => $notice->id)),
625                     $notice->content,
626                     common_local_url('showfavorites',
627                                      array('nickname' => $sender->getNickname())),
628                     common_config('site', 'name'),
629                     $sender->getNickname()) .
630             mail_footer_block();
631
632     $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
633
634     common_switch_locale();
635     mail_to_user($rcpt, $subject, $body, $headers);
636 }