]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
Don't send favorite notifications unless the user wants it.
[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     public function tag()
29     {
30         return 'favorite';
31     }
32
33     public function types()
34     {
35         return array();
36     }
37
38     public function verbs()
39     {
40         return array(ActivityVerb::FAVORITE);
41     }
42     
43     public function onCheckSchema()
44     {
45         $schema = Schema::get();
46         $schema->ensureTable('fave', Fave::schemaDef());
47         return true;
48     }
49     
50     public function onEndUpgrade()
51     {
52         printfnq("Ensuring all faves have a URI...");
53     
54         $fave = new Fave();
55         $fave->whereAdd('uri IS NULL');
56     
57         if ($fave->find()) {
58             while ($fave->fetch()) {
59                 try {
60                     $fave->decache();
61                     $fave->query(sprintf('UPDATE fave '.
62                                          'SET uri = "%s", '.
63                                          '    modified = "%s" '.
64                                          'WHERE user_id = %d '.
65                                          'AND notice_id = %d',
66                                          Fave::newUri($fave->user_id, $fave->notice_id, $fave->modified),
67                                          common_sql_date(strtotime($fave->modified)),
68                                          $fave->user_id,
69                                          $fave->notice_id));
70                 } catch (Exception $e) {
71                     common_log(LOG_ERR, "Error updating fave URI: " . $e->getMessage());
72                 }
73             }
74         }
75     
76         printfnq("DONE.\n");
77     }
78
79     public function onRouterInitialized(URLMapper $m)
80     {
81         // Web UI actions
82         $m->connect('main/favor', array('action' => 'favor'));
83         $m->connect('main/disfavor', array('action' => 'disfavor'));
84
85         if (common_config('singleuser', 'enabled')) {
86             $nickname = User::singleUserNickname();
87
88             $m->connect('favorites',
89                         array('action' => 'showfavorites',
90                               'nickname' => $nickname));
91             $m->connect('favoritesrss',
92                         array('action' => 'favoritesrss',
93                               'nickname' => $nickname));
94         } else {
95             $m->connect('favoritedrss', array('action' => 'favoritedrss'));
96             $m->connect('favorited/', array('action' => 'favorited'));
97             $m->connect('favorited', array('action' => 'favorited'));
98
99             $m->connect(':nickname/favorites',
100                         array('action' => 'showfavorites'),
101                         array('nickname' => Nickname::DISPLAY_FMT));
102             $m->connect(':nickname/favorites/rss',
103                         array('action' => 'favoritesrss'),
104                         array('nickname' => Nickname::DISPLAY_FMT));
105         }
106
107         // Favorites for API
108         $m->connect('api/favorites/create.:format',
109                     array('action' => 'ApiFavoriteCreate',
110                           'format' => '(xml|json)'));
111         $m->connect('api/favorites/destroy.:format',
112                     array('action' => 'ApiFavoriteDestroy',
113                           'format' => '(xml|json)'));
114         $m->connect('api/favorites/list.:format',
115                     array('action' => 'ApiTimelineFavorites',
116                           'format' => '(xml|json|rss|atom|as)'));
117         $m->connect('api/favorites/:id.:format',
118                     array('action' => 'ApiTimelineFavorites',
119                           'id' => Nickname::INPUT_FMT,
120                           'format' => '(xml|json|rss|atom|as)'));
121         $m->connect('api/favorites.:format',
122                     array('action' => 'ApiTimelineFavorites',
123                           'format' => '(xml|json|rss|atom|as)'));
124         $m->connect('api/favorites/create/:id.:format',
125                     array('action' => 'ApiFavoriteCreate',
126                           'id' => '[0-9]+',
127                           'format' => '(xml|json)'));
128         $m->connect('api/favorites/destroy/:id.:format',
129                     array('action' => 'ApiFavoriteDestroy',
130                           'id' => '[0-9]+',
131                           'format' => '(xml|json)'));
132
133         // AtomPub API
134         $m->connect('api/statusnet/app/favorites/:profile/:notice.atom',
135                     array('action' => 'AtomPubShowFavorite'),
136                     array('profile' => '[0-9]+',
137                           'notice' => '[0-9]+'));
138
139         $m->connect('api/statusnet/app/favorites/:profile.atom',
140                     array('action' => 'AtomPubFavoriteFeed'),
141                     array('profile' => '[0-9]+'));
142
143         // Required for qvitter API
144         $m->connect('api/statuses/favs/:id.:format',
145                     array('action' => 'ApiStatusesFavs',
146                           'id' => '[0-9]+',
147                           'format' => '(xml|json)'));
148     }
149
150     // FIXME: Set this to abstract public in lib/activityhandlerplugin.php ddwhen all plugins have migrated!
151     protected function saveObjectFromActivity(Activity $act, Notice $stored, array $options=array())  
152     {
153         assert($this->isMyActivity($act));
154
155         // If empty, we should've created it ourselves on our node.
156         if (!isset($options['created'])) {
157             $options['created'] = !empty($act->time) ? common_sql_date($act->time) : common_sql_now();
158         }
159         if (!isset($options['uri'])) {
160             $options['uri'] = !empty($act->id) ? $act->id : $act->selfLink;
161         }
162
163         // We must have an objects[0] here because in isMyActivity we require the count to be == 1
164         $actobj = $act->objects[0];
165
166         try {
167             $object = Fave::saveActivityObject($actobj, $stored);
168         } catch (ServerException $e) {
169             // Probably that the favored notice doesn't exist in our local database
170             // but may also be some missing profile or so, which we could catch in a
171             // more explicit catch-statement.
172             return null;
173         }
174         return $object;
175     }
176
177
178     public function activityObjectFromNotice(Notice $notice)
179     {
180         $fave = Fave::fromStored($notice);
181         return $fave->asActivityObject();
182     }
183
184     public function deleteRelated(Notice $notice)
185     {
186         try {
187             $fave = Fave::fromStored($notice);
188             $fave->delete();
189         } catch (NoResultException $e) {
190             // Cool, no problem. We wanted to get rid of it anyway.
191         }
192     }
193
194     protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
195     {
196         require_once INSTALLDIR.'/lib/mail.php';
197
198         foreach ($mentioned_ids as $id) {
199             $mentioned = User::getKV('id', $id);
200             if ($mentioned instanceof User && $mentioned->id != $stored->profile_id
201                     && $mentioned->email && $mentioned->emailnotifyfav) {   // do we have an email, and does user want it?
202                 mail_notify_fave($mentioned, $stored->getProfile(), $stored->getParent());
203             }
204         }
205     }
206
207     // API stuff
208
209     /**
210      * Typically just used to fill out Twitter-compatible API status data.
211      *
212      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
213      */
214     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
215     {
216         if ($scoped instanceof Profile) {
217             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
218         } else {
219             $status['favorited'] = false;
220         }
221         return true;
222     }
223
224     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
225     {
226         $userdata['favourites_count'] = Fave::countByProfile($profile);
227     }
228
229     /**
230      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
231      */
232     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
233     {
234         if ($scoped instanceof Profile) {
235             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
236         }
237         return true;
238     }
239     
240     public function onNoticeDeleteRelated(Notice $notice)
241     {
242         parent::onNoticeDeleteRelated($notice);
243
244         // The below algorithm is because we want to delete fave
245         // activities on any notice which _has_ faves, and not as
246         // in the parent function only ones that _are_ faves.
247
248         $fave = new Fave();
249         $fave->notice_id = $notice->id;
250
251         if ($fave->find()) {
252             while ($fave->fetch()) {
253                 $fave->delete();
254             }
255         }
256
257         $fave->free();
258     }
259
260     public function onUserDeleteRelated(User $user, array &$related)
261     {
262         $fave = new Fave();
263         $fave->user_id = $user->id;
264         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
265
266         Fave::blowCacheForProfileId($user->id);
267         return true;
268     }
269
270     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
271     {
272         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
273         Fave::fillFaves($notice_ids);
274
275         // DB caching
276         if ($scoped instanceof Profile) {
277             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
278         }
279     }
280
281     /**
282      * show the "favorite" form in the notice options element
283      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
284      *
285      * @return void
286      */
287     public function onStartShowNoticeOptionItems($nli)
288     {
289         if (Event::handle('StartShowFaveForm', array($nli))) {
290             $scoped = Profile::current();
291             if ($scoped instanceof Profile) {
292                 if (Fave::existsForProfile($nli->notice, $scoped)) {
293                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
294                     $disfavor->show();
295                 } else {
296                     $favor = new FavorForm($nli->out, $nli->notice);
297                     $favor->show();
298                 }
299             }
300             Event::handle('EndShowFaveForm', array($nli));
301         }
302     }
303
304     public function showNoticeListItem(NoticeListItem $nli)
305     {
306         // pass
307     }
308     public function openNoticeListItemElement(NoticeListItem $nli)
309     {
310         // pass
311     }
312     public function closeNoticeListItemElement(NoticeListItem $nli)
313     {
314         // pass
315     }
316
317     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
318     {
319         $faves = array();
320         $fave = new Fave();
321         $fave->user_id = $uas->user->id;
322
323         if (!empty($uas->after)) {
324             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
325         }
326
327         if ($fave->find()) {
328             while ($fave->fetch()) {
329                 $faves[] = clone($fave);
330             }
331         }
332
333         return $faves;
334     }
335
336     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
337     {
338         if ($nli instanceof ThreadedNoticeListSubItem) {
339             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
340             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
341         } else {
342             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
343         }
344         $threadActive = $item->show() || $threadActive;
345         return true;
346     }
347
348     /**
349      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
350      * using the class FavCommand.
351      *
352      * @param string  $cmd     Command being run
353      * @param string  $arg     Rest of the message (including address)
354      * @param User    $user    User sending the message
355      * @param Command &$result The resulting command object to be run.
356      *
357      * @return boolean hook value
358      */
359     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
360     {
361         if ($result === false && $cmd == 'fav') {
362             if (empty($arg)) {
363                 $result = null;
364             } else {
365                 list($other, $extra) = $this->split_arg($arg);
366                 if (!empty($extra)) {
367                     $result = null;
368                 } else {
369                     $result = new FavCommand($user, $other);
370                 }
371             }
372             return false;
373         }
374         return true;
375     }
376
377     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
378     {
379         // TRANS: Help message for IM/SMS command "fav <nickname>".
380         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
381         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
382         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
383     }
384
385     /**
386      * Are we allowed to perform a certain command over the API?
387      */
388     public function onCommandSupportedAPI(Command $cmd, array &$supported)
389     {
390         $supported = $supported || $cmd instanceof FavCommand;
391     }
392
393     // Layout stuff
394
395     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
396     {
397         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
398                              // TRANS: Menu item in personal group navigation menu.
399                              _m('MENU','Favorites'),
400                              // @todo i18n FIXME: Need to make this two messages.
401                              // TRANS: Menu item title in personal group navigation menu.
402                              // TRANS: %s is a username.
403                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
404                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
405                             'nav_timeline_favorites');
406     }
407
408     public function onEndPublicGroupNav(Menu $menu)
409     {
410         if (!common_config('singleuser', 'enabled')) {
411             // TRANS: Menu item in search group navigation panel.
412             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
413                                  // TRANS: Menu item title in search group navigation panel.
414                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
415         }
416     }
417
418     public function onEndShowSections(Action $action)
419     {
420         if (!$action->isAction(array('all', 'public'))) {
421             return true;
422         }
423
424         if (!common_config('performance', 'high')) {
425             $section = new PopularNoticeSection($action, $action->getScoped());
426             $section->show();
427         }
428     }
429
430     public function onPluginVersion(array &$versions)
431     {
432         $versions[] = array('name' => 'Favorite',
433                             'version' => GNUSOCIAL_VERSION,
434                             'author' => 'Mikael Nordfeldth',
435                             'homepage' => 'http://gnu.io/',
436                             'rawdescription' =>
437                             // TRANS: Plugin description.
438                             _m('Favorites (likes) using ActivityStreams.'));
439
440         return true;
441     }
442 }