FavoritePlugin.php 21 KB

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