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