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