]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
$this out of context (use $rcpt)
[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 ActivityHandlerPlugin
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);
43     }
44     
45     public function onCheckSchema()
46     {
47         $schema = Schema::get();
48         $schema->ensureTable('fave', Fave::schemaDef());
49         return true;
50     }
51
52     public function onStartUpgrade()
53     {
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
58         $user = new User();
59         $user->whereAdd('emailnotifyfav IS NOT NULL');
60         if ($user->find()) {
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());
65
66             // Make sure we have our own tables setup properly
67             while ($user->fetch()) {
68                 $user->setPref('email', 'notify_fave', $user->emailnotifyfav);
69                 $orig = clone($user);
70                 $user->emailnotifyfav = 'null';   // flag this preference as migrated
71                 $user->update($orig);
72             }
73             printfnq("DONE.\n");
74         }
75     }
76     
77     public function onEndUpgrade()
78     {
79         printfnq("Ensuring all faves have a URI...");
80     
81         $fave = new Fave();
82         $fave->whereAdd('uri IS NULL');
83     
84         if ($fave->find()) {
85             while ($fave->fetch()) {
86                 try {
87                     $fave->decache();
88                     $fave->query(sprintf('UPDATE fave '.
89                                          'SET uri = "%s", '.
90                                          '    modified = "%s" '.
91                                          'WHERE user_id = %d '.
92                                          'AND notice_id = %d',
93                                          Fave::newUri($fave->user_id, $fave->notice_id, $fave->modified),
94                                          common_sql_date(strtotime($fave->modified)),
95                                          $fave->user_id,
96                                          $fave->notice_id));
97                 } catch (Exception $e) {
98                     common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
99                 }
100             }
101         }
102     
103         printfnq("DONE.\n");
104     }
105
106     public function onRouterInitialized(URLMapper $m)
107     {
108         // Web UI actions
109         $m->connect('main/favor', array('action' => 'favor'));
110         $m->connect('main/disfavor', array('action' => 'disfavor'));
111
112         if (common_config('singleuser', 'enabled')) {
113             $nickname = User::singleUserNickname();
114
115             $m->connect('favorites',
116                         array('action' => 'showfavorites',
117                               'nickname' => $nickname));
118             $m->connect('favoritesrss',
119                         array('action' => 'favoritesrss',
120                               'nickname' => $nickname));
121         } else {
122             $m->connect('favoritedrss', array('action' => 'favoritedrss'));
123             $m->connect('favorited/', array('action' => 'favorited'));
124             $m->connect('favorited', array('action' => 'favorited'));
125
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));
132         }
133
134         // Favorites for API
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',
153                           'id' => '[0-9]+',
154                           'format' => '(xml|json)'));
155         $m->connect('api/favorites/destroy/:id.:format',
156                     array('action' => 'ApiFavoriteDestroy',
157                           'id' => '[0-9]+',
158                           'format' => '(xml|json)'));
159
160         // AtomPub API
161         $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
162                     array('action' => 'AtomPubShowFavorite'),
163                     array('profile' => '[0-9]+',
164                           'notice' => '[0-9]+'));
165
166         $m->connect('api/statusnet/app/favorites/:profile.atom',
167                     array('action' => 'AtomPubFavoriteFeed'),
168                     array('profile' => '[0-9]+'));
169
170         // Required for qvitter API
171         $m->connect('api/statuses/favs/:id.:format',
172                     array('action' => 'ApiStatusesFavs',
173                           'id' => '[0-9]+',
174                           'format' => '(xml|json)'));
175     }
176
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())  
179     {
180         assert($this->isMyActivity($act));
181
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();
185         }
186
187         // We must have an objects[0] here because in isMyActivity we require the count to be == 1
188         $actobj = $act->objects[0];
189
190         $object = Fave::saveActivityObject($actobj, $stored);
191         return $object;
192     }
193
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)
198     {
199         if (!$this->isMyNotice($stored)) {
200             return true;
201         }
202
203         common_debug('Extending activity '.$stored->id.' with '.get_called_class());
204         $this->extendActivity($stored, $act, $scoped);
205         return false;
206     }
207
208     public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
209     {
210         Fave::extendActivity($stored, $act, $scoped);
211     }
212
213     public function activityObjectFromNotice(Notice $notice)
214     {
215         $fave = Fave::fromStored($notice);
216         return $fave->asActivityObject();
217     }
218
219     public function deleteRelated(Notice $notice)
220     {
221         try {
222             $fave = Fave::fromStored($notice);
223             $fave->delete();
224         } catch (NoResultException $e) {
225             // Cool, no problem. We wanted to get rid of it anyway.
226         }
227     }
228
229     // API stuff
230
231     /**
232      * Typically just used to fill out Twitter-compatible API status data.
233      *
234      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
235      */
236     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
237     {
238         if ($scoped instanceof Profile) {
239             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
240         } else {
241             $status['favorited'] = false;
242         }
243         return true;
244     }
245
246     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
247     {
248         $userdata['favourites_count'] = Fave::countByProfile($profile);
249     }
250
251     /**
252      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
253      */
254     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
255     {
256         if ($scoped instanceof Profile) {
257             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
258         }
259         return true;
260     }
261     
262     public function onNoticeDeleteRelated(Notice $notice)
263     {
264         parent::onNoticeDeleteRelated($notice);
265
266         // The below algorithm is because we want to delete fave
267         // activities on any notice which _has_ faves, and not as
268         // in the parent function only ones that _are_ faves.
269
270         $fave = new Fave();
271         $fave->notice_id = $notice->id;
272
273         if ($fave->find()) {
274             while ($fave->fetch()) {
275                 $fave->delete();
276             }
277         }
278
279         $fave->free();
280     }
281
282     public function onUserDeleteRelated(User $user, array &$related)
283     {
284         $fave = new Fave();
285         $fave->user_id = $user->id;
286         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
287
288         Fave::blowCacheForProfileId($user->id);
289         return true;
290     }
291
292     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
293     {
294         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
295         Fave::fillFaves($notice_ids);
296
297         // DB caching
298         if ($scoped instanceof Profile) {
299             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
300         }
301     }
302
303     /**
304      * show the "favorite" form in the notice options element
305      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
306      *
307      * @return void
308      */
309     public function onStartShowNoticeOptionItems($nli)
310     {
311         if (Event::handle('StartShowFaveForm', array($nli))) {
312             $scoped = Profile::current();
313             if ($scoped instanceof Profile) {
314                 if (Fave::existsForProfile($nli->notice, $scoped)) {
315                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
316                     $disfavor->show();
317                 } else {
318                     $favor = new FavorForm($nli->out, $nli->notice);
319                     $favor->show();
320                 }
321             }
322             Event::handle('EndShowFaveForm', array($nli));
323         }
324     }
325
326     public function showNoticeListItem(NoticeListItem $nli)
327     {
328         // pass
329     }
330     public function openNoticeListItemElement(NoticeListItem $nli)
331     {
332         // pass
333     }
334     public function closeNoticeListItemElement(NoticeListItem $nli)
335     {
336         // pass
337     }
338
339     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
340     {
341         $faves = array();
342         $fave = new Fave();
343         $fave->user_id = $uas->getUser()->id;
344
345         if (!empty($uas->after)) {
346             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
347         }
348
349         if ($fave->find()) {
350             while ($fave->fetch()) {
351                 $faves[] = clone($fave);
352             }
353         }
354
355         return $faves;
356     }
357
358     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
359     {
360         if ($nli instanceof ThreadedNoticeListSubItem) {
361             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
362             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
363         } else {
364             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
365         }
366         $threadActive = $item->show() || $threadActive;
367         return true;
368     }
369
370     public function onEndFavorNotice(Profile $actor, Notice $target)
371     {
372         try {
373             $notice_author = $target->getProfile();
374             // Don't notify ourselves of our own favorite on our own notice,
375             // or if it's a remote user (since we don't know their email addresses etc.)
376             if ($notice_author->id == $actor->id || !$notice_author->isLocal()) {
377                 return true;
378             }
379             $local_user = $notice_author->getUser();
380             mail_notify_fave($local_user, $actor, $target);
381         } catch (Exception $e) {
382             // Mm'kay, probably not a local user. Let's skip this favor notification.
383         }
384     }
385
386     /**
387      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
388      * using the class FavCommand.
389      *
390      * @param string  $cmd     Command being run
391      * @param string  $arg     Rest of the message (including address)
392      * @param User    $user    User sending the message
393      * @param Command &$result The resulting command object to be run.
394      *
395      * @return boolean hook value
396      */
397     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
398     {
399         if ($result === false && $cmd == 'fav') {
400             if (empty($arg)) {
401                 $result = null;
402             } else {
403                 list($other, $extra) = CommandInterpreter::split_arg($arg);
404                 if (!empty($extra)) {
405                     $result = null;
406                 } else {
407                     $result = new FavCommand($user, $other);
408                 }
409             }
410             return false;
411         }
412         return true;
413     }
414
415     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
416     {
417         // TRANS: Help message for IM/SMS command "fav <nickname>".
418         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
419         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
420         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
421     }
422
423     /**
424      * Are we allowed to perform a certain command over the API?
425      */
426     public function onCommandSupportedAPI(Command $cmd, &$supported)
427     {
428         $supported = $supported || $cmd instanceof FavCommand;
429     }
430
431     // Form stuff (settings etc.)
432
433     public function onEndEmailFormData(Action $action, Profile $scoped)
434     {
435         // getConfigData will fall back on systemwide default
436         // and we only wish to save numerical true or false.
437         $emailfave = $scoped->getPref('email', 'notify_fave', $this->email_notify_fave) ? 1 : 0;
438
439         $action->elementStart('li');
440         $action->checkbox('email-notify_fave',
441                         // TRANS: Checkbox label in e-mail preferences form.
442                         _('Send me email when someone adds my notice as a favorite.'),
443                         $emailfave);
444         $action->elementEnd('li');
445
446         return true;
447     }
448
449     public function onStartEmailSaveForm(Action $action, Profile $scoped)
450     {
451         $emailfave = $action->boolean('email-notify_fave') ? 1 : 0;
452         try {
453             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
454                 // No need to update setting
455                 return true;
456             }
457         } catch (NoResultException $e) {
458             // Apparently there's no previously stored setting, then continue to save it as it is now.
459         }
460
461         $scoped->setPref('email', 'notify_fave', $emailfave);
462
463         return true;
464     }
465
466     // Layout stuff
467
468     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
469     {
470         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
471                              // TRANS: Menu item in personal group navigation menu.
472                              _m('MENU','Favorites'),
473                              // @todo i18n FIXME: Need to make this two messages.
474                              // TRANS: Menu item title in personal group navigation menu.
475                              // TRANS: %s is a username.
476                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
477                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
478                             'nav_timeline_favorites');
479     }
480
481     public function onEndPublicGroupNav(Menu $menu)
482     {
483         if (!common_config('singleuser', 'enabled')) {
484             // TRANS: Menu item in search group navigation panel.
485             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
486                                  // TRANS: Menu item title in search group navigation panel.
487                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
488         }
489     }
490
491     public function onEndShowSections(Action $action)
492     {
493         if (!$action->isAction(array('all', 'public'))) {
494             return true;
495         }
496
497         if (!common_config('performance', 'high')) {
498             $section = new PopularNoticeSection($action, $action->getScoped());
499             $section->show();
500         }
501     }
502
503     public function onPluginVersion(array &$versions)
504     {
505         $versions[] = array('name' => 'Favorite',
506                             'version' => GNUSOCIAL_VERSION,
507                             'author' => 'Mikael Nordfeldth',
508                             'homepage' => 'http://gnu.io/',
509                             'rawdescription' =>
510                             // TRANS: Plugin description.
511                             _m('Favorites (likes) using ActivityStreams.'));
512
513         return true;
514     }
515 }
516
517 /**
518  * Notify a user that one of their notices has been chosen as a 'fave'
519  *
520  * @param User    $rcpt   The user whose notice was faved
521  * @param Profile $sender The user who faved the notice
522  * @param Notice  $notice The notice that was faved
523  *
524  * @return void
525  */
526 function mail_notify_fave(User $rcpt, Profile $sender, Notice $notice)
527 {
528     if (!$rcpt->receivesEmailNotifications() || !$rcpt->getPref('email', 'notify_fave', $rcpt->email_notify_fave)) {
529         return;
530     }
531
532     // This test is actually "if the sender is sandboxed"
533     if (!$sender->hasRight(Right::EMAILONFAVE)) {
534         return;
535     }
536
537     if ($rcpt->hasBlocked($sender)) {
538         // If the author has blocked us, don't spam them with a notification.
539         return;
540     }
541
542     // We need the global mail.php for various mail related functions below.
543     require_once INSTALLDIR.'/lib/mail.php';
544
545     $bestname = $sender->getBestName();
546
547     common_switch_locale($rcpt->language);
548
549     // TRANS: Subject for favorite notification e-mail.
550     // TRANS: %1$s is the adding user's long name, %2$s is the adding user's nickname.
551     $subject = sprintf(_('%1$s (@%2$s) added your notice as a favorite'), $bestname, $sender->getNickname());
552
553     // TRANS: Body for favorite notification e-mail.
554     // TRANS: %1$s is the adding user's long name, $2$s is the date the notice was created,
555     // TRANS: %3$s is a URL to the faved notice, %4$s is the faved notice text,
556     // TRANS: %5$s is a URL to all faves of the adding user, %6$s is the StatusNet sitename,
557     // TRANS: %7$s is the adding user's nickname.
558     $body = sprintf(_("%1\$s (@%7\$s) just added your notice from %2\$s".
559                       " as one of their favorites.\n\n" .
560                       "The URL of your notice is:\n\n" .
561                       "%3\$s\n\n" .
562                       "The text of your notice is:\n\n" .
563                       "%4\$s\n\n" .
564                       "You can see the list of %1\$s's favorites here:\n\n" .
565                       "%5\$s"),
566                     $bestname,
567                     common_exact_date($notice->created),
568                     common_local_url('shownotice',
569                                      array('notice' => $notice->id)),
570                     $notice->content,
571                     common_local_url('showfavorites',
572                                      array('nickname' => $sender->getNickname())),
573                     common_config('site', 'name'),
574                     $sender->getNickname()) .
575             mail_footer_block();
576
577     $headers = _mail_prepare_headers('fave', $rcpt->getNickname(), $sender->getNickname());
578
579     common_switch_locale();
580     mail_to_user($rcpt, $subject, $body, $headers);
581 }