3 * Table Definition for fave
6 class Fave extends Managed_DataObject
8 public $__table = 'fave'; // table name
9 public $notice_id; // int(4) primary_key not_null
10 public $user_id; // int(4) primary_key not_null
11 public $uri; // varchar(191) not 255 because utf8mb4 takes more space not 255 because utf8mb4 takes more space
12 public $created; // datetime multiple_key not_null
13 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
15 public static function schemaDef()
19 'notice_id' => array('type' => 'int', 'not null' => true, 'description' => 'notice that is the favorite'),
20 'user_id' => array('type' => 'int', 'not null' => true, 'description' => 'user who likes this notice'),
21 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier, usually a tag URI'),
22 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
23 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
25 'primary key' => array('notice_id', 'user_id'),
26 'unique keys' => array(
27 'fave_uri_key' => array('uri'),
29 'foreign keys' => array(
30 'fave_notice_id_fkey' => array('notice', array('notice_id' => 'id')),
31 'fave_user_id_fkey' => array('profile', array('user_id' => 'id')), // note: formerly referenced notice.id, but we can now record remote users' favorites
34 'fave_notice_id_idx' => array('notice_id'),
35 'fave_user_id_idx' => array('user_id', 'modified'),
36 'fave_modified_idx' => array('modified'),
42 * Save a favorite record.
43 * @fixme post-author notification should be moved here
45 * @param Profile $actor the local or remote Profile who favorites
46 * @param Notice $target the notice that is favorited
47 * @return Fave record on success
48 * @throws Exception on failure
50 static function addNew(Profile $actor, Notice $target) {
51 if (self::existsForProfile($target, $actor)) {
52 // TRANS: Client error displayed when trying to mark a notice as favorite that already is a favorite.
53 throw new AlreadyFulfilledException(_('You have already favorited this!'));
56 $act = new Activity();
57 $act->type = ActivityObject::ACTIVITY;
58 $act->verb = ActivityVerb::FAVORITE;
60 $act->id = self::newUri($actor, $target, common_sql_date($act->time));
61 $act->title = _("Favor");
62 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
63 // notice's nickname and %3$s is the content of the favorited notice.)
64 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
65 $actor->getNickname(), $target->getProfile()->getNickname(),
66 $target->getRendered());
67 $act->actor = $actor->asActivityObject();
68 $act->target = $target->asActivityObject();
69 $act->objects = array(clone($act->target));
71 $url = common_local_url('AtomPubShowFavorite', array('profile'=>$actor->id, 'notice'=>$target->id));
72 $act->selfLink = $url;
73 $act->editLink = $url;
75 // saveActivity will in turn also call Fave::saveActivityObject which does
76 // what this function used to do before this commit.
77 $stored = Notice::saveActivity($act, $actor);
82 static function removeEntry(Profile $actor, Notice $target)
85 $fave->user_id = $actor->getID();
86 $fave->notice_id = $target->getID();
87 if (!$fave->find(true)) {
88 // TRANS: Client error displayed when trying to remove a 'favor' when there is none in the first place.
89 throw new AlreadyFulfilledException(_('This is already not favorited.'));
92 $result = $fave->delete();
93 if ($result === false) {
94 common_log_db_error($fave, 'DELETE', __FILE__);
95 // TRANS: Server error displayed when removing a favorite from the database fails.
96 throw new ServerException(_('Could not delete favorite.'));
99 Fave::blowCacheForProfileId($actor->getID());
100 Fave::blowCacheForNoticeId($target->getID());
103 // exception throwing takeover!
104 public function insert()
106 if (parent::insert()===false) {
107 common_log_db_error($this, 'INSERT', __FILE__);
108 throw new ServerException(sprintf(_m('Could not store new object of type %s'), get_called_class()));
110 self::blowCacheForProfileId($this->user_id);
111 self::blowCacheForNoticeId($this->notice_id);
115 public function delete($useWhere=false)
120 $profile = $this->getActor();
121 $notice = $this->getTarget();
123 if (Event::handle('StartDisfavorNotice', array($profile, $notice, &$result))) {
125 $result = parent::delete($useWhere);
127 if ($result !== false) {
128 Event::handle('EndDisfavorNotice', array($profile, $notice));
132 } catch (NoResultException $e) {
133 // In case there's some inconsistency where the profile or notice was deleted without losing the fave db entry
134 common_log(LOG_INFO, '"'.get_class($e->obj).'" with id=='.var_export($e->obj->id, true).' object not found when deleting favorite, ignoring...');
135 } catch (EmptyPkeyValueException $e) {
136 // Some buggy instances of GNU social have had favorites with notice id==0 stored in the database
137 common_log(LOG_INFO, _ve($e->getMessage()));
140 // If we catch an exception above, then $result===null because parent::delete only returns an int>=0 or boolean false
141 if (is_null($result)) {
142 // Delete it without the event, as something is wrong and we don't want it anyway.
143 $result = parent::delete($useWhere);
146 // Err, apparently we can reference $this->user_id after parent::delete,
147 // I guess it's safe because this is the order it was before!
148 self::blowCacheForProfileId($this->user_id);
149 self::blowCacheForNoticeId($this->notice_id);
150 self::blow('popular');
155 // FIXME: Instead of $own, send the scoped Profile so we can pass it along directly to FaveNoticeStream
156 // and preferrably we should get a Profile instead of $user_id
157 static function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
159 $target = Profile::getByID($user_id);
160 $stream = new FaveNoticeStream($target, ($own ? $target : null));
162 return $stream->getNotices($offset, $limit, $since_id, $max_id);
165 // FIXME: Instead of $own, send the scoped Profile so we can pass it along directly to FaveNoticeStream
166 // and preferrably we should get a Profile instead of $user_id
167 function idStream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
169 $target = Profile::getByID($user_id);
170 $stream = new FaveNoticeStream($target, ($own ? $target : null));
172 return $stream->getNoticeIds($offset, $limit, $since_id, $max_id);
175 function asActivity()
177 $target = $this->getTarget();
178 $actor = $this->getActor();
180 $act = new Activity();
182 $act->verb = ActivityVerb::FAVORITE;
184 // FIXME: rationalize this with URL below
186 $act->id = $this->getUri();
188 $act->time = strtotime($this->created);
189 // TRANS: Activity title when marking a notice as favorite.
190 $act->title = _("Favor");
191 // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
192 // notice's nickname and %3$s is the content of the favorited notice.)
193 $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
194 $actor->getNickname(), $target->getProfile()->getNickname(),
195 $target->getRendered());
196 $act->context = new ActivityContext();
197 $act->context->replyToID = $target->getUri();
199 $act->context->replyToURL = $target->getUrl();
200 } catch (InvalidUrlException $e) {
201 // ok, no replyToURL, i.e. the href="" in <thr:in-reply-to/>
204 $act->actor = $actor->asActivityObject();
205 $act->target = $target->asActivityObject();
206 $act->objects = array(clone($act->target));
208 $url = common_local_url('AtomPubShowFavorite',
209 array('profile' => $actor->id,
210 'notice' => $target->id));
212 $act->selfLink = $url;
213 $act->editLink = $url;
218 static function existsForProfile($notice, Profile $scoped)
220 $fave = self::pkeyGet(array('user_id'=>$scoped->id, 'notice_id'=>$notice->id));
222 return ($fave instanceof Fave);
226 * Fetch a stream of favorites by profile
228 * @param integer $profileId Profile that faved
229 * @param integer $offset Offset from last
230 * @param integer $limit Number to get
232 * @return mixed stream of faves, use fetch() to iterate
234 * @todo Cache results
235 * @todo integrate with Fave::stream()
238 static function byProfile($profileId, $offset, $limit)
242 $fav->user_id = $profileId;
244 $fav->orderBy('modified DESC');
246 $fav->limit($offset, $limit);
253 static function countByProfile(Profile $profile)
255 $c = Cache::instance();
257 $cnt = $c->get(Cache::key('fave:count_by_profile:'.$profile->id));
258 if (is_integer($cnt)) {
264 $faves->user_id = $profile->id;
265 $cnt = (int) $faves->count('notice_id');
268 $c->set(Cache::key('fave:count_by_profile:'.$profile->id), $cnt);
274 static protected $_faves = array();
277 * All faves of this notice
279 * @param Notice $notice A notice we wish to get faves for (may still be ArrayWrapper)
281 * @return array Array of Fave objects
283 static public function byNotice($notice)
285 if (!isset(self::$_faves[$notice->id])) {
286 self::fillFaves(array($notice->id));
288 return self::$_faves[$notice->id];
291 static public function fillFaves(array $notice_ids)
293 $faveMap = Fave::listGet('notice_id', $notice_ids);
294 self::$_faves = array_replace(self::$_faves, $faveMap);
297 static public function blowCacheForProfileId($profile_id)
299 $cache = Cache::instance();
301 // Faves don't happen chronologically, so we need to blow
303 $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id));
304 $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id.';last'));
305 $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id));
306 $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id.';last'));
307 $cache->delete(Cache::key('fave:count_by_profile:'.$profile_id));
310 static public function blowCacheForNoticeId($notice_id)
312 $cache = Cache::instance();
314 $cache->delete(Cache::key('fave:list-ids:notice_id:'.$notice_id));
318 // Remember that we want the _activity_ notice here, not faves applied
319 // to the supplied Notice (as with byNotice)!
320 static public function fromStored(Notice $stored)
322 $class = get_called_class();
323 $object = new $class;
324 $object->uri = $stored->uri;
325 if (!$object->find(true)) {
326 throw new NoResultException($object);
332 * Retrieves the _targeted_ notice of a verb (such as the notice that was
333 * _favorited_, but not the favorite activity itself).
335 * @param Notice $stored The activity notice.
337 * @throws NoResultException when it can't find what it's looking for.
339 static public function getTargetFromStored(Notice $stored)
341 return self::fromStored($stored)->getTarget();
344 static public function getObjectType()
346 return ActivityObject::ACTIVITY;
349 public function asActivityObject(Profile $scoped=null)
351 $actobj = new ActivityObject();
352 $actobj->id = $this->getUri();
353 $actobj->type = ActivityUtils::resolveUri(self::getObjectType());
354 $actobj->actor = $this->getActorObject();
355 $actobj->target = $this->getTargetObject();
356 $actobj->objects = array(clone($actobj->target));
357 $actobj->verb = ActivityVerb::FAVORITE;
358 $actobj->title = ActivityUtils::verbToTitle($actobj->verb);
359 $actobj->content = $this->getTarget()->getRendered();
364 * @param ActivityObject $actobj The _favored_ notice (which we're "in-reply-to")
365 * @param Notice $stored The _activity_ notice, i.e. the favor itself.
367 static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
369 // throws exception if nothing was found, but it could also be a non-Notice...
370 // FIXME: This should only test _one_ URI (and not the links etc.) though a function like this could be useful in other cases
371 $local = ActivityUtils::findLocalObject($actobj->getIdentifiers());
372 if (!$local instanceof Notice) {
373 // $local always returns something, but this was not what we expected. Something is wrong.
374 throw new Exception('Something other than a Notice was returned from findLocalObject');
377 $actor = $stored->getProfile();
378 $object = new Fave();
379 $object->user_id = $stored->getProfile()->id;
380 $object->notice_id = $local->id;
381 $object->uri = $stored->uri;
382 $object->created = $stored->created;
383 $object->modified = $stored->modified;
387 static public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
389 $target = self::getTargetFromStored($stored);
391 // The following logic was copied from StatusNet's Activity plugin
392 if (ActivityUtils::compareVerbs($target->verb, array(ActivityVerb::POST))) {
393 // "I like the thing you posted"
394 $act->objects = $target->asActivity()->objects;
396 // "I like that you did whatever you did"
397 $act->target = $target->asActivityObject();
398 $act->objects = array(clone($act->target));
400 $act->context->replyToID = $target->getUri();
401 $act->context->replyToUrl = $target->getUrl();
402 $act->title = ActivityUtils::verbToTitle($act->verb);
405 static function saveActivityObject(ActivityObject $actobj, Notice $stored)
407 $object = self::parseActivityObject($actobj, $stored);
408 $object->insert(); // exception throwing in Fave's case!
410 self::blowCacheForProfileId($object->user_id);
411 self::blowCacheForNoticeId($object->notice_id);
412 self::blow('popular');
414 Event::handle('EndFavorNotice', array($stored->getProfile(), $object->getTarget()));
418 public function getTarget()
420 return Notice::getByID($this->notice_id);
423 public function getTargetObject()
425 return $this->getTarget()->asActivityObject();
428 protected $_stored = array();
430 public function getStored()
432 if (!isset($this->_stored[$this->uri])) {
433 $stored = new Notice();
434 $stored->uri = $this->uri;
435 if (!$stored->find(true)) {
436 throw new NoResultException($stored);
438 $this->_stored[$this->uri] = $stored;
440 return $this->_stored[$this->uri];
443 public function getActor()
445 return Profile::getByID($this->user_id);
448 public function getActorObject()
450 return $this->getActor()->asActivityObject();
453 public function getUri()
455 if (!empty($this->uri)) {
459 // We (should've in this case) created it ourselves, so we tag it ourselves
460 return self::newUri($this->getActor(), $this->getTarget(), $this->created);