]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/classes/Fave.php
Fave deletion would fail in some cases with missing profiles or notices
[quix0rs-gnu-social.git] / plugins / Favorite / classes / Fave.php
1 <?php
2 /**
3  * Table Definition for fave
4  */
5
6 class Fave extends Managed_DataObject
7 {
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
14
15     public static function schemaDef()
16     {
17         return array(
18             'fields' => array(
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'),
24             ),
25             'primary key' => array('notice_id', 'user_id'),
26             'unique keys' => array(
27                 'fave_uri_key' => array('uri'),
28             ),
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
32             ),
33             'indexes' => array(
34                 'fave_notice_id_idx' => array('notice_id'),
35                 'fave_user_id_idx' => array('user_id', 'modified'),
36                 'fave_modified_idx' => array('modified'),
37             ),
38         );
39     }
40
41     /**
42      * Save a favorite record.
43      * @fixme post-author notification should be moved here
44      *
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
49      */
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!'));
54         }
55
56         $act = new Activity();
57         $act->type    = ActivityObject::ACTIVITY;
58         $act->verb    = ActivityVerb::FAVORITE;
59         $act->time    = time();
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->rendered ?: $target->content);
67         $act->actor   = $actor->asActivityObject();
68         $act->target  = $target->asActivityObject();
69         $act->objects = array(clone($act->target));
70
71         $url = common_local_url('AtomPubShowFavorite', array('profile'=>$actor->id, 'notice'=>$target->id));
72         $act->selfLink = $url;
73         $act->editLink = $url;
74
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);
78
79         return $stored;
80     }
81
82     public function removeEntry(Profile $actor, Notice $target)
83     {
84         $fave            = new Fave();
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.'));
90         }
91
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.'));
97         }
98
99         Fave::blowCacheForProfileId($actor->getID());
100         Fave::blowCacheForNoticeId($target->getID());
101     }
102
103     // exception throwing takeover!
104     public function insert()
105     {
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()));
109         }
110         self::blowCacheForProfileId($this->user_id);
111         self::blowCacheForNoticeId($this->notice_id);
112         return $this;
113     }
114
115     public function delete($useWhere=false)
116     {
117         $result = null;
118
119         try {
120             $profile = $this->getActor();
121             $notice  = $this->getTarget();
122
123             if (Event::handle('StartDisfavorNotice', array($profile, $notice, &$result))) {
124
125                 $result = parent::delete($useWhere);
126
127                 self::blowCacheForProfileId($this->user_id);
128                 self::blowCacheForNoticeId($this->notice_id);
129                 self::blow('popular');
130
131                 if ($result !== false) {
132                     Event::handle('EndDisfavorNotice', array($profile, $notice));
133                 }
134             }
135
136         } catch (NoResultException $e) {
137             common_log(LOG_INFO, '"'.get_class($e->obj).'" with id=='.var_export($e->obj->id, true).' object not found when deleting favorite, ignoring...');
138
139             // Delete it without the event, as something is wrong and we don't want it anyway.
140             $result = parent::delete($useWhere);
141
142             self::blowCacheForProfileId($this->user_id);
143             self::blowCacheForNoticeId($this->notice_id);
144             self::blow('popular');
145         }
146
147
148
149         return $result;
150     }
151
152     static function stream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
153     {
154         $stream = new FaveNoticeStream($user_id, $own);
155
156         return $stream->getNotices($offset, $limit, $since_id, $max_id);
157     }
158
159     function idStream($user_id, $offset=0, $limit=NOTICES_PER_PAGE, $own=false, $since_id=0, $max_id=0)
160     {
161         $stream = new FaveNoticeStream($user_id, $own);
162
163         return $stream->getNoticeIds($offset, $limit, $since_id, $max_id);
164     }
165
166     function asActivity()
167     {
168         $target = $this->getTarget();
169         $actor  = $this->getActor();
170
171         $act = new Activity();
172
173         $act->verb = ActivityVerb::FAVORITE;
174
175         // FIXME: rationalize this with URL below
176
177         $act->id   = $this->getUri();
178
179         $act->time    = strtotime($this->created);
180         // TRANS: Activity title when marking a notice as favorite.
181         $act->title   = _("Favor");
182         // TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
183         //        notice's nickname and %3$s is the content of the favorited notice.)
184         $act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
185                                 $actor->getNickname(), $target->getProfile()->getNickname(),
186                                 $target->rendered ?: $target->content);
187
188         $act->actor     = $actor->asActivityObject();
189         $act->target    = $target->asActivityObject();
190         $act->objects   = array(clone($act->target));
191
192         $url = common_local_url('AtomPubShowFavorite',
193                                           array('profile' => $actor->id,
194                                                 'notice'  => $target->id));
195
196         $act->selfLink = $url;
197         $act->editLink = $url;
198
199         return $act;
200     }
201
202     static function existsForProfile($notice, Profile $scoped)
203     {
204         $fave = self::pkeyGet(array('user_id'=>$scoped->id, 'notice_id'=>$notice->id));
205
206         return ($fave instanceof Fave);
207     }
208
209     /**
210      * Fetch a stream of favorites by profile
211      *
212      * @param integer $profileId Profile that faved
213      * @param integer $offset    Offset from last
214      * @param integer $limit     Number to get
215      *
216      * @return mixed stream of faves, use fetch() to iterate
217      *
218      * @todo Cache results
219      * @todo integrate with Fave::stream()
220      */
221
222     static function byProfile($profileId, $offset, $limit)
223     {
224         $fav = new Fave();
225
226         $fav->user_id = $profileId;
227
228         $fav->orderBy('modified DESC');
229
230         $fav->limit($offset, $limit);
231
232         $fav->find();
233
234         return $fav;
235     }
236
237     static function countByProfile(Profile $profile)
238     {
239         $c = Cache::instance();
240         if (!empty($c)) {
241             $cnt = $c->get(Cache::key('fave:count_by_profile:'.$profile->id));
242             if (is_integer($cnt)) {
243                 return $cnt;
244             }
245         }
246
247         $faves = new Fave();
248         $faves->user_id = $profile->id;
249         $cnt = (int) $faves->count('notice_id');
250
251         if (!empty($c)) {
252             $c->set(Cache::key('fave:count_by_profile:'.$profile->id), $cnt);
253         }
254
255         return $cnt;
256     }
257
258     static protected $_faves = array();
259
260     /**
261      * All faves of this notice
262      *
263      * @param Notice $notice A notice we wish to get faves for (may still be ArrayWrapper)
264      *
265      * @return array Array of Fave objects
266      */
267     static public function byNotice($notice)
268     {
269         if (!isset(self::$_faves[$notice->id])) {
270             self::fillFaves(array($notice->id));
271         }
272         return self::$_faves[$notice->id];
273     }
274
275     static public function fillFaves(array $notice_ids)
276     {
277         $faveMap = Fave::listGet('notice_id', $notice_ids);
278         self::$_faves = array_replace(self::$_faves, $faveMap);
279     }
280
281     static public function blowCacheForProfileId($profile_id)
282     {
283         $cache = Cache::instance();
284         if ($cache) {
285             // Faves don't happen chronologically, so we need to blow
286             // ;last cache, too
287             $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id));
288             $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id.';last'));
289             $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id));
290             $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id.';last'));
291             $cache->delete(Cache::key('fave:count_by_profile:'.$profile_id));
292         }
293     }
294     static public function blowCacheForNoticeId($notice_id)
295     {
296         $cache = Cache::instance();
297         if ($cache) {
298             $cache->delete(Cache::key('fave:list-ids:notice_id:'.$notice_id));
299         }
300     }
301
302     // Remember that we want the _activity_ notice here, not faves applied
303     // to the supplied Notice (as with byNotice)!
304     static public function fromStored(Notice $stored)
305     {
306         $class = get_called_class();
307         $object = new $class;
308         $object->uri = $stored->uri;
309         if (!$object->find(true)) {
310             throw new NoResultException($object);
311         }
312         return $object;
313     }
314
315     /**
316      * Retrieves the _targeted_ notice of a verb (such as the notice that was
317      * _favorited_, but not the favorite activity itself).
318      *
319      * @param Notice $stored    The activity notice.
320      *
321      * @throws NoResultException when it can't find what it's looking for.
322      */
323     static public function getTargetFromStored(Notice $stored)
324     {
325         return self::fromStored($stored)->getTarget();
326     }
327
328     static public function getObjectType()
329     {
330         return 'activity';
331     }
332
333     public function asActivityObject(Profile $scoped=null)
334     {
335         $actobj = new ActivityObject();
336         $actobj->id = $this->getUri();
337         $actobj->type = ActivityUtils::resolveUri(self::getObjectType());
338         $actobj->actor = $this->getActorObject();
339         $actobj->target = $this->getTargetObject();
340         $actobj->objects = array(clone($actobj->target));
341         $actobj->verb = ActivityVerb::FAVORITE;
342         $actobj->title = ActivityUtils::verbToTitle($actobj->verb);
343         $actobj->content = $this->getTarget()->rendered ?: $this->getTarget()->content;
344         return $actobj;
345     }
346
347     /**
348      * @param ActivityObject $actobj The _favored_ notice (which we're "in-reply-to")
349      * @param Notice         $stored The _activity_ notice, i.e. the favor itself.
350      */
351     static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
352     {
353         $local = ActivityUtils::findLocalObject($actobj->getIdentifiers());
354         if (!$local instanceof Notice) {
355             // $local always returns something, but this was not what we expected. Something is wrong.
356             throw new Exception('Something other than a Notice was returned from findLocalObject');
357         }
358  
359         $actor = $stored->getProfile();
360         $object = new Fave();
361         $object->user_id = $stored->getProfile()->id;
362         $object->notice_id = $local->id;
363         $object->uri = $stored->uri;
364         $object->created = $stored->created;
365         $object->modified = $stored->modified;
366         return $object;
367     }
368
369     static public function extendActivity(Notice $stored, Activity $act, Profile $scoped=null)
370     {
371         $target = self::getTargetFromStored($stored);
372
373         // The following logic was copied from StatusNet's Activity plugin
374         if (ActivityUtils::compareVerbs($target->verb, array(ActivityVerb::POST))) {
375             // "I like the thing you posted"
376             $act->objects = $target->asActivity()->objects;
377         } else {
378             // "I like that you did whatever you did"
379             $act->target = $target->asActivityObject();
380             $act->objects = array(clone($act->target));
381         }
382         $act->context->replyToID = $target->getUri();
383         $act->context->replyToUrl = $target->getUrl();
384         $act->title = ActivityUtils::verbToTitle($act->verb);
385     }
386
387     static function saveActivityObject(ActivityObject $actobj, Notice $stored)
388     {
389         $object = self::parseActivityObject($actobj, $stored);
390         $object->insert();  // exception throwing in Fave's case!
391
392         self::blowCacheForProfileId($object->user_id);
393         self::blowCacheForNoticeId($object->notice_id);
394         self::blow('popular');
395
396         Event::handle('EndFavorNotice', array($stored->getProfile(), $object->getTarget()));
397         return $object;
398     }
399
400     public function getAttentionArray() {
401         // not all objects can/should carry attentions, so we don't require extending this
402         // the format should be an array with URIs to mentioned profiles
403         return array();
404     }
405
406     public function getTarget()
407     {
408         return Notice::getByID($this->notice_id);
409     }
410
411     public function getTargetObject()
412     {
413         return $this->getTarget()->asActivityObject();
414     }
415
416     protected $_stored = array();
417
418     public function getStored()
419     {
420         if (!isset($this->_stored[$this->uri])) {
421             $stored = new Notice();
422             $stored->uri = $this->uri;
423             if (!$stored->find(true)) {
424                 throw new NoResultException($stored);
425             }
426             $this->_stored[$this->uri] = $stored;
427         }
428         return $this->_stored[$this->uri];
429     }
430
431     public function getActor()
432     {
433         return Profile::getByID($this->user_id);
434     }
435
436     public function getActorObject()
437     {
438         return $this->getActor()->asActivityObject();
439     }
440
441     public function getUri()
442     {
443         if (!empty($this->uri)) {
444             return $this->uri;
445         }
446
447         // We (should've in this case) created it ourselves, so we tag it ourselves
448         return self::newUri($this->getActor(), $this->getTarget(), $this->created);
449     }
450 }