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