]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
Merge branch 'master' of git.gnu.io:gnu/gnu-social 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->user_id, $fave->notice_id, $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         // If empty, we should've created it ourselves on our node.
189         if (!isset($options['created'])) {
190             $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
191         }
192
193         // We must have an objects[0] here because in isMyActivity we require the count to be == 1
194         $actobj = $act->objects[0];
195
196         $object = Fave::saveActivityObject($actobj, $stored);
197         $stored->object_type = $object->getObjectType();
198
199         return $object;
200     }
201
202     // FIXME: Put this in lib/activityhandlerplugin.php when we're ready
203     //          with the other microapps/activityhandlers as well.
204     //          Also it should be StartNoticeAsActivity (with a prepped Activity, including ->context etc.)
205     public function onEndNoticeAsActivity(Notice $stored, Activity $act, Profile $scoped=null)
206     {
207         if (!$this->isMyNotice($stored)) {
208             return true;
209         }
210
211         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
212         $this->extendActivity($stored, $act, $scoped);
213         return false;
214     }
215
216     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
217     {
218         Fave::extendActivity($stored, $act, $scoped);
219     }
220
221     public function activityObjectFromNotice(Notice $notice)
222     {
223         $fave = Fave::fromStored($notice);
224         return $fave->asActivityObject();
225     }
226
227     public function deleteRelated(Notice $notice)
228     {
229         try {
230             $fave = Fave::fromStored($notice);
231             $fave->delete();
232         } catch (NoResultException $e) {
233             // Cool, no problem. We wanted to get rid of it anyway.
234         }
235     }
236
237     // API stuff
238
239     /**
240      * Typically just used to fill out Twitter-compatible API status data.
241      *
242      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
243      */
244     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
245     {
246         if ($scoped instanceof Profile) {
247             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
248         } else {
249             $status['favorited'] = false;
250         }
251         return true;
252     }
253
254     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
255     {
256         $userdata['favourites_count'] = Fave::countByProfile($profile);
257     }
258
259     /**
260      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
261      */
262     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
263     {
264         if ($scoped instanceof Profile) {
265             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
266         }
267         return true;
268     }
269
270     public function onNoticeDeleteRelated(Notice $notice)
271     {
272         parent::onNoticeDeleteRelated($notice);
273
274         // The below algorithm is because we want to delete fave
275         // activities on any notice which _has_ faves, and not as
276         // in the parent function only ones that _are_ faves.
277
278         $fave = new Fave();
279         $fave->notice_id = $notice->id;
280
281         if ($fave->find()) {
282             while ($fave->fetch()) {
283                 $fave->delete();
284             }
285         }
286
287         $fave->free();
288     }
289
290     public function onProfileDeleteRelated(Profile $profile, array &$related)
291     {
292         $fave = new Fave();
293         $fave->user_id = $profile->id;
294         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
295         $fave->free();
296
297         Fave::blowCacheForProfileId($profile->id);
298         return true;
299     }
300
301     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
302     {
303         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
304         Fave::fillFaves($notice_ids);
305
306         // DB caching
307         if ($scoped instanceof Profile) {
308             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
309         }
310     }
311
312     /**
313      * show the "favorite" form in the notice options element
314      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
315      *
316      * @return void
317      */
318     public function onStartShowNoticeOptionItems($nli)
319     {
320         if (Event::handle('StartShowFaveForm', array($nli))) {
321             $scoped = Profile::current();
322             if ($scoped instanceof Profile) {
323                 if (Fave::existsForProfile($nli->notice, $scoped)) {
324                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
325                     $disfavor->show();
326                 } else {
327                     $favor = new FavorForm($nli->out, $nli->notice);
328                     $favor->show();
329                 }
330             }
331             Event::handle('EndShowFaveForm', array($nli));
332         }
333     }
334
335     protected function showNoticeListItem(NoticeListItem $nli)
336     {
337         // pass
338     }
339     public function openNoticeListItemElement(NoticeListItem $nli)
340     {
341         // pass
342     }
343     public function closeNoticeListItemElement(NoticeListItem $nli)
344     {
345         // pass
346     }
347
348     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
349     {
350         $fave = new Fave();
351         $fave->user_id = $uas->getUser()->id;
352
353         if (!empty($uas->after)) {
354             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
355         }
356
357         if ($fave->find()) {
358             while ($fave->fetch()) {
359                 $objs[] = clone($fave);
360             }
361         }
362
363         return true;
364     }
365
366     public function onEndShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
367     {
368         if ($nli instanceof ThreadedNoticeListSubItem) {
369             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
370             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
371         } else {
372             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
373         }
374         $threadActive = $item->show() || $threadActive;
375         return true;
376     }
377
378     public function onEndFavorNotice(Profile $actor, Notice $target)
379     {
380         try {
381             $notice_author = $target->getProfile();
382             // Don't notify ourselves of our own favorite on our own notice,
383             // or if it's a remote user (since we don't know their email addresses etc.)
384             if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
385                 return true;
386             }
387             $local_user = $notice_author->getUser();
388             mail_notify_fave($local_user, $actor, $target);
389         } catch (Exception $e) {
390             // Mm'kay, probably not a local user. Let's skip this favor notification.
391         }
392     }
393
394     /**
395      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
396      * using the class FavCommand.
397      *
398      * @param string  $cmd     Command being run
399      * @param string  $arg     Rest of the message (including address)
400      * @param User    $user    User sending the message
401      * @param Command &$result The resulting command object to be run.
402      *
403      * @return boolean hook value
404      */
405     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
406     {
407         if ($result === false && $cmd == 'fav') {
408             if (empty($arg)) {
409                 $result = null;
410             } else {
411                 list($other, $extra) = CommandInterpreter::split_arg($arg);
412                 if (!empty($extra)) {
413                     $result = null;
414                 } else {
415                     $result = new FavCommand($user, $other);
416                 }
417             }
418             return false;
419         }
420         return true;
421     }
422
423     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
424     {
425         // TRANS: Help message for IM/SMS command "fav <nickname>".
426         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
427         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
428         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
429     }
430
431     /**
432      * Are we allowed to perform a certain command over the API?
433      */
434     public function onCommandSupportedAPI(Command $cmd, &$supported)
435     {
436         $supported = $supported || $cmd instanceof FavCommand;
437     }
438
439     // Form stuff (settings etc.)
440
441     public function onEndEmailFormData(Action $action, Profile $scoped)
442     {
443         $emailfave = $scoped->getConfigPref('email', 'notify_fave') ? 1 : 0;
444
445         $action->elementStart('li');
446         $action->checkbox('email-notify_fave',
447                         // TRANS: Checkbox label in e-mail preferences form.
448                         _('Send me email when someone adds my notice as a favorite.'),
449                         $emailfave);
450         $action->elementEnd('li');
451
452         return true;
453     }
454
455     public function onStartEmailSaveForm(Action $action, Profile $scoped)
456     {
457         $emailfave = $action->booleanintstring('email-notify_fave');
458         try {
459             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
460                 // No need to update setting
461                 return true;
462             }
463         } catch (NoResultException $e) {
464             // Apparently there's no previously stored setting, then continue to save it as it is now.
465         }
466
467         $scoped->setPref('email', 'notify_fave', $emailfave);
468
469         return true;
470     }
471
472     // Layout stuff
473
474     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
475     {
476         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
477                              // TRANS: Menu item in personal group navigation menu.
478                              _m('MENU','Favorites'),
479                              // @todo i18n FIXME: Need to make this two messages.
480                              // TRANS: Menu item title in personal group navigation menu.
481                              // TRANS: %s is a username.
482                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
483                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
484                             'nav_timeline_favorites');
485     }
486
487     public function onEndPublicGroupNav(Menu $menu)
488     {
489         if (!common_config('singleuser', 'enabled')) {
490             // TRANS: Menu item in search group navigation panel.
491             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
492                                  // TRANS: Menu item title in search group navigation panel.
493                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
494         }
495     }
496
497     public function onEndShowSections(Action $action)
498     {
499         if (!$action->isAction(array('all', 'public'))) {
500             return true;
501         }
502
503         if (!common_config('performance', 'high')) {
504             $section = new PopularNoticeSection($action, $action->getScoped());
505             $section->show();
506         }
507     }
508
509     protected function getActionTitle(ManagedAction $action, $verb, Notice $target, Profile $scoped)
510     {
511         return Fave::existsForProfile($target, $scoped)
512                 // TRANS: Page/dialog box title when a notice is marked as favorite already
513                 ? _m('TITLE', 'Unmark notice as favorite')
514                 // TRANS: Page/dialog box title when a notice is not marked as favorite
515                 : _m('TITLE', 'Mark notice as favorite');
516     }
517
518     protected function doActionPreparation(ManagedAction $action, $verb, Notice $target, Profile $scoped)
519     {
520         if ($action->isPost()) {
521             // The below tests are only for presenting to the user. POSTs which inflict
522             // duplicate favorite entries are handled with AlreadyFulfilledException. 
523             return false;
524         }
525
526         $exists = Fave::existsForProfile($target, $scoped);
527         $expected_verb = $exists ? ActivityVerb::UNFAVORITE : ActivityVerb::FAVORITE;
528
529         switch (true) {
530         case $exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
531         case !$exists && ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
532             common_redirect(common_local_url('activityverb',
533                                 array('id'   => $target->getID(),
534                                       'verb' => ActivityUtils::resolveUri($expected_verb, true))));
535             break;
536         default:
537             // No need to redirect as we are on the correct action already.
538         }
539
540         return false;
541     }
542
543     protected function doActionPost(ManagedAction $action, $verb, Notice $target, Profile $scoped)
544     {
545         switch (true) {
546         case ActivityUtils::compareVerbs($verb, array(ActivityVerb::FAVORITE, ActivityVerb::LIKE)):
547             Fave::addNew($scoped, $target);
548             break;
549         case ActivityUtils::compareVerbs($verb, array(ActivityVerb::UNFAVORITE, ActivityVerb::UNLIKE)):
550             Fave::removeEntry($scoped, $target);
551             break;
552         default:
553             throw new ServerException('ActivityVerb POST not handled by plugin that was supposed to do it.');
554         }
555         return false;
556     }
557
558     protected function getActivityForm(ManagedAction $action, $verb, Notice $target, Profile $scoped)
559     {
560         return Fave::existsForProfile($target, $scoped)
561                 ? new DisfavorForm($action, $target)
562                 : new FavorForm($action, $target);
563     }
564
565     public function onPluginVersion(array &$versions)
566     {
567         $versions[] = array('name' => 'Favorite',
568                             'version' => GNUSOCIAL_VERSION,
569                             'author' => 'Mikael Nordfeldth',
570                             'homepage' => 'http://gnu.io/',
571                             'rawdescription' =>
572                             // TRANS: Plugin description.
573                             _m('Favorites (likes) using ActivityStreams.'));
574
575         return true;
576     }
577 }
578
579 /**
580  * Notify a user that one of their notices has been chosen as a 'fave'
581  *
582  * @param User    $rcpt   The user whose notice was faved
583  * @param Profile $sender The user who faved the notice
584  * @param Notice  $notice The notice that was faved
585  *
586  * @return void
587  */
588 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
589 {
590     if (!$rcpt->receivesEmailNotifications() || !$rcpt->getConfigPref('email', 'notify_fave')) {
591         return;
592     }
593
594     // This test is actually "if the sender is sandboxed"
595     if (!$sender->hasRight(Right::EMAILONFAVE)) {
596         return;
597     }
598
599     if ($rcpt->hasBlocked($sender)) {
600         // If the author has blocked us, don't spam them with a notification.
601         return;
602     }
603
604     // We need the global mail.php for various mail related functions below.
605     require_once INSTALLDIR.'/lib/mail.php';
606
607     $bestname = $sender->getBestName();
608
609     common_switch_locale($rcpt->language);
610
611     // TRANS: Subject for favorite notification e-mail.
612     // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
613     $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
614
615     // TRANS: Body for favorite notification e-mail.
616     // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
617     // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
618     // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
619     // TRANS: %7$s is the adding user's nickname.
620     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
621                       " as one of their favorites.\n\n" .
622                       "The URL of your notice is:\n\n" .
623                       "%3\$s\n\n" .
624                       "The text of your notice is:\n\n" .
625                       "%4\$s\n\n" .
626                       "You can see the list of %1\$s's favorites here:\n\n" .
627                       "%5\$s"),
628                     $bestname,
629                     common_exact_date($notice->created),
630                     common_local_url('shownotice',
631                                      array('notice' => $notice->id)),
632                     $notice->content,
633                     common_local_url('showfavorites',
634                                      array('nickname' => $sender->getNickname())),
635                     common_config('site', 'name'),
636                     $sender->getNickname()) .
637             mail_footer_block();
638
639     $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
640
641     common_switch_locale();
642     mail_to_user($rcpt, $subject, $body, $headers);
643 }