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