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