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