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