]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/FavoritePlugin.php
Further column collisions in ReplyNoticeStream
[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 $notify_email_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
191     public function activityObjectFromNotice(Notice $notice)
192     {
193         $fave = Fave::fromStored($notice);
194         return $fave->asActivityObject();
195     }
196
197     public function deleteRelated(Notice $notice)
198     {
199         try {
200             $fave = Fave::fromStored($notice);
201             $fave->delete();
202         } catch (NoResultException $e) {
203             // Cool, no problem. We wanted to get rid of it anyway.
204         }
205     }
206
207     protected function notifyMentioned(Notice $stored, array &$mentioned_ids)
208     {
209         require_once INSTALLDIR.'/lib/mail.php';
210
211         foreach ($mentioned_ids as $id) {
212             $mentioned = User::getKV('id', $id);
213             if ($mentioned instanceof User && $mentioned->id != $stored->profile_id
214                     && $mentioned->email && $mentioned->getPref('email', 'notify_fave', $this->notify_email_fave)) {   // do we have an email, and does user want it?
215                 mail_notify_fave($mentioned, $stored->getProfile(), $stored->getParent());
216             }
217         }
218     }
219
220     // API stuff
221
222     /**
223      * Typically just used to fill out Twitter-compatible API status data.
224      *
225      * FIXME: Make all the calls before this end up with a Notice instead of ArrayWrapper please...
226      */
227     public function onNoticeSimpleStatusArray($notice, array &$status, Profile $scoped=null, array $args=array())
228     {
229         if ($scoped instanceof Profile) {
230             $status['favorited'] = Fave::existsForProfile($notice, $scoped);
231         } else {
232             $status['favorited'] = false;
233         }
234         return true;
235     }
236
237     public function onTwitterUserArray(Profile $profile, array &$userdata, Profile $scoped=null, array $args=array())
238     {
239         $userdata['favourites_count'] = Fave::countByProfile($profile);
240     }
241
242     /**
243      * Typically just used to fill out StatusNet specific data in API calls in the referenced $info array.
244      */
245     public function onStatusNetApiNoticeInfo(Notice $notice, array &$info, Profile $scoped=null, array $args=array())
246     {
247         if ($scoped instanceof Profile) {
248             $info['favorite'] = Fave::existsForProfile($notice, $scoped) ? 'true' : 'false';
249         }
250         return true;
251     }
252     
253     public function onNoticeDeleteRelated(Notice $notice)
254     {
255         parent::onNoticeDeleteRelated($notice);
256
257         // The below algorithm is because we want to delete fave
258         // activities on any notice which _has_ faves, and not as
259         // in the parent function only ones that _are_ faves.
260
261         $fave = new Fave();
262         $fave->notice_id = $notice->id;
263
264         if ($fave->find()) {
265             while ($fave->fetch()) {
266                 $fave->delete();
267             }
268         }
269
270         $fave->free();
271     }
272
273     public function onUserDeleteRelated(User $user, array &$related)
274     {
275         $fave = new Fave();
276         $fave->user_id = $user->id;
277         $fave->delete();    // Will perform a DELETE matching "user_id = {$user->id}"
278
279         Fave::blowCacheForProfileId($user->id);
280         return true;
281     }
282
283     public function onStartNoticeListPrefill(array &$notices, array $notice_ids, Profile $scoped=null)
284     {
285         // prefill array of objects, before pluginfication it was Notice::fillFaves($notices)
286         Fave::fillFaves($notice_ids);
287
288         // DB caching
289         if ($scoped instanceof Profile) {
290             Fave::pivotGet('notice_id', $notice_ids, array('user_id' => $scoped->id));
291         }
292     }
293
294     /**
295      * show the "favorite" form in the notice options element
296      * FIXME: Don't let a NoticeListItemAdapter slip in here (or extend that from NoticeListItem)
297      *
298      * @return void
299      */
300     public function onStartShowNoticeOptionItems($nli)
301     {
302         if (Event::handle('StartShowFaveForm', array($nli))) {
303             $scoped = Profile::current();
304             if ($scoped instanceof Profile) {
305                 if (Fave::existsForProfile($nli->notice, $scoped)) {
306                     $disfavor = new DisfavorForm($nli->out, $nli->notice);
307                     $disfavor->show();
308                 } else {
309                     $favor = new FavorForm($nli->out, $nli->notice);
310                     $favor->show();
311                 }
312             }
313             Event::handle('EndShowFaveForm', array($nli));
314         }
315     }
316
317     public function showNoticeListItem(NoticeListItem $nli)
318     {
319         // pass
320     }
321     public function openNoticeListItemElement(NoticeListItem $nli)
322     {
323         // pass
324     }
325     public function closeNoticeListItemElement(NoticeListItem $nli)
326     {
327         // pass
328     }
329
330     public function onAppendUserActivityStreamObjects(UserActivityStream $uas, array &$objs)
331     {
332         $faves = array();
333         $fave = new Fave();
334         $fave->user_id = $uas->user->id;
335
336         if (!empty($uas->after)) {
337             $fave->whereAdd("modified > '" . common_sql_date($uas->after) . "'");
338         }
339
340         if ($fave->find()) {
341             while ($fave->fetch()) {
342                 $faves[] = clone($fave);
343             }
344         }
345
346         return $faves;
347     }
348
349     public function onStartShowThreadedNoticeTailItems(NoticeListItem $nli, Notice $notice, &$threadActive)
350     {
351         if ($nli instanceof ThreadedNoticeListSubItem) {
352             // The sub-items are replies to a conversation, thus we use different HTML elements etc.
353             $item = new ThreadedNoticeListInlineFavesItem($notice, $nli->out);
354         } else {
355             $item = new ThreadedNoticeListFavesItem($notice, $nli->out);
356         }
357         $threadActive = $item->show() || $threadActive;
358         return true;
359     }
360
361     /**
362      * EndInterpretCommand for FavoritePlugin will handle the 'fav' command
363      * using the class FavCommand.
364      *
365      * @param string  $cmd     Command being run
366      * @param string  $arg     Rest of the message (including address)
367      * @param User    $user    User sending the message
368      * @param Command &$result The resulting command object to be run.
369      *
370      * @return boolean hook value
371      */
372     public function onStartInterpretCommand($cmd, $arg, $user, &$result)
373     {
374         if ($result === false && $cmd == 'fav') {
375             if (empty($arg)) {
376                 $result = null;
377             } else {
378                 list($other, $extra) = $this->split_arg($arg);
379                 if (!empty($extra)) {
380                     $result = null;
381                 } else {
382                     $result = new FavCommand($user, $other);
383                 }
384             }
385             return false;
386         }
387         return true;
388     }
389
390     public function onHelpCommandMessages(HelpCommand $help, array &$commands)
391     {
392         // TRANS: Help message for IM/SMS command "fav <nickname>".
393         $commands['fav <nickname>'] = _m('COMMANDHELP', "add user's last notice as a 'fave'");
394         // TRANS: Help message for IM/SMS command "fav #<notice_id>".
395         $commands['fav #<notice_id>'] = _m('COMMANDHELP', "add notice with the given id as a 'fave'");
396     }
397
398     /**
399      * Are we allowed to perform a certain command over the API?
400      */
401     public function onCommandSupportedAPI(Command $cmd, array &$supported)
402     {
403         $supported = $supported || $cmd instanceof FavCommand;
404     }
405
406     // Form stuff (settings etc.)
407
408     public function onEndEmailFormData(Action $action, Profile $scoped)
409     {
410         // getConfigData will fall back on systemwide default
411         // and we only wish to save numerical true or false.
412         $emailfave = $scoped->getPref('email', 'notify_fave', $this->notify_email_fave) ? 1 : 0;
413
414         $action->elementStart('li');
415         $action->checkbox('email-notify_fave',
416                         // TRANS: Checkbox label in e-mail preferences form.
417                         _('Send me email when someone adds my notice as a favorite.'),
418                         $emailfave);
419         $action->elementEnd('li');
420
421         return true;
422     }
423
424     public function onStartEmailSaveForm(Action $action, Profile $scoped)
425     {
426         $emailfave = $action->boolean('email-notify_fave') ? 1 : 0;
427         try {
428             if ($emailfave == $scoped->getPref('email', 'notify_fave')) {
429                 // No need to update setting
430                 return true;
431             }
432         } catch (NoResultException $e) {
433             // Apparently there's no previously stored setting, then continue to save it as it is now.
434         }
435
436         $scoped->setPref('email', 'notify_fave', $emailfave);
437
438         return true;
439     }
440
441     // Layout stuff
442
443     public function onEndPersonalGroupNav(Menu $menu, Profile $target, Profile $scoped=null)
444     {
445         $menu->out->menuItem(common_local_url('showfavorites', array('nickname' => $target->getNickname())),
446                              // TRANS: Menu item in personal group navigation menu.
447                              _m('MENU','Favorites'),
448                              // @todo i18n FIXME: Need to make this two messages.
449                              // TRANS: Menu item title in personal group navigation menu.
450                              // TRANS: %s is a username.
451                              sprintf(_('%s\'s favorite notices'), $target->getBestName()),
452                              $scoped instanceof Profile && $target->id === $scoped->id && $menu->actionName =='showfavorites',
453                             'nav_timeline_favorites');
454     }
455
456     public function onEndPublicGroupNav(Menu $menu)
457     {
458         if (!common_config('singleuser', 'enabled')) {
459             // TRANS: Menu item in search group navigation panel.
460             $menu->out->menuItem(common_local_url('favorited'), _m('MENU','Popular'),
461                                  // TRANS: Menu item title in search group navigation panel.
462                                  _('Popular notices'), $menu->actionName == 'favorited', 'nav_timeline_favorited');
463         }
464     }
465
466     public function onEndShowSections(Action $action)
467     {
468         if (!$action->isAction(array('all', 'public'))) {
469             return true;
470         }
471
472         if (!common_config('performance', 'high')) {
473             $section = new PopularNoticeSection($action, $action->getScoped());
474             $section->show();
475         }
476     }
477
478     public function onPluginVersion(array &$versions)
479     {
480         $versions[] = array('name' => 'Favorite',
481                             'version' => GNUSOCIAL_VERSION,
482                             'author' => 'Mikael Nordfeldth',
483                             'homepage' => 'http://gnu.io/',
484                             'rawdescription' =>
485                             // TRANS: Plugin description.
486                             _m('Favorites (likes) using ActivityStreams.'));
487
488         return true;
489     }
490 }