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