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