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