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