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