Fave.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * Table Definition for fave
  4. */
  5. class Fave extends Managed_DataObject
  6. {
  7. public $__table = 'fave'; // table name
  8. public $notice_id; // int(4) primary_key not_null
  9. public $user_id; // int(4) primary_key not_null
  10. public $uri; // varchar(255)
  11. public $created; // datetime multiple_key not_null
  12. public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
  13. public static function schemaDef()
  14. {
  15. return array(
  16. 'fields' => array(
  17. 'notice_id' => array('type' => 'int', 'not null' => true, 'description' => 'notice that is the favorite'),
  18. 'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user who likes this notice'),
  19. 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
  20. 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
  21. 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
  22. ),
  23. 'primary key' => array('notice_id', 'user_id'),
  24. 'unique keys' => array(
  25. 'fave_uri_key' => array('uri'),
  26. ),
  27. 'foreign keys' => array(
  28. 'fave_notice_id_fkey' => array('notice', array('notice_id' => 'id')),
  29. 'fave_user_id_fkey' => array('profile', array('user_id' => 'id')), // note: formerly referenced notice.id, but we can now record remote users' favorites
  30. ),
  31. 'indexes' => array(
  32. 'fave_notice_id_idx' => array('notice_id'),
  33. 'fave_user_id_idx' => array('user_id', 'modified'),
  34. 'fave_modified_idx' => array('modified'),
  35. ),
  36. );
  37. }
  38. /**
  39. * Save a favorite record.
  40. * @fixme post-author notification should be moved here
  41. *
  42. * @param Profile $actor the local or remote Profile who favorites
  43. * @param Notice $target the notice that is favorited
  44. * @return Fave record on success
  45. * @throws Exception on failure
  46. */
  47. static function addNew(Profile $actor, Notice $target) {
  48. $act = new Activity();
  49. $act->type = ActivityObject::ACTIVITY;
  50. $act->verb = ActivityVerb::FAVORITE;
  51. $act->time = time();
  52. $act->id = self::newUri($actor, $target, common_sql_date($act->time));
  53. $act->title = _("Favor");
  54. // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
  55. // notice's nickname and %3$s is the content of the favorited notice.)
  56. $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
  57. $actor->getNickname(), $target->getProfile()->getNickname(),
  58. $target->rendered ?: $target->content);
  59. $act->actor = $actor->asActivityObject();
  60. $act->target = $target->asActivityObject();
  61. $act->objects = array(clone($act->target));
  62. $url = common_local_url('AtomPubShowFavorite', array('profile'=>$actor->id, 'notice'=>$target->id));
  63. $act->selfLink = $url;
  64. $act->editLink = $url;
  65. // saveActivity will in turn also call Fave::saveActivityObject which does
  66. // what this function used to do before this commit.
  67. $stored = Notice::saveActivity($act, $actor);
  68. return $stored;
  69. }
  70. // exception throwing takeover!
  71. public function insert()
  72. {
  73. if (parent::insert()===false) {
  74. common_log_db_error($this, 'INSERT', __FILE__);
  75. throw new ServerException(sprintf(_m('Could not store new object of type %s'), get_called_class()));
  76. }
  77. self::blowCacheForProfileId($this->user_id);
  78. self::blowCacheForNoticeId($this->notice_id);
  79. return $this;
  80. }
  81. public function delete($useWhere=false)
  82. {
  83. $profile = Profile::getKV('id', $this->user_id);
  84. $notice = Notice::getKV('id', $this->notice_id);
  85. $result = null;
  86. if (Event::handle('StartDisfavorNotice', array($profile, $notice, &$result))) {
  87. $result = parent::delete($useWhere);
  88. self::blowCacheForProfileId($this->user_id);
  89. self::blowCacheForNoticeId($this->notice_id);
  90. self::blow('popular');
  91. if ($result) {
  92. Event::handle('EndDisfavorNotice', array($profile, $notice));
  93. }
  94. }
  95. return $result;
  96. }
  97. function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
  98. {
  99. $stream = new FaveNoticeStream($user_id, $own);
  100. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  101. }
  102. function idStream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
  103. {
  104. $stream = new FaveNoticeStream($user_id, $own);
  105. return $stream->getNoticeIds($offset, $limit, $since_id, $max_id);
  106. }
  107. function asActivity()
  108. {
  109. $target = $this->getTarget();
  110. $actor = $this->getActor();
  111. $act = new Activity();
  112. $act->verb = ActivityVerb::FAVORITE;
  113. // FIXME: rationalize this with URL below
  114. $act->id = $this->getUri();
  115. $act->time = strtotime($this->created);
  116. // TRANS: Activity title when marking a notice as favorite.
  117. $act->title = _("Favor");
  118. // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
  119. // notice's nickname and %3$s is the content of the favorited notice.)
  120. $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
  121. $actor->getNickname(), $target->getProfile()->getNickname(),
  122. $target->rendered ?: $target->content);
  123. $act->actor = $actor->asActivityObject();
  124. $act->target = $target->asActivityObject();
  125. $act->objects = array(clone($act->target));
  126. $url = common_local_url('AtomPubShowFavorite',
  127. array('profile' => $actor->id,
  128. 'notice' => $target->id));
  129. $act->selfLink = $url;
  130. $act->editLink = $url;
  131. return $act;
  132. }
  133. static function existsForProfile($notice, Profile $scoped)
  134. {
  135. $fave = self::pkeyGet(array('user_id'=>$scoped->id, 'notice_id'=>$notice->id));
  136. return ($fave instanceof Fave);
  137. }
  138. /**
  139. * Fetch a stream of favorites by profile
  140. *
  141. * @param integer $profileId Profile that faved
  142. * @param integer $offset Offset from last
  143. * @param integer $limit Number to get
  144. *
  145. * @return mixed stream of faves, use fetch() to iterate
  146. *
  147. * @todo Cache results
  148. * @todo integrate with Fave::stream()
  149. */
  150. static function byProfile($profileId, $offset, $limit)
  151. {
  152. $fav = new Fave();
  153. $fav->user_id = $profileId;
  154. $fav->orderBy('modified DESC');
  155. $fav->limit($offset, $limit);
  156. $fav->find();
  157. return $fav;
  158. }
  159. static function countByProfile(Profile $profile)
  160. {
  161. $c = Cache::instance();
  162. if (!empty($c)) {
  163. $cnt = $c->get(Cache::key('fave:count_by_profile:'.$profile->id));
  164. if (is_integer($cnt)) {
  165. return $cnt;
  166. }
  167. }
  168. $faves = new Fave();
  169. $faves->user_id = $profile->id;
  170. $cnt = (int) $faves->count('notice_id');
  171. if (!empty($c)) {
  172. $c->set(Cache::key('fave:count_by_profile:'.$profile->id), $cnt);
  173. }
  174. return $cnt;
  175. }
  176. static protected $_faves = array();
  177. /**
  178. * All faves of this notice
  179. *
  180. * @param Notice $notice A notice we wish to get faves for (may still be ArrayWrapper)
  181. *
  182. * @return array Array of Fave objects
  183. */
  184. static public function byNotice($notice)
  185. {
  186. if (!isset(self::$_faves[$notice->id])) {
  187. self::fillFaves(array($notice->id));
  188. }
  189. return self::$_faves[$notice->id];
  190. }
  191. static public function fillFaves(array $notice_ids)
  192. {
  193. $faveMap = Fave::listGet('notice_id', $notice_ids);
  194. self::$_faves = array_replace(self::$_faves, $faveMap);
  195. }
  196. static public function blowCacheForProfileId($profile_id)
  197. {
  198. $cache = Cache::instance();
  199. if ($cache) {
  200. // Faves don't happen chronologically, so we need to blow
  201. // ;last cache, too
  202. $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id));
  203. $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id.';last'));
  204. $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id));
  205. $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id.';last'));
  206. $cache->delete(Cache::key('fave:count_by_profile:'.$profile_id));
  207. }
  208. }
  209. static public function blowCacheForNoticeId($notice_id)
  210. {
  211. $cache = Cache::instance();
  212. if ($cache) {
  213. $cache->delete(Cache::key('fave:list-ids:notice_id:'.$notice_id));
  214. }
  215. }
  216. // Remember that we want the _activity_ notice here, not faves applied
  217. // to the supplied Notice (as with byNotice)!
  218. static public function fromStored(Notice $stored)
  219. {
  220. $class = get_called_class();
  221. $object = new $class;
  222. $object->uri = $stored->uri;
  223. if (!$object->find(true)) {
  224. throw new NoResultException($object);
  225. }
  226. return $object;
  227. }
  228. /**
  229. * Retrieves the _targeted_ notice of a verb (such as the notice that was
  230. * _favorited_, but not the favorite activity itself).
  231. *
  232. * @param Notice $stored The activity notice.
  233. *
  234. * @throws NoResultException when it can't find what it's looking for.
  235. */
  236. static public function getTargetFromStored(Notice $stored)
  237. {
  238. return self::fromStored($stored)->getTarget();
  239. }
  240. static public function getObjectType()
  241. {
  242. return 'activity';
  243. }
  244. public function asActivityObject(Profile $scoped=null)
  245. {
  246. $actobj = new ActivityObject();
  247. $actobj->id = $this->getUri();
  248. $actobj->type = ActivityUtils::resolveUri(self::getObjectType());
  249. $actobj->actor = $this->getActorObject();
  250. $actobj->target = $this->getTargetObject();
  251. $actobj->objects = array(clone($actobj->target));
  252. $actobj->verb = ActivityVerb::FAVORITE;
  253. $actobj->title = ActivityUtils::verbToTitle($actobj->verb);
  254. $actobj->content = $this->getTarget()->rendered ?: $this->getTarget()->content;
  255. return $actobj;
  256. }
  257. /**
  258. * @param ActivityObject $actobj The _favored_ notice (which we're "in-reply-to")
  259. * @param Notice $stored The _activity_ notice, i.e. the favor itself.
  260. */
  261. static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
  262. {
  263. $local = ActivityUtils::findLocalObject($actobj->getIdentifiers());
  264. if (!$local instanceof Notice) {
  265. // $local always returns something, but this was not what we expected. Something is wrong.
  266. throw new Exception('Something other than a Notice was returned from findLocalObject');
  267. }
  268. $actor = $stored->getProfile();
  269. $object = new Fave();
  270. $object->user_id = $stored->getProfile()->id;
  271. $object->notice_id = $local->id;
  272. $object->uri = $stored->uri;
  273. $object->created = $stored->created;
  274. $object->modified = $stored->modified;
  275. return $object;
  276. }
  277. static public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
  278. {
  279. $target = self::getTargetFromStored($stored);
  280. // The following logic was copied from StatusNet's Activity plugin
  281. if (ActivityUtils::compareTypes($target->verb, array(ActivityVerb::POST))) {
  282. // "I like the thing you posted"
  283. $act->objects = $target->asActivity()->objects;
  284. } else {
  285. // "I like that you did whatever you did"
  286. $act->target = $target->asActivityObject();
  287. $act->objects = array(clone($act->target));
  288. }
  289. $act->context->replyToID = $target->getUri();
  290. $act->context->replyToUrl = $target->getUrl();
  291. $act->title = ActivityUtils::verbToTitle($act->verb);
  292. }
  293. static function saveActivityObject(ActivityObject $actobj, Notice $stored)
  294. {
  295. $object = self::parseActivityObject($actobj, $stored);
  296. $object->insert(); // exception throwing in Fave's case!
  297. self::blowCacheForProfileId($object->user_id);
  298. self::blowCacheForNoticeId($object->notice_id);
  299. self::blow('popular');
  300. Event::handle('EndFavorNotice', array($stored->getProfile(), $object->getTarget()));
  301. return $object;
  302. }
  303. public function getAttentionArray() {
  304. // not all objects can/should carry attentions, so we don't require extending this
  305. // the format should be an array with URIs to mentioned profiles
  306. return array();
  307. }
  308. public function getTarget()
  309. {
  310. // throws exception on failure
  311. $target = new Notice();
  312. $target->id = $this->notice_id;
  313. if (!$target->find(true)) {
  314. throw new NoResultException($target);
  315. }
  316. return $target;
  317. }
  318. public function getTargetObject()
  319. {
  320. return $this->getTarget()->asActivityObject();
  321. }
  322. protected $_stored = array();
  323. public function getStored()
  324. {
  325. if (!isset($this->_stored[$this->uri])) {
  326. $stored = new Notice();
  327. $stored->uri = $this->uri;
  328. if (!$stored->find(true)) {
  329. throw new NoResultException($stored);
  330. }
  331. $this->_stored[$this->uri] = $stored;
  332. }
  333. return $this->_stored[$this->uri];
  334. }
  335. public function getActor()
  336. {
  337. $profile = new Profile();
  338. $profile->id = $this->user_id;
  339. if (!$profile->find(true)) {
  340. throw new NoResultException($profile);
  341. }
  342. return $profile;
  343. }
  344. public function getActorObject()
  345. {
  346. return $this->getActor()->asActivityObject();
  347. }
  348. public function getUri()
  349. {
  350. if (!empty($this->uri)) {
  351. return $this->uri;
  352. }
  353. // We (should've in this case) created it ourselves, so we tag it ourselves
  354. return self::newUri($this->getActor(), $this->getTarget(), $this->created);
  355. }
  356. static function newUri(Profile $actor, Managed_DataObject $target, $created=null)
  357. {
  358. if (is_null($created)) {
  359. $created = common_sql_now();
  360. }
  361. return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
  362. $actor->id,
  363. ActivityUtils::resolveUri(self::getObjectType(), true),
  364. $target->id,
  365. common_date_iso8601($created));
  366. }
  367. }