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