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