]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
7f002d838c6e4a095ead2587c3708d34522dcbc5
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, Control Yourself, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for notice
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 /* We keep the first three 20-notice pages, plus one for pagination check,
28  * in the memcached cache. */
29
30 define('NOTICE_CACHE_WINDOW', 61);
31
32 define('NOTICE_LOCAL_PUBLIC', 1);
33 define('NOTICE_REMOTE_OMB', 0);
34 define('NOTICE_LOCAL_NONPUBLIC', -1);
35 define('NOTICE_GATEWAY', -2);
36
37 define('MAX_BOXCARS', 128);
38
39 class Notice extends Memcached_DataObject
40 {
41     ###START_AUTOCODE
42     /* the code below is auto generated do not remove the above tag */
43
44     public $__table = 'notice';                          // table name
45     public $id;                              // int(4)  primary_key not_null
46     public $profile_id;                      // int(4)   not_null
47     public $uri;                             // varchar(255)  unique_key
48     public $content;                         // varchar(140)
49     public $rendered;                        // text()
50     public $url;                             // varchar(255)
51     public $created;                         // datetime()   not_null
52     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
53     public $reply_to;                        // int(4)
54     public $is_local;                        // tinyint(1)
55     public $source;                          // varchar(32)
56     public $conversation;                    // int(4)
57
58     /* Static get */
59     function staticGet($k,$v=NULL) {
60         return Memcached_DataObject::staticGet('Notice',$k,$v);
61     }
62
63     /* the code above is auto generated do not remove the tag below */
64     ###END_AUTOCODE
65
66     function getProfile()
67     {
68         return Profile::staticGet('id', $this->profile_id);
69     }
70
71     function delete()
72     {
73         $this->blowCaches(true);
74         $this->blowFavesCache(true);
75         $this->blowSubsCache(true);
76
77         $this->query('BEGIN');
78         //Null any notices that are replies to this notice
79         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
80         $related = array('Reply',
81                          'Fave',
82                          'Notice_tag',
83                          'Group_inbox',
84                          'Queue_item');
85         if (common_config('inboxes', 'enabled')) {
86             $related[] = 'Notice_inbox';
87         }
88         foreach ($related as $cls) {
89             $inst = new $cls();
90             $inst->notice_id = $this->id;
91             $inst->delete();
92         }
93         $result = parent::delete();
94         $this->query('COMMIT');
95     }
96
97     function saveTags()
98     {
99         /* extract all #hastags */
100         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
101         if (!$count) {
102             return true;
103         }
104         
105         //turn each into their canonical tag
106         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
107         $hashtags = array();
108         for($i=0; $i<count($match[1]); $i++) {
109              $hashtags[] = common_canonical_tag($match[1][$i]);
110         }
111
112  
113         /* Add them to the database */
114         foreach(array_unique($hashtags) as $hashtag) {
115             /* elide characters we don't want in the tag */
116             $this->saveTag($hashtag);
117         }
118         return true;
119     }
120
121     function saveTag($hashtag)
122     {
123         $tag = new Notice_tag();
124         $tag->notice_id = $this->id;
125         $tag->tag = $hashtag;
126         $tag->created = $this->created;
127         $id = $tag->insert();
128
129         if (!$id) {
130             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
131                                               $last_error->message));
132             return;
133         }
134     }
135
136     static function saveNew($profile_id, $content, $source=null,
137                             $is_local=1, $reply_to=null, $uri=null, $created=null) {
138
139         $profile = Profile::staticGet($profile_id);
140
141         $final = common_shorten_links($content);
142
143         if (mb_strlen($final) > 140) {
144             common_log(LOG_INFO, 'Rejecting notice that is too long.');
145             return _('Problem saving notice. Too long.');
146         }
147
148         if (!$profile) {
149             common_log(LOG_ERR, 'Problem saving notice. Unknown user.');
150             return _('Problem saving notice. Unknown user.');
151         }
152
153         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
154             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
155             return _('Too many notices too fast; take a breather and post again in a few minutes.');
156         }
157
158         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
159             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
160                         return _('Too many duplicate messages too quickly; take a breather and post again in a few minutes.');
161         }
162
163                 $banned = common_config('profile', 'banned');
164
165         if ( in_array($profile_id, $banned) || in_array($profile->nickname, $banned)) {
166             common_log(LOG_WARNING, "Attempted post from banned user: $profile->nickname (user id = $profile_id).");
167             return _('You are banned from posting notices on this site.');
168         }
169
170         $notice = new Notice();
171         $notice->profile_id = $profile_id;
172
173         $blacklist = common_config('public', 'blacklist');
174         $autosource = common_config('public', 'autosource');
175
176         # Blacklisted are non-false, but not 1, either
177
178         if (($blacklist && in_array($profile_id, $blacklist)) ||
179             ($source && $autosource && in_array($source, $autosource))) {
180             $notice->is_local = -1;
181         } else {
182             $notice->is_local = $is_local;
183         }
184
185                 $notice->query('BEGIN');
186
187                 $notice->reply_to = $reply_to;
188         if (!empty($created)) {
189             $notice->created = $created;
190         } else {
191             $notice->created = common_sql_now();
192         }
193                 $notice->content = $final;
194                 $notice->rendered = common_render_content($final, $notice);
195                 $notice->source = $source;
196                 $notice->uri = $uri;
197
198         if (!empty($reply_to)) {
199             $reply_notice = Notice::staticGet('id', $reply_to);
200             if (!empty($reply_notice)) {
201                 $notice->reply_to = $reply_to;
202                 $notice->conversation = $reply_notice->conversation;
203             }
204         }
205
206         if (Event::handle('StartNoticeSave', array(&$notice))) {
207
208             $id = $notice->insert();
209
210             if (!$id) {
211                 common_log_db_error($notice, 'INSERT', __FILE__);
212                 return _('Problem saving notice.');
213             }
214
215             # Update the URI after the notice is in the database
216             if (!$uri) {
217                 $orig = clone($notice);
218                 $notice->uri = common_notice_uri($notice);
219
220                 if (!$notice->update($orig)) {
221                     common_log_db_error($notice, 'UPDATE', __FILE__);
222                     return _('Problem saving notice.');
223                 }
224             }
225
226             # XXX: do we need to change this for remote users?
227
228             $notice->saveReplies();
229             $notice->saveTags();
230
231             $notice->addToInboxes();
232
233             $notice->saveUrls();
234             $orig2 = clone($notice);
235                 $notice->rendered = common_render_content($final, $notice);
236             if (!$notice->update($orig2)) {
237                 common_log_db_error($notice, 'UPDATE', __FILE__);
238                 return _('Problem saving notice.');
239             }
240
241             $notice->query('COMMIT');
242
243             Event::handle('EndNoticeSave', array($notice));
244         }
245
246         # Clear the cache for subscribed users, so they'll update at next request
247         # XXX: someone clever could prepend instead of clearing the cache
248
249         $notice->blowCaches();
250
251         return $notice;
252     }
253
254     /** save all urls in the notice to the db
255      *
256      * follow redirects and save all available file information
257      * (mimetype, date, size, oembed, etc.)
258      *
259      * @return void
260      */
261     function saveUrls() {
262         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
263     }
264
265     function saveUrl($data) {
266         list($url, $notice_id) = $data;
267         File::processNew($url, $notice_id);
268     }
269
270     static function checkDupes($profile_id, $content) {
271         $profile = Profile::staticGet($profile_id);
272         if (!$profile) {
273             return false;
274         }
275         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
276         if ($notice) {
277             $last = 0;
278             while ($notice->fetch()) {
279                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
280                     return true;
281                 } else if ($notice->content == $content) {
282                     return false;
283                 }
284             }
285         }
286         # If we get here, oldest item in cache window is not
287         # old enough for dupe limit; do direct check against DB
288         $notice = new Notice();
289         $notice->profile_id = $profile_id;
290         $notice->content = $content;
291         if (common_config('db','type') == 'pgsql')
292             $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
293         else
294             $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
295
296         $cnt = $notice->count();
297         return ($cnt == 0);
298     }
299
300     static function checkEditThrottle($profile_id) {
301         $profile = Profile::staticGet($profile_id);
302         if (!$profile) {
303             return false;
304         }
305         # Get the Nth notice
306         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
307         if ($notice && $notice->fetch()) {
308             # If the Nth notice was posted less than timespan seconds ago
309             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
310                 # Then we throttle
311                 return false;
312             }
313         }
314         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
315         return true;
316     }
317
318     function getUploadedAttachment() {
319         $post = clone $this;
320         $query = 'select file.url as up, file.id as i from file join file_to_post on file.id = file_id where post_id=' . $post->escape($post->id) . ' and url like "%/notice/%/file"';
321         $post->query($query);
322         $post->fetch();
323         if (empty($post->up) || empty($post->i)) {
324             $ret = false;
325         } else {
326             $ret = array($post->up, $post->i);
327         }
328         $post->free();
329         return $ret;
330     }
331
332     function hasAttachments() {
333         $post = clone $this;
334         $query = "select count(file_id) as n_attachments from file join file_to_post on (file_id = file.id) join notice on (post_id = notice.id) where post_id = " . $post->escape($post->id);
335         $post->query($query);
336         $post->fetch();
337         $n_attachments = intval($post->n_attachments);
338         $post->free();
339         return $n_attachments;
340     }
341
342     function attachments() {
343         // XXX: cache this
344         $att = array();
345         $f2p = new File_to_post;
346         $f2p->post_id = $this->id;
347         if ($f2p->find()) {
348             while ($f2p->fetch()) {
349                 $f = File::staticGet($f2p->file_id);
350                 $att[] = clone($f);
351             }
352         }
353         return $att;
354     }
355
356     function blowCaches($blowLast=false)
357     {
358         $this->blowSubsCache($blowLast);
359         $this->blowNoticeCache($blowLast);
360         $this->blowRepliesCache($blowLast);
361         $this->blowPublicCache($blowLast);
362         $this->blowTagCache($blowLast);
363         $this->blowGroupCache($blowLast);
364         $this->blowConversationCache($blowLast);
365         $profile = Profile::staticGet($this->profile_id);
366         $profile->blowNoticeCount();
367     }
368
369     function blowConversationCache($blowLast=false)
370     {
371         $cache = common_memcache();
372         if ($cache) {
373             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
374             $cache->delete($ck);
375             if ($blowLast) {
376                 $cache->delete($ck.';last');
377             }
378         }
379     }
380
381     function blowGroupCache($blowLast=false)
382     {
383         $cache = common_memcache();
384         if ($cache) {
385             $group_inbox = new Group_inbox();
386             $group_inbox->notice_id = $this->id;
387             if ($group_inbox->find()) {
388                 while ($group_inbox->fetch()) {
389                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
390                     if ($blowLast) {
391                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
392                     }
393                     $member = new Group_member();
394                     $member->group_id = $group_inbox->group_id;
395                     if ($member->find()) {
396                         while ($member->fetch()) {
397                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
398                             if ($blowLast) {
399                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
400                             }
401                         }
402                     }
403                 }
404             }
405             $group_inbox->free();
406             unset($group_inbox);
407         }
408     }
409
410     function blowTagCache($blowLast=false)
411     {
412         $cache = common_memcache();
413         if ($cache) {
414             $tag = new Notice_tag();
415             $tag->notice_id = $this->id;
416             if ($tag->find()) {
417                 while ($tag->fetch()) {
418                     $tag->blowCache($blowLast);
419                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
420
421                     $cache->delete($ck);
422                     if ($blowLast) {
423                         $cache->delete($ck . ';last');
424                     }
425                 }
426             }
427             $tag->free();
428             unset($tag);
429         }
430     }
431
432     function blowSubsCache($blowLast=false)
433     {
434         $cache = common_memcache();
435         if ($cache) {
436             $user = new User();
437
438             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
439             $user->query('SELECT id ' .
440
441                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
442                          'WHERE subscription.subscribed = ' . $this->profile_id);
443
444             while ($user->fetch()) {
445                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
446                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
447                 if ($blowLast) {
448                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
449                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
450                 }
451             }
452             $user->free();
453             unset($user);
454         }
455     }
456
457     function blowNoticeCache($blowLast=false)
458     {
459         if ($this->is_local) {
460             $cache = common_memcache();
461             if (!empty($cache)) {
462                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
463                 if ($blowLast) {
464                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
465                 }
466             }
467         }
468     }
469
470     function blowRepliesCache($blowLast=false)
471     {
472         $cache = common_memcache();
473         if ($cache) {
474             $reply = new Reply();
475             $reply->notice_id = $this->id;
476             if ($reply->find()) {
477                 while ($reply->fetch()) {
478                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
479                     if ($blowLast) {
480                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
481                     }
482                 }
483             }
484             $reply->free();
485             unset($reply);
486         }
487     }
488
489     function blowPublicCache($blowLast=false)
490     {
491         if ($this->is_local == 1) {
492             $cache = common_memcache();
493             if ($cache) {
494                 $cache->delete(common_cache_key('public'));
495                 if ($blowLast) {
496                     $cache->delete(common_cache_key('public').';last');
497                 }
498             }
499         }
500     }
501
502     function blowFavesCache($blowLast=false)
503     {
504         $cache = common_memcache();
505         if ($cache) {
506             $fave = new Fave();
507             $fave->notice_id = $this->id;
508             if ($fave->find()) {
509                 while ($fave->fetch()) {
510                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
511                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
512                     if ($blowLast) {
513                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
514                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
515                     }
516                 }
517             }
518             $fave->free();
519             unset($fave);
520         }
521     }
522
523     # XXX: too many args; we need to move to named params or even a separate
524     # class for notice streams
525
526     static function getStream($qry, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $order=null, $since=null) {
527
528         if (common_config('memcached', 'enabled')) {
529
530             # Skip the cache if this is a since, since_id or max_id qry
531             if ($since_id > 0 || $max_id > 0 || $since) {
532                 return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
533             } else {
534                 return Notice::getCachedStream($qry, $cachekey, $offset, $limit, $order);
535             }
536         }
537
538         return Notice::getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since);
539     }
540
541     static function getStreamDirect($qry, $offset, $limit, $since_id, $max_id, $order, $since) {
542
543         $needAnd = false;
544         $needWhere = true;
545
546         if (preg_match('/\bWHERE\b/i', $qry)) {
547             $needWhere = false;
548             $needAnd = true;
549         }
550
551         if ($since_id > 0) {
552
553             if ($needWhere) {
554                 $qry .= ' WHERE ';
555                 $needWhere = false;
556             } else {
557                 $qry .= ' AND ';
558             }
559
560             $qry .= ' notice.id > ' . $since_id;
561         }
562
563         if ($max_id > 0) {
564
565             if ($needWhere) {
566                 $qry .= ' WHERE ';
567                 $needWhere = false;
568             } else {
569                 $qry .= ' AND ';
570             }
571
572             $qry .= ' notice.id <= ' . $max_id;
573         }
574
575         if ($since) {
576
577             if ($needWhere) {
578                 $qry .= ' WHERE ';
579                 $needWhere = false;
580             } else {
581                 $qry .= ' AND ';
582             }
583
584             $qry .= ' notice.created > \'' . date('Y-m-d H:i:s', $since) . '\'';
585         }
586
587         # Allow ORDER override
588
589         if ($order) {
590             $qry .= $order;
591         } else {
592             $qry .= ' ORDER BY notice.created DESC, notice.id DESC ';
593         }
594
595         if (common_config('db','type') == 'pgsql') {
596             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
597         } else {
598             $qry .= ' LIMIT ' . $offset . ', ' . $limit;
599         }
600
601         $notice = new Notice();
602
603         $notice->query($qry);
604
605         return $notice;
606     }
607
608     # XXX: this is pretty long and should probably be broken up into
609     # some helper functions
610
611     static function getCachedStream($qry, $cachekey, $offset, $limit, $order) {
612
613         # If outside our cache window, just go to the DB
614
615         if ($offset + $limit > NOTICE_CACHE_WINDOW) {
616             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
617         }
618
619         # Get the cache; if we can't, just go to the DB
620
621         $cache = common_memcache();
622
623         if (!$cache) {
624             return Notice::getStreamDirect($qry, $offset, $limit, null, null, $order, null);
625         }
626
627         # Get the notices out of the cache
628
629         $notices = $cache->get(common_cache_key($cachekey));
630
631         # On a cache hit, return a DB-object-like wrapper
632
633         if ($notices !== false) {
634             $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
635             return $wrapper;
636         }
637
638         # If the cache was invalidated because of new data being
639         # added, we can try and just get the new stuff. We keep an additional
640         # copy of the data at the key + ';last'
641
642         # No cache hit. Try to get the *last* cached version
643
644         $last_notices = $cache->get(common_cache_key($cachekey) . ';last');
645
646         if ($last_notices) {
647
648             # Reverse-chron order, so last ID is last.
649
650             $last_id = $last_notices[0]->id;
651
652             # XXX: this assumes monotonically increasing IDs; a fair
653             # bet with our DB.
654
655             $new_notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW,
656                                                   $last_id, null, $order, null);
657
658             if ($new_notice) {
659                 $new_notices = array();
660                 while ($new_notice->fetch()) {
661                     $new_notices[] = clone($new_notice);
662                 }
663                 $new_notice->free();
664                 $notices = array_slice(array_merge($new_notices, $last_notices),
665                                        0, NOTICE_CACHE_WINDOW);
666
667                 # Store the array in the cache for next time
668
669                 $result = $cache->set(common_cache_key($cachekey), $notices);
670                 $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
671
672                 # return a wrapper of the array for use now
673
674                 return new ArrayWrapper(array_slice($notices, $offset, $limit));
675             }
676         }
677
678         # Otherwise, get the full cache window out of the DB
679
680         $notice = Notice::getStreamDirect($qry, 0, NOTICE_CACHE_WINDOW, null, null, $order, null);
681
682         # If there are no hits, just return the value
683
684         if (!$notice) {
685             return $notice;
686         }
687
688         # Pack results into an array
689
690         $notices = array();
691
692         while ($notice->fetch()) {
693             $notices[] = clone($notice);
694         }
695
696         $notice->free();
697
698         # Store the array in the cache for next time
699
700         $result = $cache->set(common_cache_key($cachekey), $notices);
701         $result = $cache->set(common_cache_key($cachekey) . ';last', $notices);
702
703         # return a wrapper of the array for use now
704
705         $wrapper = new ArrayWrapper(array_slice($notices, $offset, $limit));
706
707         return $wrapper;
708     }
709
710     function getStreamByIds($ids)
711     {
712         $cache = common_memcache();
713
714         if (!empty($cache)) {
715             $notices = array();
716             foreach ($ids as $id) {
717                 $n = Notice::staticGet('id', $id);
718                 if (!empty($n)) {
719                     $notices[] = $n;
720                 }
721             }
722             return new ArrayWrapper($notices);
723         } else {
724             $notice = new Notice();
725             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
726             $notice->orderBy('id DESC');
727
728             $notice->find();
729             return $notice;
730         }
731     }
732
733     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
734     {
735         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
736                               array(),
737                               'public',
738                               $offset, $limit, $since_id, $max_id, $since);
739
740         return Notice::getStreamByIds($ids);
741     }
742
743     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
744     {
745         $notice = new Notice();
746
747         $notice->selectAdd(); // clears it
748         $notice->selectAdd('id');
749
750         $notice->orderBy('id DESC');
751
752         if (!is_null($offset)) {
753             $notice->limit($offset, $limit);
754         }
755
756         if (common_config('public', 'localonly')) {
757             $notice->whereAdd('is_local = 1');
758         } else {
759             # -1 == blacklisted
760             $notice->whereAdd('is_local != -1');
761         }
762
763         if ($since_id != 0) {
764             $notice->whereAdd('id > ' . $since_id);
765         }
766
767         if ($max_id != 0) {
768             $notice->whereAdd('id <= ' . $max_id);
769         }
770
771         if (!is_null($since)) {
772             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
773         }
774
775         $ids = array();
776
777         if ($notice->find()) {
778             while ($notice->fetch()) {
779                 $ids[] = $notice->id;
780             }
781         }
782
783         $notice->free();
784         $notice = NULL;
785
786         return $ids;
787     }
788
789     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
790     {
791         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
792                               array($id),
793                               'notice:conversation_ids:'.$id,
794                               $offset, $limit, $since_id, $max_id, $since);
795
796         return Notice::getStreamByIds($ids);
797     }
798
799     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
800     {
801         $notice = new Notice();
802
803         $notice->selectAdd(); // clears it
804         $notice->selectAdd('id');
805
806         $notice->conversation = $id;
807
808         $notice->orderBy('id DESC');
809
810         if (!is_null($offset)) {
811             $notice->limit($offset, $limit);
812         }
813
814         if ($since_id != 0) {
815             $notice->whereAdd('id > ' . $since_id);
816         }
817
818         if ($max_id != 0) {
819             $notice->whereAdd('id <= ' . $max_id);
820         }
821
822         if (!is_null($since)) {
823             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
824         }
825
826         $ids = array();
827
828         if ($notice->find()) {
829             while ($notice->fetch()) {
830                 $ids[] = $notice->id;
831             }
832         }
833
834         $notice->free();
835         $notice = NULL;
836
837         return $ids;
838     }
839
840     function addToInboxes()
841     {
842         $enabled = common_config('inboxes', 'enabled');
843
844         if ($enabled === true || $enabled === 'transitional') {
845
846             // XXX: loads constants
847
848             $inbox = new Notice_inbox();
849
850             $users = $this->getSubscribedUsers();
851
852             // FIXME: kind of ignoring 'transitional'...
853             // we'll probably stop supporting inboxless mode
854             // in 0.9.x
855
856             $ni = array();
857
858             foreach ($users as $id) {
859                 $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
860             }
861
862             $groups = $this->saveGroups();
863
864             foreach ($groups as $group) {
865                 $users = $group->getUserMembers();
866                 foreach ($users as $id) {
867                     if (!array_key_exists($id, $ni)) {
868                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
869                     }
870                 }
871             }
872
873             $cnt = 0;
874
875             $qryhdr = 'INSERT INTO notice_inbox (user_id, notice_id, source, created) VALUES ';
876             $qry = $qryhdr;
877
878             foreach ($ni as $id => $source) {
879                 if ($cnt > 0) {
880                     $qry .= ', ';
881                 }
882                 $qry .= '('.$id.', '.$this->id.', '.$source.", '".$this->created. "') ";
883                 $cnt++;
884                 if (rand() % NOTICE_INBOX_SOFT_LIMIT == 0) {
885                     Notice_inbox::gc($id);
886                 }
887                 if ($cnt >= MAX_BOXCARS) {
888                     $inbox = new Notice_inbox();
889                     $inbox->query($qry);
890                     $qry = $qryhdr;
891                     $cnt = 0;
892                 }
893             }
894
895             if ($cnt > 0) {
896                 $inbox = new Notice_inbox();
897                 $inbox->query($qry);
898             }
899         }
900
901         return;
902     }
903
904     function getSubscribedUsers()
905     {
906         $user = new User();
907
908         if(common_config('db','quote_identifiers'))
909             $user_table = '"user"';
910         else $user_table = 'user';
911
912         $qry =
913           'SELECT id ' .
914           'FROM '. $user_table .' JOIN subscription '.
915           'ON '. $user_table .'.id = subscription.subscriber ' .
916           'WHERE subscription.subscribed = %d ';
917
918         $user->query(sprintf($qry, $this->profile_id));
919
920         $ids = array();
921
922         while ($user->fetch()) {
923             $ids[] = $user->id;
924         }
925
926         $user->free();
927
928         return $ids;
929     }
930
931     function saveGroups()
932     {
933         $groups = array();
934
935         $enabled = common_config('inboxes', 'enabled');
936         if ($enabled !== true && $enabled !== 'transitional') {
937             return $groups;
938         }
939
940         /* extract all !group */
941         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
942                                 strtolower($this->content),
943                                 $match);
944         if (!$count) {
945             return $groups;
946         }
947
948         $profile = $this->getProfile();
949
950         /* Add them to the database */
951
952         foreach (array_unique($match[1]) as $nickname) {
953             /* XXX: remote groups. */
954             $group = User_group::getForNickname($nickname);
955
956             if (empty($group)) {
957                 continue;
958             }
959
960             // we automatically add a tag for every group name, too
961
962             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
963                                              'notice_id' => $this->id));
964
965             if (is_null($tag)) {
966                 $this->saveTag($nickname);
967             }
968
969             if ($profile->isMember($group)) {
970
971                 $result = $this->addToGroupInbox($group);
972
973                 if (!$result) {
974                     common_log_db_error($gi, 'INSERT', __FILE__);
975                 }
976
977                 $groups[] = clone($group);
978             }
979         }
980
981         return $groups;
982     }
983
984     function addToGroupInbox($group)
985     {
986         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
987                                          'notice_id' => $this->id));
988
989         if (empty($gi)) {
990
991             $gi = new Group_inbox();
992
993             $gi->group_id  = $group->id;
994             $gi->notice_id = $this->id;
995             $gi->created   = $this->created;
996
997             return $gi->insert();
998         }
999
1000         return true;
1001     }
1002
1003     function saveReplies()
1004     {
1005         // Alternative reply format
1006         $tname = false;
1007         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1008             $tname = $match[1];
1009         }
1010         // extract all @messages
1011         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1012
1013         $names = array();
1014
1015         if ($cnt || $tname) {
1016             // XXX: is there another way to make an array copy?
1017             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1018         }
1019
1020         $sender = Profile::staticGet($this->profile_id);
1021
1022         $replied = array();
1023
1024         // store replied only for first @ (what user/notice what the reply directed,
1025         // we assume first @ is it)
1026
1027         for ($i=0; $i<count($names); $i++) {
1028             $nickname = $names[$i];
1029             $recipient = common_relative_profile($sender, $nickname, $this->created);
1030             if (!$recipient) {
1031                 continue;
1032             }
1033             if ($i == 0 && ($recipient->id != $sender->id) && !$this->reply_to) { // Don't save reply to self
1034                 $reply_for = $recipient;
1035                 $recipient_notice = $reply_for->getCurrentNotice();
1036                 if ($recipient_notice) {
1037                     $orig = clone($this);
1038                     $this->reply_to = $recipient_notice->id;
1039                     $this->conversation = $recipient_notice->conversation;
1040                     $this->update($orig);
1041                 }
1042             }
1043             // Don't save replies from blocked profile to local user
1044             $recipient_user = User::staticGet('id', $recipient->id);
1045             if ($recipient_user && $recipient_user->hasBlocked($sender)) {
1046                 continue;
1047             }
1048             $reply = new Reply();
1049             $reply->notice_id = $this->id;
1050             $reply->profile_id = $recipient->id;
1051             $id = $reply->insert();
1052             if (!$id) {
1053                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1054                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1055                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1056                 return;
1057             } else {
1058                 $replied[$recipient->id] = 1;
1059             }
1060         }
1061
1062         // Hash format replies, too
1063         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1064         if ($cnt) {
1065             foreach ($match[1] as $tag) {
1066                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1067                 foreach ($tagged as $t) {
1068                     if (!$replied[$t->id]) {
1069                         // Don't save replies from blocked profile to local user
1070                         $t_user = User::staticGet('id', $t->id);
1071                         if ($t_user && $t_user->hasBlocked($sender)) {
1072                             continue;
1073                         }
1074                         $reply = new Reply();
1075                         $reply->notice_id = $this->id;
1076                         $reply->profile_id = $t->id;
1077                         $id = $reply->insert();
1078                         if (!$id) {
1079                             common_log_db_error($reply, 'INSERT', __FILE__);
1080                             return;
1081                         } else {
1082                             $replied[$recipient->id] = 1;
1083                         }
1084                     }
1085                 }
1086             }
1087         }
1088
1089         // If it's not a reply, make it the root of a new conversation
1090
1091         if (empty($this->conversation)) {
1092             $orig = clone($this);
1093             $this->conversation = $this->id;
1094             $this->update($orig);
1095         }
1096
1097         foreach (array_keys($replied) as $recipient) {
1098             $user = User::staticGet('id', $recipient);
1099             if ($user) {
1100                 mail_notify_attn($user, $this);
1101             }
1102         }
1103     }
1104
1105     function asAtomEntry($namespace=false, $source=false)
1106     {
1107         $profile = $this->getProfile();
1108
1109         $xs = new XMLStringer(true);
1110
1111         if ($namespace) {
1112             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1113                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1114         } else {
1115             $attrs = array();
1116         }
1117
1118         $xs->elementStart('entry', $attrs);
1119
1120         if ($source) {
1121             $xs->elementStart('source');
1122             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1123             $xs->element('link', array('href' => $profile->profileurl));
1124             $user = User::staticGet('id', $profile->id);
1125             if (!empty($user)) {
1126                 $atom_feed = common_local_url('api',
1127                                               array('apiaction' => 'statuses',
1128                                                     'method' => 'user_timeline',
1129                                                     'argument' => $profile->nickname.'.atom'));
1130                 $xs->element('link', array('rel' => 'self',
1131                                            'type' => 'application/atom+xml',
1132                                            'href' => $profile->profileurl));
1133                 $xs->element('link', array('rel' => 'license',
1134                                            'href' => common_config('license', 'url')));
1135             }
1136
1137             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1138         }
1139
1140         $xs->elementStart('author');
1141         $xs->element('name', null, $profile->nickname);
1142         $xs->element('uri', null, $profile->profileurl);
1143         $xs->elementEnd('author');
1144
1145         if ($source) {
1146             $xs->elementEnd('source');
1147         }
1148
1149         $xs->element('title', null, $this->content);
1150         $xs->element('summary', null, $this->content);
1151
1152         $xs->element('link', array('rel' => 'alternate',
1153                                    'href' => $this->bestUrl()));
1154
1155         $xs->element('id', null, $this->uri);
1156
1157         $xs->element('published', null, common_date_w3dtf($this->created));
1158         $xs->element('updated', null, common_date_w3dtf($this->modified));
1159
1160         if ($this->reply_to) {
1161             $reply_notice = Notice::staticGet('id', $this->reply_to);
1162             if (!empty($reply_notice)) {
1163                 $xs->element('link', array('rel' => 'related',
1164                                            'href' => $reply_notice->bestUrl()));
1165                 $xs->element('thr:in-reply-to',
1166                              array('ref' => $reply_notice->uri,
1167                                    'href' => $reply_notice->bestUrl()));
1168             }
1169         }
1170
1171         $xs->element('content', array('type' => 'html'), $this->rendered);
1172
1173         $tag = new Notice_tag();
1174         $tag->notice_id = $this->id;
1175         if ($tag->find()) {
1176             while ($tag->fetch()) {
1177                 $xs->element('category', array('term' => $tag->tag));
1178             }
1179         }
1180         $tag->free();
1181
1182         # Enclosures
1183         $attachments = $this->attachments();
1184         if($attachments){
1185             foreach($attachments as $attachment){
1186                 if ($attachment->isEnclosure()) {
1187                     $attributes = array('rel'=>'enclosure','href'=>$attachment->url,'type'=>$attachment->mimetype,'length'=>$attachment->size);
1188                     if($attachment->title){
1189                         $attributes['title']=$attachment->title;
1190                     }
1191                     $xs->element('link', $attributes, null);
1192                 }
1193             }
1194         }
1195
1196         $xs->elementEnd('entry');
1197
1198         return $xs->getString();
1199     }
1200
1201     function bestUrl()
1202     {
1203         if (!empty($this->url)) {
1204             return $this->url;
1205         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1206             return $this->uri;
1207         } else {
1208             return common_local_url('shownotice',
1209                                     array('notice' => $this->id));
1210         }
1211     }
1212
1213     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1214     {
1215         $cache = common_memcache();
1216
1217         if (empty($cache) ||
1218             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1219             is_null($limit) ||
1220             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1221             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1222                                                                       $max_id, $since)));
1223         }
1224
1225         $idkey = common_cache_key($cachekey);
1226
1227         $idstr = $cache->get($idkey);
1228
1229         if (!empty($idstr)) {
1230             // Cache hit! Woohoo!
1231             $window = explode(',', $idstr);
1232             $ids = array_slice($window, $offset, $limit);
1233             return $ids;
1234         }
1235
1236         $laststr = $cache->get($idkey.';last');
1237
1238         if (!empty($laststr)) {
1239             $window = explode(',', $laststr);
1240             $last_id = $window[0];
1241             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1242                                                                           $last_id, 0, null)));
1243
1244             $new_window = array_merge($new_ids, $window);
1245
1246             $new_windowstr = implode(',', $new_window);
1247
1248             $result = $cache->set($idkey, $new_windowstr);
1249             $result = $cache->set($idkey . ';last', $new_windowstr);
1250
1251             $ids = array_slice($new_window, $offset, $limit);
1252
1253             return $ids;
1254         }
1255
1256         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1257                                                                      0, 0, null)));
1258
1259         $windowstr = implode(',', $window);
1260
1261         $result = $cache->set($idkey, $windowstr);
1262         $result = $cache->set($idkey . ';last', $windowstr);
1263
1264         $ids = array_slice($window, $offset, $limit);
1265
1266         return $ids;
1267     }
1268 }