PageRenderTime 62ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/Bookmark/BookmarkPlugin.php

https://gitlab.com/windigo-gs/windigos-gnu-social
PHP | 546 lines | 291 code | 88 blank | 167 comment | 35 complexity | 1a9df2784a02300cf5af501f33817cd7 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, GPL-2.0
  1. <?php
  2. /**
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2010, StatusNet, Inc.
  5. *
  6. * A plugin to enable social-bookmarking functionality
  7. *
  8. * PHP version 5
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as published by
  12. * the Free Software Foundation, either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. * @category SocialBookmark
  24. * @package StatusNet
  25. * @author Evan Prodromou <evan@status.net>
  26. * @copyright 2010 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('STATUSNET')) {
  31. exit(1);
  32. }
  33. /**
  34. * Bookmark plugin main class
  35. *
  36. * @category Bookmark
  37. * @package StatusNet
  38. * @author Brion Vibber <brionv@status.net>
  39. * @author Evan Prodromou <evan@status.net>
  40. * @copyright 2010 StatusNet, Inc.
  41. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
  42. * @link http://status.net/
  43. */
  44. class BookmarkPlugin extends MicroAppPlugin
  45. {
  46. const VERSION = '0.1';
  47. const IMPORTDELICIOUS = 'BookmarkPlugin:IMPORTDELICIOUS';
  48. /**
  49. * Authorization for importing delicious bookmarks
  50. *
  51. * By default, everyone can import bookmarks except silenced people.
  52. *
  53. * @param Profile $profile Person whose rights to check
  54. * @param string $right Right to check; const value
  55. * @param boolean &$result Result of the check, writeable
  56. *
  57. * @return boolean hook value
  58. */
  59. function onUserRightsCheck($profile, $right, &$result)
  60. {
  61. if ($right == self::IMPORTDELICIOUS) {
  62. $result = !$profile->isSilenced();
  63. return false;
  64. }
  65. return true;
  66. }
  67. /**
  68. * Database schema setup
  69. *
  70. * @see Schema
  71. * @see ColumnDef
  72. *
  73. * @return boolean hook value; true means continue processing, false means stop.
  74. */
  75. function onCheckSchema()
  76. {
  77. $schema = Schema::get();
  78. $schema->ensureTable('bookmark', Bookmark::schemaDef());
  79. return true;
  80. }
  81. /**
  82. * Show the CSS necessary for this plugin
  83. *
  84. * @param Action $action the action being run
  85. *
  86. * @return boolean hook value
  87. */
  88. function onEndShowStyles($action)
  89. {
  90. $action->cssLink($this->path('bookmark.css'));
  91. return true;
  92. }
  93. function onEndShowScripts($action)
  94. {
  95. $action->script($this->path('js/bookmark.js'));
  96. return true;
  97. }
  98. /**
  99. * Map URLs to actions
  100. *
  101. * @param Net_URL_Mapper $m path-to-action mapper
  102. *
  103. * @return boolean hook value; true means continue processing, false means stop.
  104. */
  105. function onRouterInitialized($m)
  106. {
  107. if (common_config('singleuser', 'enabled')) {
  108. $nickname = User::singleUserNickname();
  109. $m->connect('bookmarks',
  110. array('action' => 'bookmarks', 'nickname' => $nickname));
  111. $m->connect('bookmarks/rss',
  112. array('action' => 'bookmarksrss', 'nickname' => $nickname));
  113. } else {
  114. $m->connect(':nickname/bookmarks',
  115. array('action' => 'bookmarks'),
  116. array('nickname' => Nickname::DISPLAY_FMT));
  117. $m->connect(':nickname/bookmarks/rss',
  118. array('action' => 'bookmarksrss'),
  119. array('nickname' => Nickname::DISPLAY_FMT));
  120. }
  121. $m->connect('api/bookmarks/:id.:format',
  122. array('action' => 'ApiTimelineBookmarks',
  123. 'id' => Nickname::INPUT_FMT,
  124. 'format' => '(xml|json|rss|atom|as)'));
  125. $m->connect('main/bookmark/new',
  126. array('action' => 'newbookmark'),
  127. array('id' => '[0-9]+'));
  128. $m->connect('main/bookmark/popup',
  129. array('action' => 'bookmarkpopup'));
  130. $m->connect('main/bookmark/import',
  131. array('action' => 'importdelicious'));
  132. $m->connect('main/bookmark/forurl',
  133. array('action' => 'bookmarkforurl'));
  134. $m->connect('bookmark/:id',
  135. array('action' => 'showbookmark'),
  136. array('id' => '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'));
  137. $m->connect('notice/by-url/:id',
  138. array('action' => 'noticebyurl'),
  139. array('id' => '[0-9]+'));
  140. return true;
  141. }
  142. /**
  143. * Add our two queue handlers to the queue manager
  144. *
  145. * @param QueueManager $qm current queue manager
  146. *
  147. * @return boolean hook value
  148. */
  149. function onEndInitializeQueueManager($qm)
  150. {
  151. $qm->connect('dlcsback', 'DeliciousBackupImporter');
  152. $qm->connect('dlcsbkmk', 'DeliciousBookmarkImporter');
  153. return true;
  154. }
  155. /**
  156. * Plugin version data
  157. *
  158. * @param array &$versions array of version data
  159. *
  160. * @return value
  161. */
  162. function onPluginVersion(&$versions)
  163. {
  164. $versions[] = array('name' => 'Bookmark',
  165. 'version' => self::VERSION,
  166. 'author' => 'Evan Prodromou, Stephane Berube, Jean Baptiste Favre',
  167. 'homepage' => 'http://status.net/wiki/Plugin:Bookmark',
  168. 'description' =>
  169. // TRANS: Plugin description.
  170. _m('Simple extension for supporting bookmarks. ') .
  171. 'BookmarkList feature has been developped by Stephane Berube. ' .
  172. 'Integration has been done by Jean Baptiste Favre.');
  173. return true;
  174. }
  175. /**
  176. * Load our document if requested
  177. *
  178. * @param string &$title Title to fetch
  179. * @param string &$output HTML to output
  180. *
  181. * @return boolean hook value
  182. */
  183. function onStartLoadDoc(&$title, &$output)
  184. {
  185. if ($title == 'bookmarklet') {
  186. $filename = INSTALLDIR.'/plugins/Bookmark/bookmarklet';
  187. $c = file_get_contents($filename);
  188. $output = common_markup_to_html($c);
  189. return false; // success!
  190. }
  191. return true;
  192. }
  193. /**
  194. * Show a link to our delicious import page on profile settings form
  195. *
  196. * @param Action $action Profile settings action being shown
  197. *
  198. * @return boolean hook value
  199. */
  200. function onEndProfileSettingsActions($action)
  201. {
  202. $user = common_current_user();
  203. if (!empty($user) && $user->hasRight(self::IMPORTDELICIOUS)) {
  204. $action->elementStart('li');
  205. $action->element('a',
  206. array('href' => common_local_url('importdelicious')),
  207. // TRANS: Link text in proile leading to import form.
  208. _m('Import del.icio.us bookmarks'));
  209. $action->elementEnd('li');
  210. }
  211. return true;
  212. }
  213. /**
  214. * Output our CSS class for bookmark notice list elements
  215. *
  216. * @param NoticeListItem $nli The item being shown
  217. *
  218. * @return boolean hook value
  219. */
  220. function onStartOpenNoticeListItemElement($nli)
  221. {
  222. if (!$this->isMyNotice($nli->notice)) {
  223. return true;
  224. }
  225. $nb = Bookmark::getByNotice($nli->notice);
  226. if (empty($nb)) {
  227. $this->log(LOG_INFO, "Notice {$nli->notice->id} has bookmark class but no matching Bookmark record.");
  228. return true;
  229. }
  230. $id = (empty($nli->repeat)) ? $nli->notice->id : $nli->repeat->id;
  231. $class = 'hentry notice bookmark';
  232. if ($nli->notice->scope != 0 && $nli->notice->scope != 1) {
  233. $class .= ' limited-scope';
  234. }
  235. $nli->out->elementStart('li', array('class' => $class,
  236. 'id' => 'notice-' . $id));
  237. Event::handle('EndOpenNoticeListItemElement', array($nli));
  238. return false;
  239. }
  240. /**
  241. * Modify the default menu to link to our custom action
  242. *
  243. * Using event handlers, it's possible to modify the default UI for pages
  244. * almost without limit. In this method, we add a menu item to the default
  245. * primary menu for the interface to link to our action.
  246. *
  247. * The Action class provides a rich set of events to hook, as well as output
  248. * methods.
  249. *
  250. * @param Action $action The current action handler. Use this to
  251. * do any output.
  252. *
  253. * @return boolean hook value; true means continue processing, false means stop.
  254. *
  255. * @see Action
  256. */
  257. function onEndPersonalGroupNav($action)
  258. {
  259. $this->user = common_current_user();
  260. if (!$this->user) {
  261. // TRANS: Client error displayed when trying to display bookmarks for a non-existing user.
  262. $this->clientError(_('No such user.'));
  263. }
  264. $action->menuItem(common_local_url('bookmarks', array('nickname' => $this->user->nickname)),
  265. // TRANS: Menu item in sample plugin.
  266. _m('Bookmarks'),
  267. // TRANS: Menu item title in sample plugin.
  268. _m('A list of your bookmarks'), false, 'nav_timeline_bookmarks');
  269. return true;
  270. }
  271. function types()
  272. {
  273. return array(ActivityObject::BOOKMARK);
  274. }
  275. /**
  276. * When a notice is deleted, delete the related Bookmark
  277. *
  278. * @param Notice $notice Notice being deleted
  279. *
  280. * @return boolean hook value
  281. */
  282. function deleteRelated($notice)
  283. {
  284. if ($this->isMyNotice($notice)) {
  285. $nb = Bookmark::getByNotice($notice);
  286. if (!empty($nb)) {
  287. $nb->delete();
  288. }
  289. }
  290. return true;
  291. }
  292. /**
  293. * Save a bookmark from an activity
  294. *
  295. * @param Activity $activity Activity to save
  296. * @param Profile $profile Profile to use as author
  297. * @param array $options Options to pass to bookmark-saving code
  298. *
  299. * @return Notice resulting notice
  300. */
  301. function saveNoticeFromActivity($activity, $profile, $options=array())
  302. {
  303. $bookmark = $activity->objects[0];
  304. $relLinkEls = ActivityUtils::getLinks($bookmark->element, 'related');
  305. if (count($relLinkEls) < 1) {
  306. // TRANS: Client exception thrown when a bookmark is formatted incorrectly.
  307. throw new ClientException(_m('Expected exactly 1 link '.
  308. 'rel=related in a Bookmark.'));
  309. }
  310. if (count($relLinkEls) > 1) {
  311. common_log(LOG_WARNING,
  312. "Got too many link rel=related in a Bookmark.");
  313. }
  314. $linkEl = $relLinkEls[0];
  315. $url = $linkEl->getAttribute('href');
  316. $tags = array();
  317. foreach ($activity->categories as $category) {
  318. $tags[] = common_canonical_tag($category->term);
  319. }
  320. if (!empty($activity->time)) {
  321. $options['created'] = common_sql_date($activity->time);
  322. }
  323. // Fill in location if available
  324. $location = $activity->context->location;
  325. if ($location) {
  326. $options['lat'] = $location->lat;
  327. $options['lon'] = $location->lon;
  328. if ($location->location_id) {
  329. $options['location_ns'] = $location->location_ns;
  330. $options['location_id'] = $location->location_id;
  331. }
  332. }
  333. $options['groups'] = array();
  334. $options['replies'] = array(); // TODO: context->attention
  335. foreach ($activity->context->attention as $attnUrl=>$type) {
  336. try {
  337. $other = Profile::fromUri($attnUrl);
  338. if ($other->isGroup()) {
  339. $options['groups'][] = $other->id;
  340. } else {
  341. $options['replies'][] = $attnUrl;
  342. }
  343. } catch (UnknownUriException $e) {
  344. // We simply don't know this URI, despite lookup attempts.
  345. }
  346. }
  347. // Maintain direct reply associations
  348. // @fixme what about conversation ID?
  349. if (!empty($activity->context->replyToID)) {
  350. $orig = Notice::getKV('uri',
  351. $activity->context->replyToID);
  352. if (!empty($orig)) {
  353. $options['reply_to'] = $orig->id;
  354. }
  355. }
  356. return Bookmark::saveNew($profile,
  357. $bookmark->title,
  358. $url,
  359. $tags,
  360. $bookmark->summary,
  361. $options);
  362. }
  363. function activityObjectFromNotice($notice)
  364. {
  365. assert($this->isMyNotice($notice));
  366. common_log(LOG_INFO,
  367. "Formatting notice {$notice->uri} as a bookmark.");
  368. $object = new ActivityObject();
  369. $nb = Bookmark::getByNotice($notice);
  370. $object->id = $notice->uri;
  371. $object->type = ActivityObject::BOOKMARK;
  372. $object->title = $nb->title;
  373. $object->summary = $nb->description;
  374. $object->link = $notice->getUrl();
  375. // Attributes of the URL
  376. $attachments = $notice->attachments();
  377. if (count($attachments) != 1) {
  378. // TRANS: Server exception thrown when a bookmark has multiple attachments.
  379. throw new ServerException(_m('Bookmark notice with the '.
  380. 'wrong number of attachments.'));
  381. }
  382. $target = $attachments[0];
  383. $attrs = array('rel' => 'related',
  384. 'href' => $target->url);
  385. if (!empty($target->title)) {
  386. $attrs['title'] = $target->title;
  387. }
  388. $object->extra[] = array('link', $attrs, null);
  389. // Attributes of the thumbnail, if any
  390. try {
  391. $thumbnail = $target->getThumbnail();
  392. $tattrs = array('rel' => 'preview',
  393. 'href' => $thumbnail->url);
  394. if (!empty($thumbnail->width)) {
  395. $tattrs['media:width'] = $thumbnail->width;
  396. }
  397. if (!empty($thumbnail->height)) {
  398. $tattrs['media:height'] = $thumbnail->height;
  399. }
  400. $object->extra[] = array('link', $tattrs, null);
  401. } catch (UnsupportedMediaException $e) {
  402. // No image thumbnail metadata available
  403. }
  404. return $object;
  405. }
  406. /**
  407. * Given a notice list item, returns an adapter specific
  408. * to this plugin.
  409. *
  410. * @param NoticeListItem $nli item to adapt
  411. *
  412. * @return NoticeListItemAdapter adapter or null
  413. */
  414. function adaptNoticeListItem($nli)
  415. {
  416. return new BookmarkListItem($nli);
  417. }
  418. function entryForm($out)
  419. {
  420. return new InitialBookmarkForm($out);
  421. }
  422. function tag()
  423. {
  424. return 'bookmark';
  425. }
  426. function appTitle()
  427. {
  428. // TRANS: Application title.
  429. return _m('TITLE','Bookmark');
  430. }
  431. function onEndUpgrade()
  432. {
  433. // Version 0.9.x of the plugin didn't stamp notices
  434. // with verb and object-type (for obvious reasons). Update
  435. // those notices here.
  436. $notice = new Notice();
  437. $notice->whereAdd('exists (select uri from bookmark where bookmark.uri = notice.uri)');
  438. $notice->whereAdd('((object_type is null) or (object_type = "' .ActivityObject::NOTE.'"))');
  439. $notice->find();
  440. while ($notice->fetch()) {
  441. $original = clone($notice);
  442. $notice->verb = ActivityVerb::POST;
  443. $notice->object_type = ActivityObject::BOOKMARK;
  444. $notice->update($original);
  445. }
  446. }
  447. public function activityObjectOutputJson(ActivityObject $obj, array &$out)
  448. {
  449. assert($obj->type == ActivityObject::BOOKMARK);
  450. $bm = Bookmark::getKV('uri', $obj->id);
  451. if (empty($bm)) {
  452. throw new ServerException("Unknown bookmark: " . $obj->id);
  453. }
  454. $out['displayName'] = $bm->title;
  455. $out['targetUrl'] = $bm->url;
  456. return true;
  457. }
  458. }