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