]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Fix to make blowing of replies stream cache more consistent when receiving replies...
[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      * @param $groups array of Group *objects*
706      * @param $recipients array of profile *ids*
707      */
708     function whoGets($groups=null, $recipients=null)
709     {
710         $c = self::memcache();
711
712         if (!empty($c)) {
713             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
714             if ($ni !== false) {
715                 return $ni;
716             }
717         }
718
719         if (is_null($groups)) {
720             $groups = $this->getGroups();
721         }
722
723         if (is_null($recipients)) {
724             $recipients = $this->getReplies();
725         }
726
727         $users = $this->getSubscribedUsers();
728
729         // FIXME: kind of ignoring 'transitional'...
730         // we'll probably stop supporting inboxless mode
731         // in 0.9.x
732
733         $ni = array();
734
735         foreach ($users as $id) {
736             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
737         }
738
739         $profile = $this->getProfile();
740
741         foreach ($groups as $group) {
742             $users = $group->getUserMembers();
743             foreach ($users as $id) {
744                 if (!array_key_exists($id, $ni)) {
745                     $user = User::staticGet('id', $id);
746                     if (!$user->hasBlocked($profile)) {
747                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
748                     }
749                 }
750             }
751         }
752
753         foreach ($recipients as $recipient) {
754
755             if (!array_key_exists($recipient, $ni)) {
756                 $recipientUser = User::staticGet('id', $recipient);
757                 if (!empty($recipientUser)) {
758                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
759                 }
760             }
761         }
762
763         if (!empty($c)) {
764             // XXX: pack this data better
765             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
766         }
767
768         return $ni;
769     }
770
771     /**
772      * Adds this notice to the inboxes of each local user who should receive
773      * it, based on author subscriptions, group memberships, and @-replies.
774      *
775      * Warning: running a second time currently will make items appear
776      * multiple times in users' inboxes.
777      *
778      * @fixme make more robust against errors
779      * @fixme break up massive deliveries to smaller background tasks
780      *
781      * @param array $groups optional list of Group objects;
782      *              if left empty, will be loaded from group_inbox records
783      * @param array $recipient optional list of reply profile ids
784      *              if left empty, will be loaded from reply records
785      */
786     function addToInboxes($groups=null, $recipients=null)
787     {
788         $ni = $this->whoGets($groups, $recipients);
789
790         $ids = array_keys($ni);
791
792         // We remove the author (if they're a local user),
793         // since we'll have already done this in distribute()
794
795         $i = array_search($this->profile_id, $ids);
796
797         if ($i !== false) {
798             unset($ids[$i]);
799         }
800
801         // Bulk insert
802
803         Inbox::bulkInsert($this->id, $ids);
804
805         return;
806     }
807
808     function getSubscribedUsers()
809     {
810         $user = new User();
811
812         if(common_config('db','quote_identifiers'))
813           $user_table = '"user"';
814         else $user_table = 'user';
815
816         $qry =
817           'SELECT id ' .
818           'FROM '. $user_table .' JOIN subscription '.
819           'ON '. $user_table .'.id = subscription.subscriber ' .
820           'WHERE subscription.subscribed = %d ';
821
822         $user->query(sprintf($qry, $this->profile_id));
823
824         $ids = array();
825
826         while ($user->fetch()) {
827             $ids[] = $user->id;
828         }
829
830         $user->free();
831
832         return $ids;
833     }
834
835     /**
836      * Record this notice to the given group inboxes for delivery.
837      * Overrides the regular parsing of !group markup.
838      *
839      * @param string $group_ids
840      * @fixme might prefer URIs as identifiers, as for replies?
841      *        best with generalizations on user_group to support
842      *        remote groups better.
843      */
844     function saveKnownGroups($group_ids)
845     {
846         if (!is_array($group_ids)) {
847             throw new ServerException("Bad type provided to saveKnownGroups");
848         }
849
850         $groups = array();
851         foreach ($group_ids as $id) {
852             $group = User_group::staticGet('id', $id);
853             if ($group) {
854                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
855                 $result = $this->addToGroupInbox($group);
856                 if (!$result) {
857                     common_log_db_error($gi, 'INSERT', __FILE__);
858                 }
859
860                 // @fixme should we save the tags here or not?
861                 $groups[] = clone($group);
862             } else {
863                 common_log(LOG_ERR, "Local delivery to group id $id skipped, doesn't exist");
864             }
865         }
866
867         return $groups;
868     }
869
870     /**
871      * Parse !group delivery and record targets into group_inbox.
872      * @return array of Group objects
873      */
874     function saveGroups()
875     {
876         // Don't save groups for repeats
877
878         if (!empty($this->repeat_of)) {
879             return array();
880         }
881
882         $groups = array();
883
884         /* extract all !group */
885         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
886                                 strtolower($this->content),
887                                 $match);
888         if (!$count) {
889             return $groups;
890         }
891
892         $profile = $this->getProfile();
893
894         /* Add them to the database */
895
896         foreach (array_unique($match[1]) as $nickname) {
897             /* XXX: remote groups. */
898             $group = User_group::getForNickname($nickname, $profile);
899
900             if (empty($group)) {
901                 continue;
902             }
903
904             // we automatically add a tag for every group name, too
905
906             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
907                                              'notice_id' => $this->id));
908
909             if (is_null($tag)) {
910                 $this->saveTag($nickname);
911             }
912
913             if ($profile->isMember($group)) {
914
915                 $result = $this->addToGroupInbox($group);
916
917                 if (!$result) {
918                     common_log_db_error($gi, 'INSERT', __FILE__);
919                 }
920
921                 $groups[] = clone($group);
922             }
923         }
924
925         return $groups;
926     }
927
928     function addToGroupInbox($group)
929     {
930         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
931                                          'notice_id' => $this->id));
932
933         if (empty($gi)) {
934
935             $gi = new Group_inbox();
936
937             $gi->group_id  = $group->id;
938             $gi->notice_id = $this->id;
939             $gi->created   = $this->created;
940
941             $result = $gi->insert();
942
943             if (!$result) {
944                 common_log_db_error($gi, 'INSERT', __FILE__);
945                 throw new ServerException(_('Problem saving group inbox.'));
946             }
947
948             self::blow('user_group:notice_ids:%d', $gi->group_id);
949         }
950
951         return true;
952     }
953
954     /**
955      * Save reply records indicating that this notice needs to be
956      * delivered to the local users with the given URIs.
957      *
958      * Since this is expected to be used when saving foreign-sourced
959      * messages, we won't deliver to any remote targets as that's the
960      * source service's responsibility.
961      *
962      * Mail notifications etc will be handled later.
963      *
964      * @param array of unique identifier URIs for recipients
965      */
966     function saveKnownReplies($uris)
967     {
968         if (empty($uris)) {
969             return;
970         }
971         $sender = Profile::staticGet($this->profile_id);
972
973         foreach ($uris as $uri) {
974
975             $user = User::staticGet('uri', $uri);
976
977             if (!empty($user)) {
978                 if ($user->hasBlocked($sender)) {
979                     continue;
980                 }
981
982                 $reply = new Reply();
983
984                 $reply->notice_id  = $this->id;
985                 $reply->profile_id = $user->id;
986
987                 $id = $reply->insert();
988             }
989         }
990
991         return;
992     }
993
994     /**
995      * Pull @-replies from this message's content in StatusNet markup format
996      * and save reply records indicating that this message needs to be
997      * delivered to those users.
998      *
999      * Mail notifications to local profiles will be sent later.
1000      *
1001      * @return array of integer profile IDs
1002      */
1003
1004     function saveReplies()
1005     {
1006         // Don't save reply data for repeats
1007
1008         if (!empty($this->repeat_of)) {
1009             return array();
1010         }
1011
1012         $sender = Profile::staticGet($this->profile_id);
1013
1014         // @todo ideally this parser information would only
1015         // be calculated once.
1016
1017         $mentions = common_find_mentions($this->content, $this);
1018
1019         $replied = array();
1020
1021         // store replied only for first @ (what user/notice what the reply directed,
1022         // we assume first @ is it)
1023
1024         foreach ($mentions as $mention) {
1025
1026             foreach ($mention['mentioned'] as $mentioned) {
1027
1028                 // skip if they're already covered
1029
1030                 if (!empty($replied[$mentioned->id])) {
1031                     continue;
1032                 }
1033
1034                 // Don't save replies from blocked profile to local user
1035
1036                 $mentioned_user = User::staticGet('id', $mentioned->id);
1037                 if (!empty($mentioned_user) && $mentioned_user->hasBlocked($sender)) {
1038                     continue;
1039                 }
1040
1041                 $reply = new Reply();
1042
1043                 $reply->notice_id  = $this->id;
1044                 $reply->profile_id = $mentioned->id;
1045
1046                 $id = $reply->insert();
1047
1048                 if (!$id) {
1049                     common_log_db_error($reply, 'INSERT', __FILE__);
1050                     throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
1051                 } else {
1052                     $replied[$mentioned->id] = 1;
1053                     self::blow('reply:stream:%d', $mentioned->id);
1054                 }
1055             }
1056         }
1057
1058         $recipientIds = array_keys($replied);
1059
1060         return $recipientIds;
1061     }
1062
1063     /**
1064      * Pull the complete list of @-reply targets for this notice.
1065      *
1066      * @return array of integer profile ids
1067      */
1068     function getReplies()
1069     {
1070         // XXX: cache me
1071
1072         $ids = array();
1073
1074         $reply = new Reply();
1075         $reply->selectAdd();
1076         $reply->selectAdd('profile_id');
1077         $reply->notice_id = $this->id;
1078
1079         if ($reply->find()) {
1080             while($reply->fetch()) {
1081                 $ids[] = $reply->profile_id;
1082             }
1083         }
1084
1085         $reply->free();
1086
1087         return $ids;
1088     }
1089
1090     /**
1091      * Send e-mail notifications to local @-reply targets.
1092      *
1093      * Replies must already have been saved; this is expected to be run
1094      * from the distrib queue handler.
1095      */
1096     function sendReplyNotifications()
1097     {
1098         // Don't send reply notifications for repeats
1099
1100         if (!empty($this->repeat_of)) {
1101             return array();
1102         }
1103
1104         $recipientIds = $this->getReplies();
1105
1106         foreach ($recipientIds as $recipientId) {
1107             $user = User::staticGet('id', $recipientId);
1108             if (!empty($user)) {
1109                 mail_notify_attn($user, $this);
1110             }
1111         }
1112     }
1113
1114     /**
1115      * Pull list of groups this notice needs to be delivered to,
1116      * as previously recorded by saveGroups() or saveKnownGroups().
1117      *
1118      * @return array of Group objects
1119      */
1120     function getGroups()
1121     {
1122         // Don't save groups for repeats
1123
1124         if (!empty($this->repeat_of)) {
1125             return array();
1126         }
1127
1128         // XXX: cache me
1129
1130         $groups = array();
1131
1132         $gi = new Group_inbox();
1133
1134         $gi->selectAdd();
1135         $gi->selectAdd('group_id');
1136
1137         $gi->notice_id = $this->id;
1138
1139         if ($gi->find()) {
1140             while ($gi->fetch()) {
1141                 $group = User_group::staticGet('id', $gi->group_id);
1142                 if ($group) {
1143                     $groups[] = $group;
1144                 }
1145             }
1146         }
1147
1148         $gi->free();
1149
1150         return $groups;
1151     }
1152
1153     function asAtomEntry($namespace=false, $source=false, $author=true)
1154     {
1155         $profile = $this->getProfile();
1156
1157         $xs = new XMLStringer(true);
1158
1159         if ($namespace) {
1160             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1161                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
1162                            'xmlns:georss' => 'http://www.georss.org/georss',
1163                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
1164                            'xmlns:media' => 'http://purl.org/syndication/atommedia',
1165                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
1166                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0');
1167         } else {
1168             $attrs = array();
1169         }
1170
1171         $xs->elementStart('entry', $attrs);
1172
1173         if ($source) {
1174             $xs->elementStart('source');
1175             $xs->element('id', null, $profile->profileurl);
1176             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1177             $xs->element('link', array('href' => $profile->profileurl));
1178             $user = User::staticGet('id', $profile->id);
1179             if (!empty($user)) {
1180                 $atom_feed = common_local_url('ApiTimelineUser',
1181                                               array('format' => 'atom',
1182                                                     'id' => $profile->nickname));
1183                 $xs->element('link', array('rel' => 'self',
1184                                            'type' => 'application/atom+xml',
1185                                            'href' => $profile->profileurl));
1186                 $xs->element('link', array('rel' => 'license',
1187                                            'href' => common_config('license', 'url')));
1188             }
1189
1190             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1191             $xs->element('updated', null, common_date_w3dtf($this->created));
1192         }
1193
1194         if ($source) {
1195             $xs->elementEnd('source');
1196         }
1197
1198         $xs->element('title', null, common_xml_safe_str($this->content));
1199
1200         if ($author) {
1201             $xs->raw($profile->asAtomAuthor());
1202             $xs->raw($profile->asActivityActor());
1203         }
1204
1205         $xs->element('link', array('rel' => 'alternate',
1206                                    'type' => 'text/html',
1207                                    'href' => $this->bestUrl()));
1208
1209         $xs->element('id', null, $this->uri);
1210
1211         $xs->element('published', null, common_date_w3dtf($this->created));
1212         $xs->element('updated', null, common_date_w3dtf($this->created));
1213
1214         if ($this->reply_to) {
1215             $reply_notice = Notice::staticGet('id', $this->reply_to);
1216             if (!empty($reply_notice)) {
1217                 $xs->element('link', array('rel' => 'related',
1218                                            'href' => $reply_notice->bestUrl()));
1219                 $xs->element('thr:in-reply-to',
1220                              array('ref' => $reply_notice->uri,
1221                                    'href' => $reply_notice->bestUrl()));
1222             }
1223         }
1224
1225         if (!empty($this->conversation)) {
1226
1227             $conv = Conversation::staticGet('id', $this->conversation);
1228
1229             if (!empty($conv)) {
1230                 $xs->element(
1231                     'link', array(
1232                         'rel' => 'ostatus:conversation',
1233                         'href' => $conv->uri
1234                     )
1235                 );
1236             }
1237         }
1238
1239         $reply_ids = $this->getReplies();
1240
1241         foreach ($reply_ids as $id) {
1242             $profile = Profile::staticGet('id', $id);
1243            if (!empty($profile)) {
1244                 $xs->element(
1245                     'link', array(
1246                         'rel' => 'ostatus:attention',
1247                         'href' => $profile->getUri()
1248                     )
1249                 );
1250             }
1251         }
1252
1253         $groups = $this->getGroups();
1254
1255         foreach ($groups as $group) {
1256             $xs->element(
1257                 'link', array(
1258                     'rel' => 'ostatus:attention',
1259                     'href' => $group->permalink()
1260                 )
1261             );
1262         }
1263
1264         if (!empty($this->repeat_of)) {
1265             $repeat = Notice::staticGet('id', $this->repeat_of);
1266             if (!empty($repeat)) {
1267                 $xs->element(
1268                     'ostatus:forward',
1269                      array('ref' => $repeat->uri, 'href' => $repeat->bestUrl())
1270                 );
1271             }
1272         }
1273
1274         $xs->element(
1275             'content',
1276             array('type' => 'html'),
1277             common_xml_safe_str($this->rendered)
1278         );
1279
1280         $tag = new Notice_tag();
1281         $tag->notice_id = $this->id;
1282         if ($tag->find()) {
1283             while ($tag->fetch()) {
1284                 $xs->element('category', array('term' => $tag->tag));
1285             }
1286         }
1287         $tag->free();
1288
1289         # Enclosures
1290         $attachments = $this->attachments();
1291         if($attachments){
1292             foreach($attachments as $attachment){
1293                 $enclosure=$attachment->getEnclosure();
1294                 if ($enclosure) {
1295                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1296                     if($enclosure->title){
1297                         $attributes['title']=$enclosure->title;
1298                     }
1299                     $xs->element('link', $attributes, null);
1300                 }
1301             }
1302         }
1303
1304         if (!empty($this->lat) && !empty($this->lon)) {
1305             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1306         }
1307
1308         $xs->elementEnd('entry');
1309
1310         return $xs->getString();
1311     }
1312
1313     /**
1314      * Returns an XML string fragment with a reference to a notice as an
1315      * Activity Streams noun object with the given element type.
1316      *
1317      * Assumes that 'activity' namespace has been previously defined.
1318      *
1319      * @param string $element one of 'subject', 'object', 'target'
1320      * @return string
1321      */
1322     function asActivityNoun($element)
1323     {
1324         $noun = ActivityObject::fromNotice($this);
1325         return $noun->asString('activity:' . $element);
1326     }
1327
1328     function bestUrl()
1329     {
1330         if (!empty($this->url)) {
1331             return $this->url;
1332         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1333             return $this->uri;
1334         } else {
1335             return common_local_url('shownotice',
1336                                     array('notice' => $this->id));
1337         }
1338     }
1339
1340     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
1341     {
1342         $cache = common_memcache();
1343
1344         if (empty($cache) ||
1345             $since_id != 0 || $max_id != 0 ||
1346             is_null($limit) ||
1347             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1348             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1349                                                                       $max_id)));
1350         }
1351
1352         $idkey = common_cache_key($cachekey);
1353
1354         $idstr = $cache->get($idkey);
1355
1356         if ($idstr !== false) {
1357             // Cache hit! Woohoo!
1358             $window = explode(',', $idstr);
1359             $ids = array_slice($window, $offset, $limit);
1360             return $ids;
1361         }
1362
1363         $laststr = $cache->get($idkey.';last');
1364
1365         if ($laststr !== false) {
1366             $window = explode(',', $laststr);
1367             $last_id = $window[0];
1368             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1369                                                                           $last_id, 0, null)));
1370
1371             $new_window = array_merge($new_ids, $window);
1372
1373             $new_windowstr = implode(',', $new_window);
1374
1375             $result = $cache->set($idkey, $new_windowstr);
1376             $result = $cache->set($idkey . ';last', $new_windowstr);
1377
1378             $ids = array_slice($new_window, $offset, $limit);
1379
1380             return $ids;
1381         }
1382
1383         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1384                                                                      0, 0, null)));
1385
1386         $windowstr = implode(',', $window);
1387
1388         $result = $cache->set($idkey, $windowstr);
1389         $result = $cache->set($idkey . ';last', $windowstr);
1390
1391         $ids = array_slice($window, $offset, $limit);
1392
1393         return $ids;
1394     }
1395
1396     /**
1397      * Determine which notice, if any, a new notice is in reply to.
1398      *
1399      * For conversation tracking, we try to see where this notice fits
1400      * in the tree. Rough algorithm is:
1401      *
1402      * if (reply_to is set and valid) {
1403      *     return reply_to;
1404      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1405      *     return ID of last notice by initial @name in content;
1406      * }
1407      *
1408      * Note that all @nickname instances will still be used to save "reply" records,
1409      * so the notice shows up in the mentioned users' "replies" tab.
1410      *
1411      * @param integer $reply_to   ID passed in by Web or API
1412      * @param integer $profile_id ID of author
1413      * @param string  $source     Source tag, like 'web' or 'gwibber'
1414      * @param string  $content    Final notice content
1415      *
1416      * @return integer ID of replied-to notice, or null for not a reply.
1417      */
1418
1419     static function getReplyTo($reply_to, $profile_id, $source, $content)
1420     {
1421         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1422
1423         // If $reply_to is specified, we check that it exists, and then
1424         // return it if it does
1425
1426         if (!empty($reply_to)) {
1427             $reply_notice = Notice::staticGet('id', $reply_to);
1428             if (!empty($reply_notice)) {
1429                 return $reply_to;
1430             }
1431         }
1432
1433         // If it's not a "low bandwidth" source (one where you can't set
1434         // a reply_to argument), we return. This is mostly web and API
1435         // clients.
1436
1437         if (!in_array($source, $lb)) {
1438             return null;
1439         }
1440
1441         // Is there an initial @ or T?
1442
1443         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1444             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1445             $nickname = common_canonical_nickname($match[1]);
1446         } else {
1447             return null;
1448         }
1449
1450         // Figure out who that is.
1451
1452         $sender = Profile::staticGet('id', $profile_id);
1453         if (empty($sender)) {
1454             return null;
1455         }
1456
1457         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1458
1459         if (empty($recipient)) {
1460             return null;
1461         }
1462
1463         // Get their last notice
1464
1465         $last = $recipient->getCurrentNotice();
1466
1467         if (!empty($last)) {
1468             return $last->id;
1469         }
1470     }
1471
1472     static function maxContent()
1473     {
1474         $contentlimit = common_config('notice', 'contentlimit');
1475         // null => use global limit (distinct from 0!)
1476         if (is_null($contentlimit)) {
1477             $contentlimit = common_config('site', 'textlimit');
1478         }
1479         return $contentlimit;
1480     }
1481
1482     static function contentTooLong($content)
1483     {
1484         $contentlimit = self::maxContent();
1485         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1486     }
1487
1488     function getLocation()
1489     {
1490         $location = null;
1491
1492         if (!empty($this->location_id) && !empty($this->location_ns)) {
1493             $location = Location::fromId($this->location_id, $this->location_ns);
1494         }
1495
1496         if (is_null($location)) { // no ID, or Location::fromId() failed
1497             if (!empty($this->lat) && !empty($this->lon)) {
1498                 $location = Location::fromLatLon($this->lat, $this->lon);
1499             }
1500         }
1501
1502         return $location;
1503     }
1504
1505     function repeat($repeater_id, $source)
1506     {
1507         $author = Profile::staticGet('id', $this->profile_id);
1508
1509         $content = sprintf(_('RT @%1$s %2$s'),
1510                            $author->nickname,
1511                            $this->content);
1512
1513         $maxlen = common_config('site', 'textlimit');
1514         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1515             // Web interface and current Twitter API clients will
1516             // pull the original notice's text, but some older
1517             // clients and RSS/Atom feeds will see this trimmed text.
1518             //
1519             // Unfortunately this is likely to lose tags or URLs
1520             // at the end of long notices.
1521             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1522         }
1523
1524         return self::saveNew($repeater_id, $content, $source,
1525                              array('repeat_of' => $this->id));
1526     }
1527
1528     // These are supposed to be in chron order!
1529
1530     function repeatStream($limit=100)
1531     {
1532         $cache = common_memcache();
1533
1534         if (empty($cache)) {
1535             $ids = $this->_repeatStreamDirect($limit);
1536         } else {
1537             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1538             if ($idstr !== false) {
1539                 $ids = explode(',', $idstr);
1540             } else {
1541                 $ids = $this->_repeatStreamDirect(100);
1542                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1543             }
1544             if ($limit < 100) {
1545                 // We do a max of 100, so slice down to limit
1546                 $ids = array_slice($ids, 0, $limit);
1547             }
1548         }
1549
1550         return Notice::getStreamByIds($ids);
1551     }
1552
1553     function _repeatStreamDirect($limit)
1554     {
1555         $notice = new Notice();
1556
1557         $notice->selectAdd(); // clears it
1558         $notice->selectAdd('id');
1559
1560         $notice->repeat_of = $this->id;
1561
1562         $notice->orderBy('created'); // NB: asc!
1563
1564         if (!is_null($offset)) {
1565             $notice->limit($offset, $limit);
1566         }
1567
1568         $ids = array();
1569
1570         if ($notice->find()) {
1571             while ($notice->fetch()) {
1572                 $ids[] = $notice->id;
1573             }
1574         }
1575
1576         $notice->free();
1577         $notice = NULL;
1578
1579         return $ids;
1580     }
1581
1582     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1583     {
1584         $options = array();
1585
1586         if (!empty($location_id) && !empty($location_ns)) {
1587
1588             $options['location_id'] = $location_id;
1589             $options['location_ns'] = $location_ns;
1590
1591             $location = Location::fromId($location_id, $location_ns);
1592
1593             if (!empty($location)) {
1594                 $options['lat'] = $location->lat;
1595                 $options['lon'] = $location->lon;
1596             }
1597
1598         } else if (!empty($lat) && !empty($lon)) {
1599
1600             $options['lat'] = $lat;
1601             $options['lon'] = $lon;
1602
1603             $location = Location::fromLatLon($lat, $lon);
1604
1605             if (!empty($location)) {
1606                 $options['location_id'] = $location->location_id;
1607                 $options['location_ns'] = $location->location_ns;
1608             }
1609         } else if (!empty($profile)) {
1610
1611             if (isset($profile->lat) && isset($profile->lon)) {
1612                 $options['lat'] = $profile->lat;
1613                 $options['lon'] = $profile->lon;
1614             }
1615
1616             if (isset($profile->location_id) && isset($profile->location_ns)) {
1617                 $options['location_id'] = $profile->location_id;
1618                 $options['location_ns'] = $profile->location_ns;
1619             }
1620         }
1621
1622         return $options;
1623     }
1624
1625     function clearReplies()
1626     {
1627         $replyNotice = new Notice();
1628         $replyNotice->reply_to = $this->id;
1629
1630         //Null any notices that are replies to this notice
1631
1632         if ($replyNotice->find()) {
1633             while ($replyNotice->fetch()) {
1634                 $orig = clone($replyNotice);
1635                 $replyNotice->reply_to = null;
1636                 $replyNotice->update($orig);
1637             }
1638         }
1639
1640         // Reply records
1641
1642         $reply = new Reply();
1643         $reply->notice_id = $this->id;
1644
1645         if ($reply->find()) {
1646             while($reply->fetch()) {
1647                 self::blow('reply:stream:%d', $reply->profile_id);
1648                 $reply->delete();
1649             }
1650         }
1651
1652         $reply->free();
1653     }
1654
1655     function clearRepeats()
1656     {
1657         $repeatNotice = new Notice();
1658         $repeatNotice->repeat_of = $this->id;
1659
1660         //Null any notices that are repeats of this notice
1661
1662         if ($repeatNotice->find()) {
1663             while ($repeatNotice->fetch()) {
1664                 $orig = clone($repeatNotice);
1665                 $repeatNotice->repeat_of = null;
1666                 $repeatNotice->update($orig);
1667             }
1668         }
1669     }
1670
1671     function clearFaves()
1672     {
1673         $fave = new Fave();
1674         $fave->notice_id = $this->id;
1675
1676         if ($fave->find()) {
1677             while ($fave->fetch()) {
1678                 self::blow('fave:ids_by_user_own:%d', $fave->user_id);
1679                 self::blow('fave:ids_by_user_own:%d;last', $fave->user_id);
1680                 self::blow('fave:ids_by_user:%d', $fave->user_id);
1681                 self::blow('fave:ids_by_user:%d;last', $fave->user_id);
1682                 $fave->delete();
1683             }
1684         }
1685
1686         $fave->free();
1687     }
1688
1689     function clearTags()
1690     {
1691         $tag = new Notice_tag();
1692         $tag->notice_id = $this->id;
1693
1694         if ($tag->find()) {
1695             while ($tag->fetch()) {
1696                 self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
1697                 self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
1698                 self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
1699                 self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
1700                 $tag->delete();
1701             }
1702         }
1703
1704         $tag->free();
1705     }
1706
1707     function clearGroupInboxes()
1708     {
1709         $gi = new Group_inbox();
1710
1711         $gi->notice_id = $this->id;
1712
1713         if ($gi->find()) {
1714             while ($gi->fetch()) {
1715                 self::blow('user_group:notice_ids:%d', $gi->group_id);
1716                 $gi->delete();
1717             }
1718         }
1719
1720         $gi->free();
1721     }
1722
1723     function distribute()
1724     {
1725         // We always insert for the author so they don't
1726         // have to wait
1727
1728         $user = User::staticGet('id', $this->profile_id);
1729         if (!empty($user)) {
1730             Inbox::insertNotice($user->id, $this->id);
1731         }
1732
1733         if (common_config('queue', 'inboxes')) {
1734             // If there's a failure, we want to _force_
1735             // distribution at this point.
1736             try {
1737                 $qm = QueueManager::get();
1738                 $qm->enqueue($this, 'distrib');
1739             } catch (Exception $e) {
1740                 // If the exception isn't transient, this
1741                 // may throw more exceptions as DQH does
1742                 // its own enqueueing. So, we ignore them!
1743                 try {
1744                     $handler = new DistribQueueHandler();
1745                     $handler->handle($this);
1746                 } catch (Exception $e) {
1747                     common_log(LOG_ERR, "emergency redistribution resulted in " . $e->getMessage());
1748                 }
1749                 // Re-throw so somebody smarter can handle it.
1750                 throw $e;
1751             }
1752         } else {
1753             $handler = new DistribQueueHandler();
1754             $handler->handle($this);
1755         }
1756     }
1757
1758     function insert()
1759     {
1760         $result = parent::insert();
1761
1762         if ($result) {
1763             // Profile::hasRepeated() abuses pkeyGet(), so we
1764             // have to clear manually
1765             if (!empty($this->repeat_of)) {
1766                 $c = self::memcache();
1767                 if (!empty($c)) {
1768                     $ck = self::multicacheKey('Notice',
1769                                               array('profile_id' => $this->profile_id,
1770                                                     'repeat_of' => $this->repeat_of));
1771                     $c->delete($ck);
1772                 }
1773             }
1774         }
1775
1776         return $result;
1777     }
1778 }