]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[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  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
34  */
35
36 if (!defined('STATUSNET') && !defined('LACONICA')) {
37     exit(1);
38 }
39
40 /**
41  * Table Definition for notice
42  */
43 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
44
45 /* We keep the first three 20-notice pages, plus one for pagination check,
46  * in the memcached cache. */
47
48 define('NOTICE_CACHE_WINDOW', 61);
49
50 define('MAX_BOXCARS', 128);
51
52 class Notice extends Memcached_DataObject
53 {
54     ###START_AUTOCODE
55     /* the code below is auto generated do not remove the above tag */
56
57     public $__table = 'notice';                          // table name
58     public $id;                              // int(4)  primary_key not_null
59     public $profile_id;                      // int(4)  multiple_key not_null
60     public $uri;                             // varchar(255)  unique_key
61     public $content;                         // text
62     public $rendered;                        // text
63     public $url;                             // varchar(255)
64     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
65     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
66     public $reply_to;                        // int(4)
67     public $is_local;                        // int(4)
68     public $source;                          // varchar(32)
69     public $conversation;                    // int(4)
70     public $lat;                             // decimal(10,7)
71     public $lon;                             // decimal(10,7)
72     public $location_id;                     // int(4)
73     public $location_ns;                     // int(4)
74     public $repeat_of;                       // int(4)
75
76     /* Static get */
77     function staticGet($k,$v=NULL)
78     {
79         return Memcached_DataObject::staticGet('Notice',$k,$v);
80     }
81
82     /* the code above is auto generated do not remove the tag below */
83     ###END_AUTOCODE
84
85     /* Notice types */
86     const LOCAL_PUBLIC    =  1;
87     const REMOTE_OMB      =  0;
88     const LOCAL_NONPUBLIC = -1;
89     const GATEWAY         = -2;
90
91     function getProfile()
92     {
93         return Profile::staticGet('id', $this->profile_id);
94     }
95
96     function delete()
97     {
98         // For auditing purposes, save a record that the notice
99         // was deleted.
100
101         // @fixme we have some cases where things get re-run and so the
102         // insert fails.
103         $deleted = Deleted_notice::staticGet('id', $this->id);
104         if (!$deleted) {
105             $deleted = new Deleted_notice();
106
107             $deleted->id         = $this->id;
108             $deleted->profile_id = $this->profile_id;
109             $deleted->uri        = $this->uri;
110             $deleted->created    = $this->created;
111             $deleted->deleted    = common_sql_now();
112
113             $deleted->insert();
114         }
115
116         // Clear related records
117
118         $this->clearReplies();
119         $this->clearRepeats();
120         $this->clearFaves();
121         $this->clearTags();
122         $this->clearGroupInboxes();
123
124         // NOTE: we don't clear inboxes
125         // NOTE: we don't clear queue items
126
127         $result = parent::delete();
128
129         $this->blowOnDelete();
130         return $result;
131     }
132
133     /**
134      * Extract #hashtags from this notice's content and save them to the database.
135      */
136     function saveTags()
137     {
138         /* extract all #hastags */
139         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
140         if (!$count) {
141             return true;
142         }
143
144         /* Add them to the database */
145         return $this->saveKnownTags($match[1]);
146     }
147
148     /**
149      * Record the given set of hash tags in the db for this notice.
150      * Given tag strings will be normalized and checked for dupes.
151      */
152     function saveKnownTags($hashtags)
153     {
154         //turn each into their canonical tag
155         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
156         for($i=0; $i<count($hashtags); $i++) {
157             /* elide characters we don't want in the tag */
158             $hashtags[$i] = common_canonical_tag($hashtags[$i]);
159         }
160
161         foreach(array_unique($hashtags) as $hashtag) {
162             $this->saveTag($hashtag);
163             self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, $hashtag);
164         }
165         return true;
166     }
167
168     /**
169      * Record a single hash tag as associated with this notice.
170      * Tag format and uniqueness must be validated by caller.
171      */
172     function saveTag($hashtag)
173     {
174         $tag = new Notice_tag();
175         $tag->notice_id = $this->id;
176         $tag->tag = $hashtag;
177         $tag->created = $this->created;
178         $id = $tag->insert();
179
180         if (!$id) {
181             // TRANS: Server exception. %s are the error details.
182             throw new ServerException(sprintf(_('Database error inserting hashtag: %s'),
183                                               $last_error->message));
184             return;
185         }
186
187         // if it's saved, blow its cache
188         $tag->blowCache(false);
189     }
190
191     /**
192      * Save a new notice and push it out to subscribers' inboxes.
193      * Poster's permissions are checked before sending.
194      *
195      * @param int $profile_id Profile ID of the poster
196      * @param string $content source message text; links may be shortened
197      *                        per current user's preference
198      * @param string $source source key ('web', 'api', etc)
199      * @param array $options Associative array of optional properties:
200      *              string 'created' timestamp of notice; defaults to now
201      *              int 'is_local' source/gateway ID, one of:
202      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
203      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
204      *                                            hide from public timeline but show in
205      *                                            local "and friends" timelines
206      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
207      *                  Notice::GATEWAY         - From another non-OMB service;
208      *                                            will not appear in public views
209      *              float 'lat' decimal latitude for geolocation
210      *              float 'lon' decimal longitude for geolocation
211      *              int 'location_id' geoname identifier
212      *              int 'location_ns' geoname namespace to interpret location_id
213      *              int 'reply_to'; notice ID this is a reply to
214      *              int 'repeat_of'; notice ID this is a repeat of
215      *              string 'uri' unique ID for notice; defaults to local notice URL
216      *              string 'url' permalink to notice; defaults to local notice URL
217      *              string 'rendered' rendered HTML version of content
218      *              array 'replies' list of profile URIs for reply delivery in
219      *                              place of extracting @-replies from content.
220      *              array 'groups' list of group IDs to deliver to, in place of
221      *                              extracting ! tags from content
222      *              array 'tags' list of hashtag strings to save with the notice
223      *                           in place of extracting # tags from content
224      *              array 'urls' list of attached/referred URLs to save with the
225      *                           notice in place of extracting links from content
226      * @fixme tag override
227      *
228      * @return Notice
229      * @throws ClientException
230      */
231     static function saveNew($profile_id, $content, $source, $options=null) {
232         $defaults = array('uri' => null,
233                           'url' => null,
234                           'reply_to' => null,
235                           'repeat_of' => null);
236
237         if (!empty($options)) {
238             $options = $options + $defaults;
239             extract($options);
240         }
241
242         if (!isset($is_local)) {
243             $is_local = Notice::LOCAL_PUBLIC;
244         }
245
246         $profile = Profile::staticGet($profile_id);
247
248         $final = common_shorten_links($content);
249
250         if (Notice::contentTooLong($final)) {
251             throw new ClientException(_('Problem saving notice. Too long.'));
252         }
253
254         if (empty($profile)) {
255             throw new ClientException(_('Problem saving notice. Unknown user.'));
256         }
257
258         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
259             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
260             throw new ClientException(_('Too many notices too fast; take a breather '.
261                                         'and post again in a few minutes.'));
262         }
263
264         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
265             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
266             throw new ClientException(_('Too many duplicate messages too quickly;'.
267                                         ' take a breather and post again in a few minutes.'));
268         }
269
270         if (!$profile->hasRight(Right::NEWNOTICE)) {
271             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
272             throw new ClientException(_('You are banned from posting notices on this site.'));
273         }
274
275         $notice = new Notice();
276         $notice->profile_id = $profile_id;
277
278         $autosource = common_config('public', 'autosource');
279
280         # Sandboxed are non-false, but not 1, either
281
282         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
283             ($source && $autosource && in_array($source, $autosource))) {
284             $notice->is_local = Notice::LOCAL_NONPUBLIC;
285         } else {
286             $notice->is_local = $is_local;
287         }
288
289         if (!empty($created)) {
290             $notice->created = $created;
291         } else {
292             $notice->created = common_sql_now();
293         }
294
295         $notice->content = $final;
296
297         $notice->source = $source;
298         $notice->uri = $uri;
299         $notice->url = $url;
300
301         // Handle repeat case
302
303         if (isset($repeat_of)) {
304             $notice->repeat_of = $repeat_of;
305         } else {
306             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
307         }
308
309         if (!empty($notice->reply_to)) {
310             $reply = Notice::staticGet('id', $notice->reply_to);
311             $notice->conversation = $reply->conversation;
312         }
313
314         if (!empty($lat) && !empty($lon)) {
315             $notice->lat = $lat;
316             $notice->lon = $lon;
317         }
318
319         if (!empty($location_ns) && !empty($location_id)) {
320             $notice->location_id = $location_id;
321             $notice->location_ns = $location_ns;
322         }
323
324         if (!empty($rendered)) {
325             $notice->rendered = $rendered;
326         } else {
327             $notice->rendered = common_render_content($final, $notice);
328         }
329
330         if (Event::handle('StartNoticeSave', array(&$notice))) {
331
332             // XXX: some of these functions write to the DB
333
334             $id = $notice->insert();
335
336             if (!$id) {
337                 common_log_db_error($notice, 'INSERT', __FILE__);
338                 throw new ServerException(_('Problem saving notice.'));
339             }
340
341             // Update ID-dependent columns: URI, conversation
342
343             $orig = clone($notice);
344
345             $changed = false;
346
347             if (empty($uri)) {
348                 $notice->uri = common_notice_uri($notice);
349                 $changed = true;
350             }
351
352             // If it's not part of a conversation, it's
353             // the beginning of a new conversation.
354
355             if (empty($notice->conversation)) {
356                 $conv = Conversation::create();
357                 $notice->conversation = $conv->id;
358                 $changed = true;
359             }
360
361             if ($changed) {
362                 if (!$notice->update($orig)) {
363                     common_log_db_error($notice, 'UPDATE', __FILE__);
364                     throw new ServerException(_('Problem saving notice.'));
365                 }
366             }
367
368         }
369
370         # Clear the cache for subscribed users, so they'll update at next request
371         # XXX: someone clever could prepend instead of clearing the cache
372
373         $notice->blowOnInsert();
374
375         // Save per-notice metadata...
376
377         if (isset($replies)) {
378             $notice->saveKnownReplies($replies);
379         } else {
380             $notice->saveReplies();
381         }
382
383         if (isset($tags)) {
384             $notice->saveKnownTags($tags);
385         } else {
386             $notice->saveTags();
387         }
388
389         // Note: groups may save tags, so must be run after tags are saved
390         // to avoid errors on duplicates.
391         if (isset($groups)) {
392             $notice->saveKnownGroups($groups);
393         } else {
394             $notice->saveGroups();
395         }
396
397         if (isset($urls)) {
398             $notice->saveKnownUrls($urls);
399         } else {
400             $notice->saveUrls();
401         }
402
403         // Prepare inbox delivery, may be queued to background.
404         $notice->distribute();
405
406         return $notice;
407     }
408
409     function blowOnInsert($conversation = false)
410     {
411         self::blow('profile:notice_ids:%d', $this->profile_id);
412         self::blow('public');
413
414         // XXX: Before we were blowing the casche only if the notice id
415         // was not the root of the conversation.  What to do now?
416
417         self::blow('notice:conversation_ids:%d', $this->conversation);
418
419         if (!empty($this->repeat_of)) {
420             self::blow('notice:repeats:%d', $this->repeat_of);
421         }
422
423         $original = Notice::staticGet('id', $this->repeat_of);
424
425         if (!empty($original)) {
426             $originalUser = User::staticGet('id', $original->profile_id);
427             if (!empty($originalUser)) {
428                 self::blow('user:repeats_of_me:%d', $originalUser->id);
429             }
430         }
431
432         $profile = Profile::staticGet($this->profile_id);
433         if (!empty($profile)) {
434             $profile->blowNoticeCount();
435         }
436     }
437
438     /**
439      * Clear cache entries related to this notice at delete time.
440      * Necessary to avoid breaking paging on public, profile timelines.
441      */
442     function blowOnDelete()
443     {
444         $this->blowOnInsert();
445
446         self::blow('profile:notice_ids:%d;last', $this->profile_id);
447         self::blow('public;last');
448     }
449
450     /** save all urls in the notice to the db
451      *
452      * follow redirects and save all available file information
453      * (mimetype, date, size, oembed, etc.)
454      *
455      * @return void
456      */
457     function saveUrls() {
458         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
459     }
460
461     /**
462      * Save the given URLs as related links/attachments to the db
463      *
464      * follow redirects and save all available file information
465      * (mimetype, date, size, oembed, etc.)
466      *
467      * @return void
468      */
469     function saveKnownUrls($urls)
470     {
471         // @fixme validation?
472         foreach ($urls as $url) {
473             File::processNew($url, $this->id);
474         }
475     }
476
477     /**
478      * @private callback
479      */
480     function saveUrl($data) {
481         list($url, $notice_id) = $data;
482         File::processNew($url, $notice_id);
483     }
484
485     static function checkDupes($profile_id, $content) {
486         $profile = Profile::staticGet($profile_id);
487         if (empty($profile)) {
488             return false;
489         }
490         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
491         if (!empty($notice)) {
492             $last = 0;
493             while ($notice->fetch()) {
494                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
495                     return true;
496                 } else if ($notice->content == $content) {
497                     return false;
498                 }
499             }
500         }
501         # If we get here, oldest item in cache window is not
502         # old enough for dupe limit; do direct check against DB
503         $notice = new Notice();
504         $notice->profile_id = $profile_id;
505         $notice->content = $content;
506         if (common_config('db','type') == 'pgsql')
507           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
508         else
509           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
510
511         $cnt = $notice->count();
512         return ($cnt == 0);
513     }
514
515     static function checkEditThrottle($profile_id) {
516         $profile = Profile::staticGet($profile_id);
517         if (empty($profile)) {
518             return false;
519         }
520         # Get the Nth notice
521         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
522         if ($notice && $notice->fetch()) {
523             # If the Nth notice was posted less than timespan seconds ago
524             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
525                 # Then we throttle
526                 return false;
527             }
528         }
529         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
530         return true;
531     }
532
533     function getUploadedAttachment() {
534         $post = clone $this;
535         $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"';
536         $post->query($query);
537         $post->fetch();
538         if (empty($post->up) || empty($post->i)) {
539             $ret = false;
540         } else {
541             $ret = array($post->up, $post->i);
542         }
543         $post->free();
544         return $ret;
545     }
546
547     function hasAttachments() {
548         $post = clone $this;
549         $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);
550         $post->query($query);
551         $post->fetch();
552         $n_attachments = intval($post->n_attachments);
553         $post->free();
554         return $n_attachments;
555     }
556
557     function attachments() {
558         // XXX: cache this
559         $att = array();
560         $f2p = new File_to_post;
561         $f2p->post_id = $this->id;
562         if ($f2p->find()) {
563             while ($f2p->fetch()) {
564                 $f = File::staticGet($f2p->file_id);
565                 $att[] = clone($f);
566             }
567         }
568         return $att;
569     }
570
571     function getStreamByIds($ids)
572     {
573         $cache = common_memcache();
574
575         if (!empty($cache)) {
576             $notices = array();
577             foreach ($ids as $id) {
578                 $n = Notice::staticGet('id', $id);
579                 if (!empty($n)) {
580                     $notices[] = $n;
581                 }
582             }
583             return new ArrayWrapper($notices);
584         } else {
585             $notice = new Notice();
586             if (empty($ids)) {
587                 //if no IDs requested, just return the notice object
588                 return $notice;
589             }
590             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
591
592             $notice->find();
593
594             $temp = array();
595
596             while ($notice->fetch()) {
597                 $temp[$notice->id] = clone($notice);
598             }
599
600             $wrapped = array();
601
602             foreach ($ids as $id) {
603                 if (array_key_exists($id, $temp)) {
604                     $wrapped[] = $temp[$id];
605                 }
606             }
607
608             return new ArrayWrapper($wrapped);
609         }
610     }
611
612     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0)
613     {
614         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
615                               array(),
616                               'public',
617                               $offset, $limit, $since_id, $max_id);
618         return Notice::getStreamByIds($ids);
619     }
620
621     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0)
622     {
623         $notice = new Notice();
624
625         $notice->selectAdd(); // clears it
626         $notice->selectAdd('id');
627
628         $notice->orderBy('id DESC');
629
630         if (!is_null($offset)) {
631             $notice->limit($offset, $limit);
632         }
633
634         if (common_config('public', 'localonly')) {
635             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
636         } else {
637             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
638             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
639             $notice->whereAdd('is_local !='. Notice::GATEWAY);
640         }
641
642         if ($since_id != 0) {
643             $notice->whereAdd('id > ' . $since_id);
644         }
645
646         if ($max_id != 0) {
647             $notice->whereAdd('id <= ' . $max_id);
648         }
649
650         $ids = array();
651
652         if ($notice->find()) {
653             while ($notice->fetch()) {
654                 $ids[] = $notice->id;
655             }
656         }
657
658         $notice->free();
659         $notice = NULL;
660
661         return $ids;
662     }
663
664     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
665     {
666         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
667                               array($id),
668                               'notice:conversation_ids:'.$id,
669                               $offset, $limit, $since_id, $max_id);
670
671         return Notice::getStreamByIds($ids);
672     }
673
674     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0)
675     {
676         $notice = new Notice();
677
678         $notice->selectAdd(); // clears it
679         $notice->selectAdd('id');
680
681         $notice->conversation = $id;
682
683         $notice->orderBy('id DESC');
684
685         if (!is_null($offset)) {
686             $notice->limit($offset, $limit);
687         }
688
689         if ($since_id != 0) {
690             $notice->whereAdd('id > ' . $since_id);
691         }
692
693         if ($max_id != 0) {
694             $notice->whereAdd('id <= ' . $max_id);
695         }
696
697         $ids = array();
698
699         if ($notice->find()) {
700             while ($notice->fetch()) {
701                 $ids[] = $notice->id;
702             }
703         }
704
705         $notice->free();
706         $notice = NULL;
707
708         return $ids;
709     }
710
711     /**
712      * Is this notice part of an active conversation?
713      *
714      * @return boolean true if other messages exist in the same
715      *                 conversation, false if this is the only one
716      */
717     function hasConversation()
718     {
719         if (!empty($this->conversation)) {
720             $conversation = Notice::conversationStream(
721                 $this->conversation,
722                 1,
723                 1
724             );
725             if ($conversation->N > 0) {
726                 return true;
727             }
728         }
729         return false;
730     }
731
732     /**
733      * @param $groups array of Group *objects*
734      * @param $recipients array of profile *ids*
735      */
736     function whoGets($groups=null, $recipients=null)
737     {
738         $c = self::memcache();
739
740         if (!empty($c)) {
741             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
742             if ($ni !== false) {
743                 return $ni;
744             }
745         }
746
747         if (is_null($groups)) {
748             $groups = $this->getGroups();
749         }
750
751         if (is_null($recipients)) {
752             $recipients = $this->getReplies();
753         }
754
755         $users = $this->getSubscribedUsers();
756
757         // FIXME: kind of ignoring 'transitional'...
758         // we'll probably stop supporting inboxless mode
759         // in 0.9.x
760
761         $ni = array();
762
763         foreach ($users as $id) {
764             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
765         }
766
767         $profile = $this->getProfile();
768
769         foreach ($groups as $group) {
770             $users = $group->getUserMembers();
771             foreach ($users as $id) {
772                 if (!array_key_exists($id, $ni)) {
773                     $user = User::staticGet('id', $id);
774                     if (!$user->hasBlocked($profile)) {
775                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
776                     }
777                 }
778             }
779         }
780
781         foreach ($recipients as $recipient) {
782
783             if (!array_key_exists($recipient, $ni)) {
784                 $recipientUser = User::staticGet('id', $recipient);
785                 if (!empty($recipientUser)) {
786                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
787                 }
788             }
789         }
790
791         if (!empty($c)) {
792             // XXX: pack this data better
793             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
794         }
795
796         return $ni;
797     }
798
799     /**
800      * Adds this notice to the inboxes of each local user who should receive
801      * it, based on author subscriptions, group memberships, and @-replies.
802      *
803      * Warning: running a second time currently will make items appear
804      * multiple times in users' inboxes.
805      *
806      * @fixme make more robust against errors
807      * @fixme break up massive deliveries to smaller background tasks
808      *
809      * @param array $groups optional list of Group objects;
810      *              if left empty, will be loaded from group_inbox records
811      * @param array $recipient optional list of reply profile ids
812      *              if left empty, will be loaded from reply records
813      */
814     function addToInboxes($groups=null, $recipients=null)
815     {
816         $ni = $this->whoGets($groups, $recipients);
817
818         $ids = array_keys($ni);
819
820         // We remove the author (if they're a local user),
821         // since we'll have already done this in distribute()
822
823         $i = array_search($this->profile_id, $ids);
824
825         if ($i !== false) {
826             unset($ids[$i]);
827         }
828
829         // Bulk insert
830
831         Inbox::bulkInsert($this->id, $ids);
832
833         return;
834     }
835
836     function getSubscribedUsers()
837     {
838         $user = new User();
839
840         if(common_config('db','quote_identifiers'))
841           $user_table = '"user"';
842         else $user_table = 'user';
843
844         $qry =
845           'SELECT id ' .
846           'FROM '. $user_table .' JOIN subscription '.
847           'ON '. $user_table .'.id = subscription.subscriber ' .
848           'WHERE subscription.subscribed = %d ';
849
850         $user->query(sprintf($qry, $this->profile_id));
851
852         $ids = array();
853
854         while ($user->fetch()) {
855             $ids[] = $user->id;
856         }
857
858         $user->free();
859
860         return $ids;
861     }
862
863     /**
864      * Record this notice to the given group inboxes for delivery.
865      * Overrides the regular parsing of !group markup.
866      *
867      * @param string $group_ids
868      * @fixme might prefer URIs as identifiers, as for replies?
869      *        best with generalizations on user_group to support
870      *        remote groups better.
871      */
872     function saveKnownGroups($group_ids)
873     {
874         if (!is_array($group_ids)) {
875             throw new ServerException("Bad type provided to saveKnownGroups");
876         }
877
878         $groups = array();
879         foreach ($group_ids as $id) {
880             $group = User_group::staticGet('id', $id);
881             if ($group) {
882                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
883                 $result = $this->addToGroupInbox($group);
884                 if (!$result) {
885                     common_log_db_error($gi, 'INSERT', __FILE__);
886                 }
887
888                 // @fixme should we save the tags here or not?
889                 $groups[] = clone($group);
890             } else {
891                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
892             }
893         }
894
895         return $groups;
896     }
897
898     /**
899      * Parse !group delivery and record targets into group_inbox.
900      * @return array of Group objects
901      */
902     function saveGroups()
903     {
904         // Don't save groups for repeats
905
906         if (!empty($this->repeat_of)) {
907             return array();
908         }
909
910         $groups = array();
911
912         /* extract all !group */
913         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
914                                 strtolower($this->content),
915                                 $match);
916         if (!$count) {
917             return $groups;
918         }
919
920         $profile = $this->getProfile();
921
922         /* Add them to the database */
923
924         foreach (array_unique($match[1]) as $nickname) {
925             /* XXX: remote groups. */
926             $group = User_group::getForNickname($nickname, $profile);
927
928             if (empty($group)) {
929                 continue;
930             }
931
932             // we automatically add a tag for every group name, too
933
934             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
935                                              'notice_id' => $this->id));
936
937             if (is_null($tag)) {
938                 $this->saveTag($nickname);
939             }
940
941             if ($profile->isMember($group)) {
942
943                 $result = $this->addToGroupInbox($group);
944
945                 if (!$result) {
946                     common_log_db_error($gi, 'INSERT', __FILE__);
947                 }
948
949                 $groups[] = clone($group);
950             }
951         }
952
953         return $groups;
954     }
955
956     function addToGroupInbox($group)
957     {
958         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
959                                          'notice_id' => $this->id));
960
961         if (empty($gi)) {
962
963             $gi = new Group_inbox();
964
965             $gi->group_id  = $group->id;
966             $gi->notice_id = $this->id;
967             $gi->created   = $this->created;
968
969             $result = $gi->insert();
970
971             if (!$result) {
972                 common_log_db_error($gi, 'INSERT', __FILE__);
973                 throw new ServerException(_('Problem saving group inbox.'));
974             }
975
976             self::blow('user_group:notice_ids:%d', $gi->group_id);
977         }
978
979         return true;
980     }
981
982     /**
983      * Save reply records indicating that this notice needs to be
984      * delivered to the local users with the given URIs.
985      *
986      * Since this is expected to be used when saving foreign-sourced
987      * messages, we won't deliver to any remote targets as that's the
988      * source service's responsibility.
989      *
990      * Mail notifications etc will be handled later.
991      *
992      * @param array of unique identifier URIs for recipients
993      */
994     function saveKnownReplies($uris)
995     {
996         if (empty($uris)) {
997             return;
998         }
999         $sender = Profile::staticGet($this->profile_id);
1000
1001         foreach ($uris as $uri) {
1002
1003             $user = User::staticGet('uri', $uri);
1004
1005             if (!empty($user)) {
1006                 if ($user->hasBlocked($sender)) {
1007                     continue;
1008                 }
1009
1010                 $reply = new Reply();
1011
1012                 $reply->notice_id  = $this->id;
1013                 $reply->profile_id = $user->id;
1014
1015                 $id = $reply->insert();
1016             }
1017         }
1018
1019         return;
1020     }
1021
1022     /**
1023      * Pull @-replies from this message's content in StatusNet markup format
1024      * and save reply records indicating that this message needs to be
1025      * delivered to those users.
1026      *
1027      * Mail notifications to local profiles will be sent later.
1028      *
1029      * @return array of integer profile IDs
1030      */
1031
1032     function saveReplies()
1033     {
1034         // Don't save reply data for repeats
1035
1036         if (!empty($this->repeat_of)) {
1037             return array();
1038         }
1039
1040         $sender = Profile::staticGet($this->profile_id);
1041
1042         // @todo ideally this parser information would only
1043         // be calculated once.
1044
1045         $mentions = common_find_mentions($this->content, $this);
1046
1047         $replied = array();
1048
1049         // store replied only for first @ (what user/notice what the reply directed,
1050         // we assume first @ is it)
1051
1052         foreach ($mentions as $mention) {
1053
1054             foreach ($mention['mentioned'] as $mentioned) {
1055
1056                 // skip if they're already covered
1057
1058                 if (!empty($replied[$mentioned->id])) {
1059                     continue;
1060                 }
1061
1062                 // Don't save replies from blocked profile to local user
1063
1064                 $mentioned_user = User::staticGet('id', $mentioned->id);
1065                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1066                     continue;
1067                 }
1068
1069                 $reply = new Reply();
1070
1071                 $reply->notice_id  = $this->id;
1072                 $reply->profile_id = $mentioned->id;
1073
1074                 $id = $reply->insert();
1075
1076                 if (!$id) {
1077                     common_log_db_error($reply, 'INSERT', __FILE__);
1078                     throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1079                 } else {
1080                     $replied[$mentioned->id] = 1;
1081                     self::blow('reply:stream:%d', $mentioned->id);
1082                 }
1083             }
1084         }
1085
1086         $recipientIds = array_keys($replied);
1087
1088         return $recipientIds;
1089     }
1090
1091     /**
1092      * Pull the complete list of @-reply targets for this notice.
1093      *
1094      * @return array of integer profile ids
1095      */
1096     function getReplies()
1097     {
1098         // XXX: cache me
1099
1100         $ids = array();
1101
1102         $reply = new Reply();
1103         $reply->selectAdd();
1104         $reply->selectAdd('profile_id');
1105         $reply->notice_id = $this->id;
1106
1107         if ($reply->find()) {
1108             while($reply->fetch()) {
1109                 $ids[] = $reply->profile_id;
1110             }
1111         }
1112
1113         $reply->free();
1114
1115         return $ids;
1116     }
1117
1118     /**
1119      * Send e-mail notifications to local @-reply targets.
1120      *
1121      * Replies must already have been saved; this is expected to be run
1122      * from the distrib queue handler.
1123      */
1124     function sendReplyNotifications()
1125     {
1126         // Don't send reply notifications for repeats
1127
1128         if (!empty($this->repeat_of)) {
1129             return array();
1130         }
1131
1132         $recipientIds = $this->getReplies();
1133
1134         foreach ($recipientIds as $recipientId) {
1135             $user = User::staticGet('id', $recipientId);
1136             if (!empty($user)) {
1137                 mail_notify_attn($user, $this);
1138             }
1139         }
1140     }
1141
1142     /**
1143      * Pull list of groups this notice needs to be delivered to,
1144      * as previously recorded by saveGroups() or saveKnownGroups().
1145      *
1146      * @return array of Group objects
1147      */
1148     function getGroups()
1149     {
1150         // Don't save groups for repeats
1151
1152         if (!empty($this->repeat_of)) {
1153             return array();
1154         }
1155
1156         // XXX: cache me
1157
1158         $groups = array();
1159
1160         $gi = new Group_inbox();
1161
1162         $gi->selectAdd();
1163         $gi->selectAdd('group_id');
1164
1165         $gi->notice_id = $this->id;
1166
1167         if ($gi->find()) {
1168             while ($gi->fetch()) {
1169                 $group = User_group::staticGet('id', $gi->group_id);
1170                 if ($group) {
1171                     $groups[] = $group;
1172                 }
1173             }
1174         }
1175
1176         $gi->free();
1177
1178         return $groups;
1179     }
1180
1181     function asAtomEntry($namespace=false, $source=false, $author=true, $cur=null)
1182     {
1183         $profile = $this->getProfile();
1184
1185         $xs = new XMLStringer(true);
1186
1187         if ($namespace) {
1188             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1189                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1190                            'xmlns:georss' => 'http://www.georss.org/georss',
1191                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1192                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
1193                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1194                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
1195                            'xmlns:statusnet' => 'http://status.net/ont/');
1196         } else {
1197             $attrs = array();
1198         }
1199
1200         $xs->elementStart('entry', $attrs);
1201
1202         if ($source) {
1203             $xs->elementStart('source');
1204             $xs->element('id', null, $profile->profileurl);
1205             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1206             $xs->element('link', array('href' => $profile->profileurl));
1207             $user = User::staticGet('id', $profile->id);
1208             if (!empty($user)) {
1209                 $atom_feed = common_local_url('ApiTimelineUser',
1210                                               array('format' => 'atom',
1211                                                     'id' => $profile->nickname));
1212                 $xs->element('link', array('rel' => 'self',
1213                                            'type' => 'application/atom+xml',
1214                                            'href' => $profile->profileurl));
1215                 $xs->element('link', array('rel' => 'license',
1216                                            'href' => common_config('license', 'url')));
1217             }
1218
1219             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1220             $xs->element('updated', null, common_date_w3dtf($this->created));
1221         }
1222
1223         if ($source) {
1224             $xs->elementEnd('source');
1225         }
1226
1227         $xs->element('title', null, common_xml_safe_str($this->content));
1228
1229         if ($author) {
1230             $xs->raw($profile->asAtomAuthor());
1231             $xs->raw($profile->asActivityActor());
1232         }
1233
1234         $xs->element('link', array('rel' => 'alternate',
1235                                    'type' => 'text/html',
1236                                    'href' => $this->bestUrl()));
1237
1238         $xs->element('id', null, $this->uri);
1239
1240         $xs->element('published', null, common_date_w3dtf($this->created));
1241         $xs->element('updated', null, common_date_w3dtf($this->created));
1242
1243         $noticeInfoAttr = array(
1244             'local_id'   => $this->id,    // local notice ID (useful to clients for ordering)
1245             'source'     => $this->source, // the client name (source attribution)
1246         );
1247
1248         $ns = $this->getSource();
1249         if ($ns) {
1250             if (!empty($ns->url)) {
1251                 $noticeInfoAttr['source_link'] = $ns->url;
1252             }
1253         }
1254
1255         if (!empty($cur)) {
1256             $noticeInfoAttr['favorite'] = ($cur->hasFave($this)) ? "true" : "false";
1257             $profile = $cur->getProfile();
1258             $noticeInfoAttr['repeated'] = ($profile->hasRepeated($this->id)) ? "true" : "false";
1259         }
1260
1261         if (!empty($this->repeat_of)) {
1262             $noticeInfoAttr['repeat_of'] = $this->repeat_of;
1263         }
1264
1265         $xs->element('statusnet:notice_info', $noticeInfoAttr, null);
1266
1267         if ($this->reply_to) {
1268             $reply_notice = Notice::staticGet('id', $this->reply_to);
1269             if (!empty($reply_notice)) {
1270                 $xs->element('link', array('rel' => 'related',
1271                                            'href' => $reply_notice->bestUrl()));
1272                 $xs->element('thr:in-reply-to',
1273                              array('ref' => $reply_notice->uri,
1274                                    'href' => $reply_notice->bestUrl()));
1275             }
1276         }
1277
1278         if (!empty($this->conversation)) {
1279
1280             $conv = Conversation::staticGet('id', $this->conversation);
1281
1282             if (!empty($conv)) {
1283                 $xs->element(
1284                     'link', array(
1285                         'rel' => 'ostatus:conversation',
1286                         'href' => $conv->uri
1287                     )
1288                 );
1289             }
1290         }
1291
1292         $reply_ids = $this->getReplies();
1293
1294         foreach ($reply_ids as $id) {
1295             $profile = Profile::staticGet('id', $id);
1296            if (!empty($profile)) {
1297                 $xs->element(
1298                     'link', array(
1299                         'rel' => 'ostatus:attention',
1300                         'href' => $profile->getUri()
1301                     )
1302                 );
1303             }
1304         }
1305
1306         $groups = $this->getGroups();
1307
1308         foreach ($groups as $group) {
1309             $xs->element(
1310                 'link', array(
1311                     'rel' => 'ostatus:attention',
1312                     'href' => $group->permalink()
1313                 )
1314             );
1315         }
1316
1317         if (!empty($this->repeat_of)) {
1318             $repeat = Notice::staticGet('id', $this->repeat_of);
1319             if (!empty($repeat)) {
1320                 $xs->element(
1321                     'ostatus:forward',
1322                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1323                 );
1324             }
1325         }
1326
1327         $xs->element(
1328             'content',
1329             array('type' => 'html'),
1330             common_xml_safe_str($this->rendered)
1331         );
1332
1333         $tag = new Notice_tag();
1334         $tag->notice_id = $this->id;
1335         if ($tag->find()) {
1336             while ($tag->fetch()) {
1337                 $xs->element('category', array('term' => $tag->tag));
1338             }
1339         }
1340         $tag->free();
1341
1342         # Enclosures
1343         $attachments = $this->attachments();
1344         if($attachments){
1345             foreach($attachments as $attachment){
1346                 $enclosure=$attachment->getEnclosure();
1347                 if ($enclosure) {
1348                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1349                     if($enclosure->title){
1350                         $attributes['title']=$enclosure->title;
1351                     }
1352                     $xs->element('link', $attributes, null);
1353                 }
1354             }
1355         }
1356
1357         if (!empty($this->lat) && !empty($this->lon)) {
1358             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1359         }
1360
1361         $xs->elementEnd('entry');
1362
1363         return $xs->getString();
1364     }
1365
1366     /**
1367      * Returns an XML string fragment with a reference to a notice as an
1368      * Activity Streams noun object with the given element type.
1369      *
1370      * Assumes that 'activity' namespace has been previously defined.
1371      *
1372      * @param string $element one of 'subject', 'object', 'target'
1373      * @return string
1374      */
1375     function asActivityNoun($element)
1376     {
1377         $noun = ActivityObject::fromNotice($this);
1378         return $noun->asString('activity:' . $element);
1379     }
1380
1381     function bestUrl()
1382     {
1383         if (!empty($this->url)) {
1384             return $this->url;
1385         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1386             return $this->uri;
1387         } else {
1388             return common_local_url('shownotice',
1389                                     array('notice' => $this->id));
1390         }
1391     }
1392
1393     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1394     {
1395         $cache = common_memcache();
1396
1397         if (empty($cache) ||
1398             $since_id != 0 || $max_id != 0 ||
1399             is_null($limit) ||
1400             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1401             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1402                                                                       $max_id)));
1403         }
1404
1405         $idkey = common_cache_key($cachekey);
1406
1407         $idstr = $cache->get($idkey);
1408
1409         if ($idstr !== false) {
1410             // Cache hit! Woohoo!
1411             $window = explode(',', $idstr);
1412             $ids = array_slice($window, $offset, $limit);
1413             return $ids;
1414         }
1415
1416         $laststr = $cache->get($idkey.';last');
1417
1418         if ($laststr !== false) {
1419             $window = explode(',', $laststr);
1420             $last_id = $window[0];
1421             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1422                                                                           $last_id, 0, null)));
1423
1424             $new_window = array_merge($new_ids, $window);
1425
1426             $new_windowstr = implode(',', $new_window);
1427
1428             $result = $cache->set($idkey, $new_windowstr);
1429             $result = $cache->set($idkey . ';last', $new_windowstr);
1430
1431             $ids = array_slice($new_window, $offset, $limit);
1432
1433             return $ids;
1434         }
1435
1436         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1437                                                                      0, 0, null)));
1438
1439         $windowstr = implode(',', $window);
1440
1441         $result = $cache->set($idkey, $windowstr);
1442         $result = $cache->set($idkey . ';last', $windowstr);
1443
1444         $ids = array_slice($window, $offset, $limit);
1445
1446         return $ids;
1447     }
1448
1449     /**
1450      * Determine which notice, if any, a new notice is in reply to.
1451      *
1452      * For conversation tracking, we try to see where this notice fits
1453      * in the tree. Rough algorithm is:
1454      *
1455      * if (reply_to is set and valid) {
1456      *     return reply_to;
1457      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1458      *     return ID of last notice by initial @name in content;
1459      * }
1460      *
1461      * Note that all @nickname instances will still be used to save "reply" records,
1462      * so the notice shows up in the mentioned users' "replies" tab.
1463      *
1464      * @param integer $reply_to   ID passed in by Web or API
1465      * @param integer $profile_id ID of author
1466      * @param string  $source     Source tag, like 'web' or 'gwibber'
1467      * @param string  $content    Final notice content
1468      *
1469      * @return integer ID of replied-to notice, or null for not a reply.
1470      */
1471
1472     static function getReplyTo($reply_to, $profile_id, $source, $content)
1473     {
1474         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1475
1476         // If $reply_to is specified, we check that it exists, and then
1477         // return it if it does
1478
1479         if (!empty($reply_to)) {
1480             $reply_notice = Notice::staticGet('id', $reply_to);
1481             if (!empty($reply_notice)) {
1482                 return $reply_to;
1483             }
1484         }
1485
1486         // If it's not a "low bandwidth" source (one where you can't set
1487         // a reply_to argument), we return. This is mostly web and API
1488         // clients.
1489
1490         if (!in_array($source, $lb)) {
1491             return null;
1492         }
1493
1494         // Is there an initial @ or T?
1495
1496         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1497             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1498             $nickname = common_canonical_nickname($match[1]);
1499         } else {
1500             return null;
1501         }
1502
1503         // Figure out who that is.
1504
1505         $sender = Profile::staticGet('id', $profile_id);
1506         if (empty($sender)) {
1507             return null;
1508         }
1509
1510         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1511
1512         if (empty($recipient)) {
1513             return null;
1514         }
1515
1516         // Get their last notice
1517
1518         $last = $recipient->getCurrentNotice();
1519
1520         if (!empty($last)) {
1521             return $last->id;
1522         }
1523     }
1524
1525     static function maxContent()
1526     {
1527         $contentlimit = common_config('notice', 'contentlimit');
1528         // null => use global limit (distinct from 0!)
1529         if (is_null($contentlimit)) {
1530             $contentlimit = common_config('site', 'textlimit');
1531         }
1532         return $contentlimit;
1533     }
1534
1535     static function contentTooLong($content)
1536     {
1537         $contentlimit = self::maxContent();
1538         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1539     }
1540
1541     function getLocation()
1542     {
1543         $location = null;
1544
1545         if (!empty($this->location_id) && !empty($this->location_ns)) {
1546             $location = Location::fromId($this->location_id, $this->location_ns);
1547         }
1548
1549         if (is_null($location)) { // no ID, or Location::fromId() failed
1550             if (!empty($this->lat) && !empty($this->lon)) {
1551                 $location = Location::fromLatLon($this->lat, $this->lon);
1552             }
1553         }
1554
1555         return $location;
1556     }
1557
1558     function repeat($repeater_id, $source)
1559     {
1560         $author = Profile::staticGet('id', $this->profile_id);
1561
1562         // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
1563         // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
1564         $content = sprintf(_('RT @%1$s %2$s'),
1565                            $author->nickname,
1566                            $this->content);
1567
1568         $maxlen = common_config('site', 'textlimit');
1569         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1570             // Web interface and current Twitter API clients will
1571             // pull the original notice's text, but some older
1572             // clients and RSS/Atom feeds will see this trimmed text.
1573             //
1574             // Unfortunately this is likely to lose tags or URLs
1575             // at the end of long notices.
1576             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1577         }
1578
1579         return self::saveNew($repeater_id, $content, $source,
1580                              array('repeat_of' => $this->id));
1581     }
1582
1583     // These are supposed to be in chron order!
1584
1585     function repeatStream($limit=100)
1586     {
1587         $cache = common_memcache();
1588
1589         if (empty($cache)) {
1590             $ids = $this->_repeatStreamDirect($limit);
1591         } else {
1592             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1593             if ($idstr !== false) {
1594                 $ids = explode(',', $idstr);
1595             } else {
1596                 $ids = $this->_repeatStreamDirect(100);
1597                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1598             }
1599             if ($limit < 100) {
1600                 // We do a max of 100, so slice down to limit
1601                 $ids = array_slice($ids, 0, $limit);
1602             }
1603         }
1604
1605         return Notice::getStreamByIds($ids);
1606     }
1607
1608     function _repeatStreamDirect($limit)
1609     {
1610         $notice = new Notice();
1611
1612         $notice->selectAdd(); // clears it
1613         $notice->selectAdd('id');
1614
1615         $notice->repeat_of = $this->id;
1616
1617         $notice->orderBy('created'); // NB: asc!
1618
1619         if (!is_null($offset)) {
1620             $notice->limit($offset, $limit);
1621         }
1622
1623         $ids = array();
1624
1625         if ($notice->find()) {
1626             while ($notice->fetch()) {
1627                 $ids[] = $notice->id;
1628             }
1629         }
1630
1631         $notice->free();
1632         $notice = NULL;
1633
1634         return $ids;
1635     }
1636
1637     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1638     {
1639         $options = array();
1640
1641         if (!empty($location_id) && !empty($location_ns)) {
1642
1643             $options['location_id'] = $location_id;
1644             $options['location_ns'] = $location_ns;
1645
1646             $location = Location::fromId($location_id, $location_ns);
1647
1648             if (!empty($location)) {
1649                 $options['lat'] = $location->lat;
1650                 $options['lon'] = $location->lon;
1651             }
1652
1653         } else if (!empty($lat) && !empty($lon)) {
1654
1655             $options['lat'] = $lat;
1656             $options['lon'] = $lon;
1657
1658             $location = Location::fromLatLon($lat, $lon);
1659
1660             if (!empty($location)) {
1661                 $options['location_id'] = $location->location_id;
1662                 $options['location_ns'] = $location->location_ns;
1663             }
1664         } else if (!empty($profile)) {
1665
1666             if (isset($profile->lat) && isset($profile->lon)) {
1667                 $options['lat'] = $profile->lat;
1668                 $options['lon'] = $profile->lon;
1669             }
1670
1671             if (isset($profile->location_id) && isset($profile->location_ns)) {
1672                 $options['location_id'] = $profile->location_id;
1673                 $options['location_ns'] = $profile->location_ns;
1674             }
1675         }
1676
1677         return $options;
1678     }
1679
1680     function clearReplies()
1681     {
1682         $replyNotice = new Notice();
1683         $replyNotice->reply_to = $this->id;
1684
1685         //Null any notices that are replies to this notice
1686
1687         if ($replyNotice->find()) {
1688             while ($replyNotice->fetch()) {
1689                 $orig = clone($replyNotice);
1690                 $replyNotice->reply_to = null;
1691                 $replyNotice->update($orig);
1692             }
1693         }
1694
1695         // Reply records
1696
1697         $reply = new Reply();
1698         $reply->notice_id = $this->id;
1699
1700         if ($reply->find()) {
1701             while($reply->fetch()) {
1702                 self::blow('reply:stream:%d', $reply->profile_id);
1703                 $reply->delete();
1704             }
1705         }
1706
1707         $reply->free();
1708     }
1709
1710     function clearRepeats()
1711     {
1712         $repeatNotice = new Notice();
1713         $repeatNotice->repeat_of = $this->id;
1714
1715         //Null any notices that are repeats of this notice
1716
1717         if ($repeatNotice->find()) {
1718             while ($repeatNotice->fetch()) {
1719                 $orig = clone($repeatNotice);
1720                 $repeatNotice->repeat_of = null;
1721                 $repeatNotice->update($orig);
1722             }
1723         }
1724     }
1725
1726     function clearFaves()
1727     {
1728         $fave = new Fave();
1729         $fave->notice_id = $this->id;
1730
1731         if ($fave->find()) {
1732             while ($fave->fetch()) {
1733                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1734                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1735                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1736                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1737                 $fave->delete();
1738             }
1739         }
1740
1741         $fave->free();
1742     }
1743
1744     function clearTags()
1745     {
1746         $tag = new Notice_tag();
1747         $tag->notice_id = $this->id;
1748
1749         if ($tag->find()) {
1750             while ($tag->fetch()) {
1751                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1752                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1753                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1754                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1755                 $tag->delete();
1756             }
1757         }
1758
1759         $tag->free();
1760     }
1761
1762     function clearGroupInboxes()
1763     {
1764         $gi = new Group_inbox();
1765
1766         $gi->notice_id = $this->id;
1767
1768         if ($gi->find()) {
1769             while ($gi->fetch()) {
1770                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1771                 $gi->delete();
1772             }
1773         }
1774
1775         $gi->free();
1776     }
1777
1778     function distribute()
1779     {
1780         // We always insert for the author so they don't
1781         // have to wait
1782
1783         $user = User::staticGet('id', $this->profile_id);
1784         if (!empty($user)) {
1785             Inbox::insertNotice($user->id, $this->id);
1786         }
1787
1788         if (common_config('queue', 'inboxes')) {
1789             // If there's a failure, we want to _force_
1790             // distribution at this point.
1791             try {
1792                 $qm = QueueManager::get();
1793                 $qm->enqueue($this, 'distrib');
1794             } catch (Exception $e) {
1795                 // If the exception isn't transient, this
1796                 // may throw more exceptions as DQH does
1797                 // its own enqueueing. So, we ignore them!
1798                 try {
1799                     $handler = new DistribQueueHandler();
1800                     $handler->handle($this);
1801                 } catch (Exception $e) {
1802                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1803                 }
1804                 // Re-throw so somebody smarter can handle it.
1805                 throw $e;
1806             }
1807         } else {
1808             $handler = new DistribQueueHandler();
1809             $handler->handle($this);
1810         }
1811     }
1812
1813     function insert()
1814     {
1815         $result = parent::insert();
1816
1817         if ($result) {
1818             // Profile::hasRepeated() abuses pkeyGet(), so we
1819             // have to clear manually
1820             if (!empty($this->repeat_of)) {
1821                 $c = self::memcache();
1822                 if (!empty($c)) {
1823                     $ck = self::multicacheKey('Notice',
1824                                               array('profile_id' => $this->profile_id,
1825                                                     'repeat_of' => $this->repeat_of));
1826                     $c->delete($ck);
1827                 }
1828             }
1829         }
1830
1831         return $result;
1832     }
1833
1834     /**
1835      * Get the source of the notice
1836      *
1837      * @return Notice_source $ns A notice source object. 'code' is the only attribute
1838      *                           guaranteed to be populated.
1839      */
1840     function getSource()
1841     {
1842         $ns = new Notice_source();
1843         if (!empty($this->source)) {
1844             switch ($this->source) {
1845             case 'web':
1846             case 'xmpp':
1847             case 'mail':
1848             case 'omb':
1849             case 'system':
1850             case 'api':
1851                 $ns->code = $this->source;
1852                 break;
1853             default:
1854                 $ns = Notice_source::staticGet($this->source);
1855                 if (!$ns) {
1856                     $ns = new Notice_source();
1857                     $ns->code = $this->source;
1858                     $app = Oauth_application::staticGet('name', $this->source);
1859                     if ($app) {
1860                         $ns->name = $app->name;
1861                         $ns->url  = $app->source_url;
1862                     }
1863                 }
1864                 break;
1865             }
1866         }
1867         return $ns;
1868     }
1869
1870     /**
1871      * Determine whether the notice was locally created
1872      *
1873      * @return boolean locality
1874      */
1875
1876     public function isLocal()
1877     {
1878         return ($this->is_local == Notice::LOCAL_PUBLIC ||
1879                 $this->is_local == Notice::LOCAL_NONPUBLIC);
1880     }
1881
1882 }