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