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