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