]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Favorite/classes/Fave.php
ceaa37022b799f2e6c31720772dc3fc573ddde19
[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         $notice = Notice::getKV('id', $this->notice_id);
132
133         if (!$notice) {
134             throw new Exception("Fave for non-existent notice: " . $this->notice_id);
135         }
136
137         $profile = Profile::getKV('id', $this->user_id);
138
139         if (!$profile) {
140             throw new Exception("Fave by non-existent profile: " . $this->user_id);
141         }
142
143         $act = new Activity();
144
145         $act->verb = ActivityVerb::FAVORITE;
146
147         // FIXME: rationalize this with URL below
148
149         $act->id   = $this->getURI();
150
151         $act->time    = strtotime($this->modified);
152         // TRANS: Activity title when marking a notice as favorite.
153         $act->title   = _("Favor");
154         // TRANS: Ntofication given when a user marks a notice as favorite.
155         // TRANS: %1$s is a user nickname or full name, %2$s is a notice URI.
156         $act->content = sprintf(_('%1$s marked notice %2$s as a favorite.'),
157                                $profile->getBestName(),
158                                $notice->getUrl());
159
160         $act->actor     = $profile->asActivityObject();
161         $act->objects[] = ActivityObject::fromNotice($notice);
162
163         $url = common_local_url('AtomPubShowFavorite',
164                                           array('profile' => $this->user_id,
165                                                 'notice'  => $this->notice_id));
166
167         $act->selfLink = $url;
168         $act->editLink = $url;
169
170         return $act;
171     }
172
173     static function existsForProfile($notice, Profile $scoped)
174     {
175         $fave = self::pkeyGet(array('user_id'=>$scoped->id, 'notice_id'=>$notice->id));
176
177         return ($fave instanceof Fave);
178     }
179
180     /**
181      * Fetch a stream of favorites by profile
182      *
183      * @param integer $profileId Profile that faved
184      * @param integer $offset    Offset from last
185      * @param integer $limit     Number to get
186      *
187      * @return mixed stream of faves, use fetch() to iterate
188      *
189      * @todo Cache results
190      * @todo integrate with Fave::stream()
191      */
192
193     static function byProfile($profileId, $offset, $limit)
194     {
195         $fav = new Fave();
196
197         $fav->user_id = $profileId;
198
199         $fav->orderBy('modified DESC');
200
201         $fav->limit($offset, $limit);
202
203         $fav->find();
204
205         return $fav;
206     }
207
208     static function countByProfile(Profile $profile)
209     {
210         $c = Cache::instance();
211         if (!empty($c)) {
212             $cnt = $c->get(Cache::key('fave:count_by_profile:'.$profile->id));
213             if (is_integer($cnt)) {
214                 return $cnt;
215             }
216         }
217
218         $faves = new Fave();
219         $faves->user_id = $profile->id;
220         $cnt = (int) $faves->count('notice_id');
221
222         if (!empty($c)) {
223             $c->set(Cache::key('fave:count_by_profile:'.$profile->id), $cnt);
224         }
225
226         return $cnt;
227     }
228
229     static protected $_faves = array();
230
231     /**
232      * All faves of this notice
233      *
234      * @param Notice $notice A notice we wish to get faves for (may still be ArrayWrapper)
235      *
236      * @return array Array of Fave objects
237      */
238     static public function byNotice($notice)
239     {
240         if (!isset(self::$_faves[$notice->id])) {
241             self::fillFaves(array($notice->id));
242         }
243         return self::$_faves[$notice->id];
244     }
245
246     static public function fillFaves(array $notice_ids)
247     {
248         $faveMap = Fave::listGet('notice_id', $notice_ids);
249         self::$_faves = array_replace(self::$_faves, $faveMap);
250     }
251
252     static public function blowCacheForProfileId($profile_id)
253     {
254         $cache = Cache::instance();
255         if ($cache) {
256             // Faves don't happen chronologically, so we need to blow
257             // ;last cache, too
258             $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id));
259             $cache->delete(Cache::key('fave:ids_by_user:'.$profile_id.';last'));
260             $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id));
261             $cache->delete(Cache::key('fave:ids_by_user_own:'.$profile_id.';last'));
262             $cache->delete(Cache::key('fave:count_by_profile:'.$profile_id));
263         }
264     }
265     static public function blowCacheForNoticeId($notice_id)
266     {
267         $cache = Cache::instance();
268         if ($cache) {
269             $cache->delete(Cache::key('fave:list-ids:notice_id:'.$notice_id));
270         }
271     }
272
273     // Remember that we want the _activity_ notice here, not faves applied
274     // to the supplied Notice (as with byNotice)!
275     static public function fromStored(Notice $stored)
276     {
277         $class = get_called_class();
278         $object = new $class;
279         $object->uri = $stored->uri;
280         if (!$object->find(true)) {
281             throw new NoResultException($object);
282         }
283         return $object;
284     }
285
286     static public function verbToTitle($verb)
287     {
288         return ucfirst($verb);
289     }
290
291     static public function getObjectType()
292     {
293         return 'activity';
294     }
295
296     public function asActivityObject(Profile $scoped=null)
297     {
298         $actobj = new ActivityObject();
299         $actobj->id = $this->getUri();
300         $actobj->type = ActivityUtils::resolveUri(ActivityObject::ACTIVITY);
301         $actobj->actor = $this->getActorObject();
302         $actobj->objects = array(clone($actobj->target));
303         $actobj->title = Stored_ActivityVerb::verbToTitle($this->verb);
304         //$actobj->verb = $this->verb;
305         //$actobj->target = $this->getTargetObject();
306         return $actobj;
307     }
308
309     static public function parseActivityObject(ActivityObject $actobj, Notice $stored)
310     {
311         // The ActivityObject we get here is the _favored_ notice (kind of what we're "in-reply-to")
312         // The Notice we get is the _activity_ stored in our Notice table
313
314         $type = isset($actobj->type) ? ActivityUtils::resolveUri($actobj->type, true) : ActivityObject::NOTE;
315         $local = ActivityUtils::findLocalObject($actobj->getIdentifiers(), $type); 
316         if (!$local instanceof Notice) {
317             // $local always returns something, but this was not what we expected. Something is wrong.
318             throw new Exception('Something other than a Notice was returned from findLocalObject');
319         }
320  
321         $actor = $stored->getProfile();
322         $object = new Fave();
323         $object->user_id = $stored->getProfile()->id;
324         $object->notice_id = $local->id;
325         $object->uri = $stored->uri;
326         $object->created = $stored->created;
327         $object->modified = $stored->modified;
328         return $object;
329     }
330
331     static function saveActivityObject(ActivityObject $actobj, Notice $stored)
332     {
333         $object = self::parseActivityObject($actobj, $stored);
334         $object->insert();  // exception throwing!
335         return $object;
336     }
337
338
339     public function getTarget()
340     {
341         // throws exception on failure
342         return ActivityUtils::findLocalObject(array($this->uri), $this->type);
343     }
344
345     public function getTargetObject()
346     {
347         return $this->getTarget()->asActivityObject();
348     }
349
350     protected $_stored = array();
351
352     public function getStored()
353     {
354         if (!isset($this->_stored[$this->uri])) {
355             $stored = new Notice();
356             $stored->uri = $this->uri;
357             if (!$stored->find(true)) {
358                 throw new NoResultException($stored);
359             }
360             $this->_stored[$this->uri] = $stored;
361         }
362         return $this->_stored[$this->uri];
363     }
364
365     public function getActor()
366     {
367         $profile = new Profile();
368         $profile->id = $this->user_id;
369         if (!$profile->find(true)) {
370             throw new NoResultException($profile);
371         }
372         return $profile;
373     }
374
375     public function getActorObject()
376     {
377         return $this->getActor()->asActivityObject();
378     }
379
380     public function getURI()
381     {
382         if (!empty($this->uri)) {
383             return $this->uri;
384         }
385
386         // We (should've in this case) created it ourselves, so we tag it ourselves
387         return self::newURI($this->getActor(), $this->getTarget(), $this->created);
388     }
389
390     static function newURI(Profile $actor, Managed_DataObject $target, $created=null)
391     {
392         if (is_null($created)) {
393             $created = common_sql_now();
394         }
395         return TagURI::mint(strtolower(get_called_class()).':%d:%s:%d:%s',
396                                         $actor->id,
397                                         ActivityUtils::resolveUri(self::getObjectType(), true),
398                                         $target->id,
399                                         common_date_iso8601($created));
400     }
401 }