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