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