]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
6248b332c41d3fd6e5d704b8984d855dc437a661
[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     public function saveNoticeFromActivity(Activity $activity, Profile $actor, array $options=array())
151     {
152     }
153
154     public function activityObjectFromNotice(Notice $notice)
155     {
156     }
157
158     public function deleteRelated(Notice $notice)
159     {
160     }
161
162     // API stuff
163
164     /**
165      * Typically just used to fill out Twitter-compatible API status data.
166      *
167      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
168      */
169     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
170     {
171         if ($scoped instanceof Profile) {
172             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
173         } else {
174             $status['favorited'] = false;
175         }
176         return true;
177     }
178
179     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
180     {
181         $userdata['favourites_count'] = Fave::countByProfile($profile);
182     }
183
184     /**
185      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
186      */
187     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
188     {
189         if ($scoped instanceof Profile) {
190             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
191         }
192         return true;
193     }
194     
195     public function onNoticeDeleteRelated(Notice $notice)
196     {
197         parent::onNoticeDeleteRelated($notice);
198
199         // The below algorithm is because we have faves not stored as
200         // proper activities in Notice from legacy versions of SN/GNU social
201
202         $fave = new Fave();
203         $fave->notice_id = $notice->id;
204
205         if ($fave->find()) {
206             while ($fave->fetch()) {
207                 Fave::blowCacheForProfileId($fave->user_id);
208                 $fave->delete();
209             }
210         }
211
212         $fave->free();
213     }
214
215     public function onUserDeleteRelated(User $user, array &$related)
216     {
217         $fave = new Fave();
218         $fave->user_id = $user->id;
219         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
220
221         Fave::blowCacheForProfileId($user->id);
222         return true;
223     }
224
225     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
226     {
227         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
228         Fave::fillFaves($notice_ids);
229
230         // DB caching
231         if ($scoped instanceof Profile) {
232             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
233         }
234     }
235
236     /**
237      * show the "favorite" form in the notice options element
238      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
239      *
240      * @return void
241      */
242     public function onStartShowNoticeOptionItems($nli)
243     {
244         if (Event::handle('StartShowFaveForm', array($nli))) {
245             $scoped = Profile::current();
246             if ($scoped instanceof Profile) {
247                 if (Fave::existsForProfile($nli->notice, $scoped)) {
248                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
249                     $disfavor->show();
250                 } else {
251                     $favor = new FavorForm($nli->out, $nli->notice);
252                     $favor->show();
253                 }
254             }
255             Event::handle('EndShowFaveForm', array($nli));
256         }
257     }
258
259     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
260     {
261         $faves = array();
262         $fave = new Fave();
263         $fave->user_id = $uas->user->id;
264
265         if (!empty($uas->after)) {
266             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
267         }
268
269         if ($fave->find()) {
270             while ($fave->fetch()) {
271                 $faves[] = clone($fave);
272             }
273         }
274
275         return $faves;
276     }
277
278     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
279     {
280         if ($nli instanceof ThreadedNoticeListSubItem) {
281             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
282             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
283         } else {
284             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
285         }
286         $threadActive = $item->show() || $threadActive;
287         return true;
288     }
289
290     /**
291      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
292      * using the class FavCommand.
293      *
294      * @param string  $cmd     Command being run
295      * @param string  $arg     Rest of the message (including address)
296      * @param User    $user    User sending the message
297      * @param Command &$result The resulting command object to be run.
298      *
299      * @return boolean hook value
300      */
301     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
302     {
303         if ($result === false && $cmd == 'fav') {
304             if (empty($arg)) {
305                 $result = null;
306             } else {
307                 list($other, $extra) = $this->split_arg($arg);
308                 if (!empty($extra)) {
309                     $result = null;
310                 } else {
311                     $result = new FavCommand($user, $other);
312                 }
313             }
314             return false;
315         }
316         return true;
317     }
318
319     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
320     {
321         // TRANS: Help message for IM/SMS command "fav <nickname>".
322         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
323         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
324         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
325     }
326
327     /**
328      * Are we allowed to perform a certain command over the API?
329      */
330     public function onCommandSupportedAPI(Command $cmd, array &$supported)
331     {
332         $supported = $supported || $cmd instanceof FavCommand;
333     }
334
335     // Layout stuff
336
337     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
338     {
339         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
340                              // TRANS: Menu item in personal group navigation menu.
341                              _m('MENU','Favorites'),
342                              // @todo i18n FIXME: Need to make this two messages.
343                              // TRANS: Menu item title in personal group navigation menu.
344                              // TRANS: %s is a username.
345                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
346                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
347                             'nav_timeline_favorites');
348     }
349
350     public function onEndPublicGroupNav(Menu $menu)
351     {
352         if (!common_config('singleuser', 'enabled')) {
353             // TRANS: Menu item in search group navigation panel.
354             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
355                                  // TRANS: Menu item title in search group navigation panel.
356                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
357         }
358     }
359
360     public function onEndShowSections(Action $action)
361     {
362         if (!$action->isAction(array('all', 'public'))) {
363             return true;
364         }
365
366         if (!common_config('performance', 'high')) {
367             $section = new PopularNoticeSection($action, $action->getScoped());
368             $section->show();
369         }
370     }
371
372     public function onPluginVersion(array &$versions)
373     {
374         $versions[] = array('name' => 'Favorite',
375                             'version' => GNUSOCIAL_VERSION,
376                             'author' => 'Mikael Nordfeldth',
377                             'homepage' => 'http://gnu.io/',
378                             'rawdescription' =>
379                             // TRANS: Plugin description.
380                             _m('Favorites (likes) using ActivityStreams.'));
381
382         return true;
383     }
384 }