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