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