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