]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Notice.php
Merge branch '0.9.x' of git@gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / classes / Notice.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  *
19  * @category Notices
20  * @package  StatusNet
21  * @author   Brenda Wallace <shiny@cpan.org>
22  * @author   Christopher Vollick <psycotica0@gmail.com>
23  * @author   CiaranG <ciaran@ciarang.com>
24  * @author   Craig Andrews <candrews@integralblue.com>
25  * @author   Evan Prodromou <evan@controlezvous.ca>
26  * @author   Gina Haeussge <osd@foosel.net>
27  * @author   Jeffery To <jeffery.to@gmail.com>
28  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author   Robin Millette <millette@controlyourself.ca>
30  * @author   Sarven Capadisli <csarven@controlyourself.ca>
31  * @author   Tom Adams <tom@holizz.com>
32  * @license  GNU Affero General Public License http://www.gnu.org/licenses/
33  */
34
35 if (!defined('STATUSNET') && !defined('LACONICA')) {
36     exit(1);
37 }
38
39 /**
40  * Table Definition for notice
41  */
42 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
43
44 /* We keep the first three 20-notice pages, plus one for pagination check,
45  * in the memcached cache. */
46
47 define('NOTICE_CACHE_WINDOW', 61);
48
49 define('MAX_BOXCARS', 128);
50
51 class Notice extends Memcached_DataObject
52 {
53     ###START_AUTOCODE
54     /* the code below is auto generated do not remove the above tag */
55
56     public $__table = 'notice';                          // table name
57     public $id;                              // int(4)  primary_key not_null
58     public $profile_id;                      // int(4)  multiple_key not_null
59     public $uri;                             // varchar(255)  unique_key
60     public $content;                         // text
61     public $rendered;                        // text
62     public $url;                             // varchar(255)
63     public $created;                         // datetime  multiple_key not_null default_0000-00-00%2000%3A00%3A00
64     public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
65     public $reply_to;                        // int(4)
66     public $is_local;                        // int(4)
67     public $source;                          // varchar(32)
68     public $conversation;                    // int(4)
69     public $lat;                             // decimal(10,7)
70     public $lon;                             // decimal(10,7)
71     public $location_id;                     // int(4)
72     public $location_ns;                     // int(4)
73     public $repeat_of;                       // int(4)
74
75     /* Static get */
76     function staticGet($k,$v=NULL)
77     {
78         return Memcached_DataObject::staticGet('Notice',$k,$v);
79     }
80
81     /* the code above is auto generated do not remove the tag below */
82     ###END_AUTOCODE
83
84     /* Notice types */
85     const LOCAL_PUBLIC    =  1;
86     const REMOTE_OMB      =  0;
87     const LOCAL_NONPUBLIC = -1;
88     const GATEWAY         = -2;
89
90     function getProfile()
91     {
92         return Profile::staticGet('id', $this->profile_id);
93     }
94
95     function delete()
96     {
97         $this->blowCaches(true);
98         $this->blowFavesCache(true);
99         $this->blowSubsCache(true);
100
101         // For auditing purposes, save a record that the notice
102         // was deleted.
103
104         $deleted = new Deleted_notice();
105
106         $deleted->id         = $this->id;
107         $deleted->profile_id = $this->profile_id;
108         $deleted->uri        = $this->uri;
109         $deleted->created    = $this->created;
110         $deleted->deleted    = common_sql_now();
111
112         $this->query('BEGIN');
113
114         $deleted->insert();
115
116         //Null any notices that are replies to this notice
117         $this->query(sprintf("UPDATE notice set reply_to = null WHERE reply_to = %d", $this->id));
118
119         //Null any notices that are repeats of this notice
120         //XXX: probably need to uncache these, too
121
122         $this->query(sprintf("UPDATE notice set repeat_of = null WHERE repeat_of = %d", $this->id));
123
124         $related = array('Reply',
125                          'Fave',
126                          'Notice_tag',
127                          'Group_inbox',
128                          'Queue_item');
129
130         foreach ($related as $cls) {
131             $inst = new $cls();
132             $inst->notice_id = $this->id;
133             $inst->delete();
134         }
135         $result = parent::delete();
136         $this->query('COMMIT');
137     }
138
139     function saveTags()
140     {
141         /* extract all #hastags */
142         $count = preg_match_all('/(?:^|\s)#([\pL\pN_\-\.]{1,64})/', strtolower($this->content), $match);
143         if (!$count) {
144             return true;
145         }
146
147         //turn each into their canonical tag
148         //this is needed to remove dupes before saving e.g. #hash.tag = #hashtag
149         $hashtags = array();
150         for($i=0; $i<count($match[1]); $i++) {
151             $hashtags[] = common_canonical_tag($match[1][$i]);
152         }
153
154         /* Add them to the database */
155         foreach(array_unique($hashtags) as $hashtag) {
156             /* elide characters we don't want in the tag */
157             $this->saveTag($hashtag);
158         }
159         return true;
160     }
161
162     function saveTag($hashtag)
163     {
164         $tag = new Notice_tag();
165         $tag->notice_id = $this->id;
166         $tag->tag = $hashtag;
167         $tag->created = $this->created;
168         $id = $tag->insert();
169
170         if (!$id) {
171             throw new ServerException(sprintf(_('DB error inserting hashtag: %s'),
172                                               $last_error->message));
173             return;
174         }
175     }
176
177     /**
178      * Save a new notice and push it out to subscribers' inboxes.
179      * Poster's permissions are checked before sending.
180      *
181      * @param int $profile_id Profile ID of the poster
182      * @param string $content source message text; links may be shortened
183      *                        per current user's preference
184      * @param string $source source key ('web', 'api', etc)
185      * @param array $options Associative array of optional properties:
186      *              string 'created' timestamp of notice; defaults to now
187      *              int 'is_local' source/gateway ID, one of:
188      *                  Notice::LOCAL_PUBLIC    - Local, ok to appear in public timeline
189      *                  Notice::REMOTE_OMB      - Sent from a remote OMB service;
190      *                                            hide from public timeline but show in
191      *                                            local "and friends" timelines
192      *                  Notice::LOCAL_NONPUBLIC - Local, but hide from public timeline
193      *                  Notice::GATEWAY         - From another non-OMB service;
194      *                                            will not appear in public views
195      *              float 'lat' decimal latitude for geolocation
196      *              float 'lon' decimal longitude for geolocation
197      *              int 'location_id' geoname identifier
198      *              int 'location_ns' geoname namespace to interpret location_id
199      *              int 'reply_to'; notice ID this is a reply to
200      *              int 'repeat_of'; notice ID this is a repeat of
201      *              string 'uri' permalink to notice; defaults to local notice URL
202      *
203      * @return Notice
204      * @throws ClientException
205      */
206     static function saveNew($profile_id, $content, $source, $options=null) {
207         $defaults = array('uri' => null,
208                           'reply_to' => null,
209                           'repeat_of' => null);
210
211         if (!empty($options)) {
212             $options = $options + $defaults;
213             extract($options);
214         }
215
216         if (!isset($is_local)) {
217             $is_local = Notice::LOCAL_PUBLIC;
218         }
219
220         $profile = Profile::staticGet($profile_id);
221
222         $final = common_shorten_links($content);
223
224         if (Notice::contentTooLong($final)) {
225             throw new ClientException(_('Problem saving notice. Too long.'));
226         }
227
228         if (empty($profile)) {
229             throw new ClientException(_('Problem saving notice. Unknown user.'));
230         }
231
232         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
233             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
234             throw new ClientException(_('Too many notices too fast; take a breather '.
235                                         'and post again in a few minutes.'));
236         }
237
238         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
239             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
240             throw new ClientException(_('Too many duplicate messages too quickly;'.
241                                         ' take a breather and post again in a few minutes.'));
242         }
243
244         if (!$profile->hasRight(Right::NEWNOTICE)) {
245             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
246             throw new ClientException(_('You are banned from posting notices on this site.'));
247         }
248
249         $notice = new Notice();
250         $notice->profile_id = $profile_id;
251
252         $autosource = common_config('public', 'autosource');
253
254         # Sandboxed are non-false, but not 1, either
255
256         if (!$profile->hasRight(Right::PUBLICNOTICE) ||
257             ($source && $autosource && in_array($source, $autosource))) {
258             $notice->is_local = Notice::LOCAL_NONPUBLIC;
259         } else {
260             $notice->is_local = $is_local;
261         }
262
263         if (!empty($created)) {
264             $notice->created = $created;
265         } else {
266             $notice->created = common_sql_now();
267         }
268
269         $notice->content = $final;
270         $notice->rendered = common_render_content($final, $notice);
271         $notice->source = $source;
272         $notice->uri = $uri;
273
274         // Handle repeat case
275
276         if (isset($repeat_of)) {
277             $notice->repeat_of = $repeat_of;
278         } else {
279             $notice->reply_to = self::getReplyTo($reply_to, $profile_id, $source, $final);
280         }
281
282         if (!empty($notice->reply_to)) {
283             $reply = Notice::staticGet('id', $notice->reply_to);
284             $notice->conversation = $reply->conversation;
285         }
286
287         if (!empty($lat) && !empty($lon)) {
288             $notice->lat = $lat;
289             $notice->lon = $lon;
290         }
291
292         if (!empty($location_ns) && !empty($location_id)) {
293             $notice->location_id = $location_id;
294             $notice->location_ns = $location_ns;
295         }
296
297         if (Event::handle('StartNoticeSave', array(&$notice))) {
298
299             // XXX: some of these functions write to the DB
300
301             $id = $notice->insert();
302
303             if (!$id) {
304                 common_log_db_error($notice, 'INSERT', __FILE__);
305                 throw new ServerException(_('Problem saving notice.'));
306             }
307
308             // Update ID-dependent columns: URI, conversation
309
310             $orig = clone($notice);
311
312             $changed = false;
313
314             if (empty($uri)) {
315                 $notice->uri = common_notice_uri($notice);
316                 $changed = true;
317             }
318
319             // If it's not part of a conversation, it's
320             // the beginning of a new conversation.
321
322             if (empty($notice->conversation)) {
323                 $notice->conversation = $notice->id;
324                 $changed = true;
325             }
326
327             if ($changed) {
328                 if (!$notice->update($orig)) {
329                     common_log_db_error($notice, 'UPDATE', __FILE__);
330                     throw new ServerException(_('Problem saving notice.'));
331                 }
332             }
333
334             // XXX: do we need to change this for remote users?
335
336             $notice->saveTags();
337
338             $notice->addToInboxes();
339
340             $notice->saveUrls();
341
342             Event::handle('EndNoticeSave', array($notice));
343         }
344
345         # Clear the cache for subscribed users, so they'll update at next request
346         # XXX: someone clever could prepend instead of clearing the cache
347
348         $notice->blowCaches();
349
350         return $notice;
351     }
352
353     /** save all urls in the notice to the db
354      *
355      * follow redirects and save all available file information
356      * (mimetype, date, size, oembed, etc.)
357      *
358      * @return void
359      */
360     function saveUrls() {
361         common_replace_urls_callback($this->content, array($this, 'saveUrl'), $this->id);
362     }
363
364     function saveUrl($data) {
365         list($url, $notice_id) = $data;
366         File::processNew($url, $notice_id);
367     }
368
369     static function checkDupes($profile_id, $content) {
370         $profile = Profile::staticGet($profile_id);
371         if (empty($profile)) {
372             return false;
373         }
374         $notice = $profile->getNotices(0, NOTICE_CACHE_WINDOW);
375         if (!empty($notice)) {
376             $last = 0;
377             while ($notice->fetch()) {
378                 if (time() - strtotime($notice->created) >= common_config('site', 'dupelimit')) {
379                     return true;
380                 } else if ($notice->content == $content) {
381                     return false;
382                 }
383             }
384         }
385         # If we get here, oldest item in cache window is not
386         # old enough for dupe limit; do direct check against DB
387         $notice = new Notice();
388         $notice->profile_id = $profile_id;
389         $notice->content = $content;
390         if (common_config('db','type') == 'pgsql')
391           $notice->whereAdd('extract(epoch from now() - created) < ' . common_config('site', 'dupelimit'));
392         else
393           $notice->whereAdd('now() - created < ' . common_config('site', 'dupelimit'));
394
395         $cnt = $notice->count();
396         return ($cnt == 0);
397     }
398
399     static function checkEditThrottle($profile_id) {
400         $profile = Profile::staticGet($profile_id);
401         if (empty($profile)) {
402             return false;
403         }
404         # Get the Nth notice
405         $notice = $profile->getNotices(common_config('throttle', 'count') - 1, 1);
406         if ($notice && $notice->fetch()) {
407             # If the Nth notice was posted less than timespan seconds ago
408             if (time() - strtotime($notice->created) <= common_config('throttle', 'timespan')) {
409                 # Then we throttle
410                 return false;
411             }
412         }
413         # Either not N notices in the stream, OR the Nth was not posted within timespan seconds
414         return true;
415     }
416
417     function getUploadedAttachment() {
418         $post = clone $this;
419         $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"';
420         $post->query($query);
421         $post->fetch();
422         if (empty($post->up) || empty($post->i)) {
423             $ret = false;
424         } else {
425             $ret = array($post->up, $post->i);
426         }
427         $post->free();
428         return $ret;
429     }
430
431     function hasAttachments() {
432         $post = clone $this;
433         $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);
434         $post->query($query);
435         $post->fetch();
436         $n_attachments = intval($post->n_attachments);
437         $post->free();
438         return $n_attachments;
439     }
440
441     function attachments() {
442         // XXX: cache this
443         $att = array();
444         $f2p = new File_to_post;
445         $f2p->post_id = $this->id;
446         if ($f2p->find()) {
447             while ($f2p->fetch()) {
448                 $f = File::staticGet($f2p->file_id);
449                 $att[] = clone($f);
450             }
451         }
452         return $att;
453     }
454
455     function blowCaches($blowLast=false)
456     {
457         $this->blowSubsCache($blowLast);
458         $this->blowNoticeCache($blowLast);
459         $this->blowRepliesCache($blowLast);
460         $this->blowPublicCache($blowLast);
461         $this->blowTagCache($blowLast);
462         $this->blowGroupCache($blowLast);
463         $this->blowConversationCache($blowLast);
464         $this->blowRepeatCache();
465         $profile = Profile::staticGet($this->profile_id);
466         $profile->blowNoticeCount();
467     }
468
469     function blowRepeatCache()
470     {
471         if (!empty($this->repeat_of)) {
472             $cache = common_memcache();
473             if (!empty($cache)) {
474                 // XXX: only blow if <100 in cache
475                 $ck = common_cache_key('notice:repeats:'.$this->repeat_of);
476                 $result = $cache->delete($ck);
477
478                 $user = User::staticGet('id', $this->profile_id);
479
480                 if (!empty($user)) {
481                     $uk = common_cache_key('user:repeated_by_me:'.$user->id);
482                     $cache->delete($uk);
483                     $user->free();
484                     unset($user);
485                 }
486
487                 $original = Notice::staticGet('id', $this->repeat_of);
488
489                 if (!empty($original)) {
490                     $originalUser = User::staticGet('id', $original->profile_id);
491                     if (!empty($originalUser)) {
492                         $ouk = common_cache_key('user:repeats_of_me:'.$originalUser->id);
493                         $cache->delete($ouk);
494                         $originalUser->free();
495                         unset($originalUser);
496                     }
497                     $original->free();
498                     unset($original);
499                 }
500             }
501         }
502     }
503
504     function blowConversationCache($blowLast=false)
505     {
506         $cache = common_memcache();
507         if ($cache) {
508             $ck = common_cache_key('notice:conversation_ids:'.$this->conversation);
509             $cache->delete($ck);
510             if ($blowLast) {
511                 $cache->delete($ck.';last');
512             }
513         }
514     }
515
516     function blowGroupCache($blowLast=false)
517     {
518         $cache = common_memcache();
519         if ($cache) {
520             $group_inbox = new Group_inbox();
521             $group_inbox->notice_id = $this->id;
522             if ($group_inbox->find()) {
523                 while ($group_inbox->fetch()) {
524                     $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id));
525                     if ($blowLast) {
526                         $cache->delete(common_cache_key('user_group:notice_ids:' . $group_inbox->group_id.';last'));
527                     }
528                     $member = new Group_member();
529                     $member->group_id = $group_inbox->group_id;
530                     if ($member->find()) {
531                         while ($member->fetch()) {
532                             $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id));
533                             $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id));
534                             if (empty($this->repeat_of)) {
535                                 $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id));
536                                 $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id));
537                             }
538                             if ($blowLast) {
539                                 $cache->delete(common_cache_key('notice_inbox:by_user:' . $member->profile_id . ';last'));
540                                 $cache->delete(common_cache_key('notice_inbox:by_user_own:' . $member->profile_id . ';last'));
541                                 if (empty($this->repeat_of)) {
542                                     $cache->delete(common_cache_key('user:friends_timeline:' . $member->profile_id . ';last'));
543                                     $cache->delete(common_cache_key('user:friends_timeline_own:' . $member->profile_id . ';last'));
544                                 }
545                             }
546                         }
547                     }
548                 }
549             }
550             $group_inbox->free();
551             unset($group_inbox);
552         }
553     }
554
555     function blowTagCache($blowLast=false)
556     {
557         $cache = common_memcache();
558         if ($cache) {
559             $tag = new Notice_tag();
560             $tag->notice_id = $this->id;
561             if ($tag->find()) {
562                 while ($tag->fetch()) {
563                     $tag->blowCache($blowLast);
564                     $ck = 'profile:notice_ids_tagged:' . $this->profile_id . ':' . $tag->tag;
565
566                     $cache->delete($ck);
567                     if ($blowLast) {
568                         $cache->delete($ck . ';last');
569                     }
570                 }
571             }
572             $tag->free();
573             unset($tag);
574         }
575     }
576
577     function blowSubsCache($blowLast=false)
578     {
579         $cache = common_memcache();
580         if ($cache) {
581             $user = new User();
582
583             $UT = common_config('db','type')=='pgsql'?'"user"':'user';
584             $user->query('SELECT id ' .
585
586                          "FROM $UT JOIN subscription ON $UT.id = subscription.subscriber " .
587                          'WHERE subscription.subscribed = ' . $this->profile_id);
588
589             while ($user->fetch()) {
590                 $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id));
591                 $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id));
592                 if (empty($this->repeat_of)) {
593                     $cache->delete(common_cache_key('user:friends_timeline:'.$user->id));
594                     $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id));
595                 }
596                 if ($blowLast) {
597                     $cache->delete(common_cache_key('notice_inbox:by_user:'.$user->id.';last'));
598                     $cache->delete(common_cache_key('notice_inbox:by_user_own:'.$user->id.';last'));
599                     if (empty($this->repeat_of)) {
600                         $cache->delete(common_cache_key('user:friends_timeline:'.$user->id.';last'));
601                         $cache->delete(common_cache_key('user:friends_timeline_own:'.$user->id.';last'));
602                     }
603                 }
604             }
605             $user->free();
606             unset($user);
607         }
608     }
609
610     function blowNoticeCache($blowLast=false)
611     {
612         if ($this->is_local) {
613             $cache = common_memcache();
614             if (!empty($cache)) {
615                 $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id));
616                 if ($blowLast) {
617                     $cache->delete(common_cache_key('profile:notice_ids:'.$this->profile_id.';last'));
618                 }
619             }
620         }
621     }
622
623     function blowRepliesCache($blowLast=false)
624     {
625         $cache = common_memcache();
626         if ($cache) {
627             $reply = new Reply();
628             $reply->notice_id = $this->id;
629             if ($reply->find()) {
630                 while ($reply->fetch()) {
631                     $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id));
632                     if ($blowLast) {
633                         $cache->delete(common_cache_key('reply:stream:'.$reply->profile_id.';last'));
634                     }
635                 }
636             }
637             $reply->free();
638             unset($reply);
639         }
640     }
641
642     function blowPublicCache($blowLast=false)
643     {
644         if ($this->is_local == Notice::LOCAL_PUBLIC) {
645             $cache = common_memcache();
646             if ($cache) {
647                 $cache->delete(common_cache_key('public'));
648                 if ($blowLast) {
649                     $cache->delete(common_cache_key('public').';last');
650                 }
651             }
652         }
653     }
654
655     function blowFavesCache($blowLast=false)
656     {
657         $cache = common_memcache();
658         if ($cache) {
659             $fave = new Fave();
660             $fave->notice_id = $this->id;
661             if ($fave->find()) {
662                 while ($fave->fetch()) {
663                     $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id));
664                     $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id));
665                     if ($blowLast) {
666                         $cache->delete(common_cache_key('fave:ids_by_user:'.$fave->user_id.';last'));
667                         $cache->delete(common_cache_key('fave:by_user_own:'.$fave->user_id.';last'));
668                     }
669                 }
670             }
671             $fave->free();
672             unset($fave);
673         }
674     }
675
676     function getStreamByIds($ids)
677     {
678         $cache = common_memcache();
679
680         if (!empty($cache)) {
681             $notices = array();
682             foreach ($ids as $id) {
683                 $n = Notice::staticGet('id', $id);
684                 if (!empty($n)) {
685                     $notices[] = $n;
686                 }
687             }
688             return new ArrayWrapper($notices);
689         } else {
690             $notice = new Notice();
691             if (empty($ids)) {
692                 //if no IDs requested, just return the notice object
693                 return $notice;
694             }
695             $notice->whereAdd('id in (' . implode(', ', $ids) . ')');
696
697             $notice->find();
698
699             $temp = array();
700
701             while ($notice->fetch()) {
702                 $temp[$notice->id] = clone($notice);
703             }
704
705             $wrapped = array();
706
707             foreach ($ids as $id) {
708                 if (array_key_exists($id, $temp)) {
709                     $wrapped[] = $temp[$id];
710                 }
711             }
712
713             return new ArrayWrapper($wrapped);
714         }
715     }
716
717     function publicStream($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
718     {
719         $ids = Notice::stream(array('Notice', '_publicStreamDirect'),
720                               array(),
721                               'public',
722                               $offset, $limit, $since_id, $max_id, $since);
723
724         return Notice::getStreamByIds($ids);
725     }
726
727     function _publicStreamDirect($offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
728     {
729         $notice = new Notice();
730
731         $notice->selectAdd(); // clears it
732         $notice->selectAdd('id');
733
734         $notice->orderBy('id DESC');
735
736         if (!is_null($offset)) {
737             $notice->limit($offset, $limit);
738         }
739
740         if (common_config('public', 'localonly')) {
741             $notice->whereAdd('is_local = ' . Notice::LOCAL_PUBLIC);
742         } else {
743             # -1 == blacklisted, -2 == gateway (i.e. Twitter)
744             $notice->whereAdd('is_local !='. Notice::LOCAL_NONPUBLIC);
745             $notice->whereAdd('is_local !='. Notice::GATEWAY);
746         }
747
748         if ($since_id != 0) {
749             $notice->whereAdd('id > ' . $since_id);
750         }
751
752         if ($max_id != 0) {
753             $notice->whereAdd('id <= ' . $max_id);
754         }
755
756         if (!is_null($since)) {
757             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
758         }
759
760         $ids = array();
761
762         if ($notice->find()) {
763             while ($notice->fetch()) {
764                 $ids[] = $notice->id;
765             }
766         }
767
768         $notice->free();
769         $notice = NULL;
770
771         return $ids;
772     }
773
774     function conversationStream($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
775     {
776         $ids = Notice::stream(array('Notice', '_conversationStreamDirect'),
777                               array($id),
778                               'notice:conversation_ids:'.$id,
779                               $offset, $limit, $since_id, $max_id, $since);
780
781         return Notice::getStreamByIds($ids);
782     }
783
784     function _conversationStreamDirect($id, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
785     {
786         $notice = new Notice();
787
788         $notice->selectAdd(); // clears it
789         $notice->selectAdd('id');
790
791         $notice->conversation = $id;
792
793         $notice->orderBy('id DESC');
794
795         if (!is_null($offset)) {
796             $notice->limit($offset, $limit);
797         }
798
799         if ($since_id != 0) {
800             $notice->whereAdd('id > ' . $since_id);
801         }
802
803         if ($max_id != 0) {
804             $notice->whereAdd('id <= ' . $max_id);
805         }
806
807         if (!is_null($since)) {
808             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
809         }
810
811         $ids = array();
812
813         if ($notice->find()) {
814             while ($notice->fetch()) {
815                 $ids[] = $notice->id;
816             }
817         }
818
819         $notice->free();
820         $notice = NULL;
821
822         return $ids;
823     }
824
825     function whoGets()
826     {
827         $c = self::memcache();
828
829         if (!empty($c)) {
830             $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
831             if ($ni !== false) {
832                 return $ni;
833             }
834         }
835
836         $users = $this->getSubscribedUsers();
837
838         // FIXME: kind of ignoring 'transitional'...
839         // we'll probably stop supporting inboxless mode
840         // in 0.9.x
841
842         $ni = array();
843
844         foreach ($users as $id) {
845             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
846         }
847
848         $groups = $this->saveGroups();
849         $profile = $this->getProfile();
850
851         foreach ($groups as $group) {
852             $users = $group->getUserMembers();
853             foreach ($users as $id) {
854                 if (!array_key_exists($id, $ni)) {
855                     $user = User::staticGet('id', $id);
856                     if (!$user->hasBlocked($profile)) {
857                         $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
858                     }
859                 }
860             }
861         }
862
863         $recipients = $this->saveReplies();
864
865         foreach ($recipients as $recipient) {
866
867             if (!array_key_exists($recipient, $ni)) {
868                 $recipientUser = User::staticGet('id', $recipient);
869                 if (!empty($recipientUser)) {
870                     $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
871                 }
872             }
873         }
874
875         if (!empty($c)) {
876             // XXX: pack this data better
877             $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
878         }
879
880         return $ni;
881     }
882
883     function addToInboxes()
884     {
885         $ni = $this->whoGets();
886
887         Inbox::bulkInsert($this->id, array_keys($ni));
888
889         return;
890     }
891
892     function getSubscribedUsers()
893     {
894         $user = new User();
895
896         if(common_config('db','quote_identifiers'))
897           $user_table = '"user"';
898         else $user_table = 'user';
899
900         $qry =
901           'SELECT id ' .
902           'FROM '. $user_table .' JOIN subscription '.
903           'ON '. $user_table .'.id = subscription.subscriber ' .
904           'WHERE subscription.subscribed = %d ';
905
906         $user->query(sprintf($qry, $this->profile_id));
907
908         $ids = array();
909
910         while ($user->fetch()) {
911             $ids[] = $user->id;
912         }
913
914         $user->free();
915
916         return $ids;
917     }
918
919     function saveGroups()
920     {
921         // Don't save groups for repeats
922
923         if (!empty($this->repeat_of)) {
924             return array();
925         }
926
927         $groups = array();
928
929         /* extract all !group */
930         $count = preg_match_all('/(?:^|\s)!([A-Za-z0-9]{1,64})/',
931                                 strtolower($this->content),
932                                 $match);
933         if (!$count) {
934             return $groups;
935         }
936
937         $profile = $this->getProfile();
938
939         /* Add them to the database */
940
941         foreach (array_unique($match[1]) as $nickname) {
942             /* XXX: remote groups. */
943             $group = User_group::getForNickname($nickname);
944
945             if (empty($group)) {
946                 continue;
947             }
948
949             // we automatically add a tag for every group name, too
950
951             $tag = Notice_tag::pkeyGet(array('tag' => common_canonical_tag($nickname),
952                                              'notice_id' => $this->id));
953
954             if (is_null($tag)) {
955                 $this->saveTag($nickname);
956             }
957
958             if ($profile->isMember($group)) {
959
960                 $result = $this->addToGroupInbox($group);
961
962                 if (!$result) {
963                     common_log_db_error($gi, 'INSERT', __FILE__);
964                 }
965
966                 $groups[] = clone($group);
967             }
968         }
969
970         return $groups;
971     }
972
973     function addToGroupInbox($group)
974     {
975         $gi = Group_inbox::pkeyGet(array('group_id' => $group->id,
976                                          'notice_id' => $this->id));
977
978         if (empty($gi)) {
979
980             $gi = new Group_inbox();
981
982             $gi->group_id  = $group->id;
983             $gi->notice_id = $this->id;
984             $gi->created   = $this->created;
985
986             return $gi->insert();
987         }
988
989         return true;
990     }
991
992     /**
993      * @return array of integer profile IDs
994      */
995     function saveReplies()
996     {
997         // Don't save reply data for repeats
998
999         if (!empty($this->repeat_of)) {
1000             return array();
1001         }
1002
1003         // Alternative reply format
1004         $tname = false;
1005         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $this->content, $match)) {
1006             $tname = $match[1];
1007         }
1008         // extract all @messages
1009         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $this->content, $match);
1010
1011         $names = array();
1012
1013         if ($cnt || $tname) {
1014             // XXX: is there another way to make an array copy?
1015             $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1016         }
1017
1018         $sender = Profile::staticGet($this->profile_id);
1019
1020         $replied = array();
1021
1022         // store replied only for first @ (what user/notice what the reply directed,
1023         // we assume first @ is it)
1024
1025         for ($i=0; $i<count($names); $i++) {
1026             $nickname = $names[$i];
1027             $recipient = common_relative_profile($sender, $nickname, $this->created);
1028             if (empty($recipient)) {
1029                 continue;
1030             }
1031             // Don't save replies from blocked profile to local user
1032             $recipient_user = User::staticGet('id', $recipient->id);
1033             if (!empty($recipient_user) && $recipient_user->hasBlocked($sender)) {
1034                 continue;
1035             }
1036             $reply = new Reply();
1037             $reply->notice_id = $this->id;
1038             $reply->profile_id = $recipient->id;
1039             $id = $reply->insert();
1040             if (!$id) {
1041                 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1042                 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1043                 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1044                 return array();
1045             } else {
1046                 $replied[$recipient->id] = 1;
1047             }
1048         }
1049
1050         // Hash format replies, too
1051         $cnt = preg_match_all('/(?:^|\s)@#([a-z0-9]{1,64})/', $this->content, $match);
1052         if ($cnt) {
1053             foreach ($match[1] as $tag) {
1054                 $tagged = Profile_tag::getTagged($sender->id, $tag);
1055                 foreach ($tagged as $t) {
1056                     if (!$replied[$t->id]) {
1057                         // Don't save replies from blocked profile to local user
1058                         $t_user = User::staticGet('id', $t->id);
1059                         if ($t_user && $t_user->hasBlocked($sender)) {
1060                             continue;
1061                         }
1062                         $reply = new Reply();
1063                         $reply->notice_id = $this->id;
1064                         $reply->profile_id = $t->id;
1065                         $id = $reply->insert();
1066                         if (!$id) {
1067                             common_log_db_error($reply, 'INSERT', __FILE__);
1068                             return array();
1069                         } else {
1070                             $replied[$recipient->id] = 1;
1071                         }
1072                     }
1073                 }
1074             }
1075         }
1076
1077         $recipientIds = array_keys($replied);
1078
1079         foreach ($recipientIds as $recipientId) {
1080             $user = User::staticGet('id', $recipientId);
1081             if ($user) {
1082                 mail_notify_attn($user, $this);
1083             }
1084         }
1085
1086         return $recipientIds;
1087     }
1088
1089     function asAtomEntry($namespace=false, $source=false)
1090     {
1091         $profile = $this->getProfile();
1092
1093         $xs = new XMLStringer(true);
1094
1095         if ($namespace) {
1096             $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
1097                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
1098         } else {
1099             $attrs = array();
1100         }
1101
1102         $xs->elementStart('entry', $attrs);
1103
1104         if ($source) {
1105             $xs->elementStart('source');
1106             $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
1107             $xs->element('link', array('href' => $profile->profileurl));
1108             $user = User::staticGet('id', $profile->id);
1109             if (!empty($user)) {
1110                 $atom_feed = common_local_url('ApiTimelineUser',
1111                                               array('format' => 'atom',
1112                                                     'id' => $profile->nickname));
1113                 $xs->element('link', array('rel' => 'self',
1114                                            'type' => 'application/atom+xml',
1115                                            'href' => $profile->profileurl));
1116                 $xs->element('link', array('rel' => 'license',
1117                                            'href' => common_config('license', 'url')));
1118             }
1119
1120             $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
1121         }
1122
1123         $xs->elementStart('author');
1124         $xs->element('name', null, $profile->nickname);
1125         $xs->element('uri', null, $profile->profileurl);
1126         $xs->elementEnd('author');
1127
1128         if ($source) {
1129             $xs->elementEnd('source');
1130         }
1131
1132         $xs->element('title', null, $this->content);
1133         $xs->element('summary', null, $this->content);
1134
1135         $xs->element('link', array('rel' => 'alternate',
1136                                    'href' => $this->bestUrl()));
1137
1138         $xs->element('id', null, $this->uri);
1139
1140         $xs->element('published', null, common_date_w3dtf($this->created));
1141         $xs->element('updated', null, common_date_w3dtf($this->created));
1142
1143         if ($this->reply_to) {
1144             $reply_notice = Notice::staticGet('id', $this->reply_to);
1145             if (!empty($reply_notice)) {
1146                 $xs->element('link', array('rel' => 'related',
1147                                            'href' => $reply_notice->bestUrl()));
1148                 $xs->element('thr:in-reply-to',
1149                              array('ref' => $reply_notice->uri,
1150                                    'href' => $reply_notice->bestUrl()));
1151             }
1152         }
1153
1154         $xs->element('content', array('type' => 'html'), $this->rendered);
1155
1156         $tag = new Notice_tag();
1157         $tag->notice_id = $this->id;
1158         if ($tag->find()) {
1159             while ($tag->fetch()) {
1160                 $xs->element('category', array('term' => $tag->tag));
1161             }
1162         }
1163         $tag->free();
1164
1165         # Enclosures
1166         $attachments = $this->attachments();
1167         if($attachments){
1168             foreach($attachments as $attachment){
1169                 $enclosure=$attachment->getEnclosure();
1170                 if ($enclosure) {
1171                     $attributes = array('rel'=>'enclosure','href'=>$enclosure->url,'type'=>$enclosure->mimetype,'length'=>$enclosure->size);
1172                     if($enclosure->title){
1173                         $attributes['title']=$enclosure->title;
1174                     }
1175                     $xs->element('link', $attributes, null);
1176                 }
1177             }
1178         }
1179
1180         if (!empty($this->lat) && !empty($this->lon)) {
1181             $xs->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
1182             $xs->element('georss:point', null, $this->lat . ' ' . $this->lon);
1183             $xs->elementEnd('geo');
1184         }
1185
1186         $xs->elementEnd('entry');
1187
1188         return $xs->getString();
1189     }
1190
1191     function bestUrl()
1192     {
1193         if (!empty($this->url)) {
1194             return $this->url;
1195         } else if (!empty($this->uri) && preg_match('/^https?:/', $this->uri)) {
1196             return $this->uri;
1197         } else {
1198             return common_local_url('shownotice',
1199                                     array('notice' => $this->id));
1200         }
1201     }
1202
1203     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0, $since=null)
1204     {
1205         $cache = common_memcache();
1206
1207         if (empty($cache) ||
1208             $since_id != 0 || $max_id != 0 || (!is_null($since) && $since > 0) ||
1209             is_null($limit) ||
1210             ($offset + $limit) > NOTICE_CACHE_WINDOW) {
1211             return call_user_func_array($fn, array_merge($args, array($offset, $limit, $since_id,
1212                                                                       $max_id, $since)));
1213         }
1214
1215         $idkey = common_cache_key($cachekey);
1216
1217         $idstr = $cache->get($idkey);
1218
1219         if ($idstr !== false) {
1220             // Cache hit! Woohoo!
1221             $window = explode(',', $idstr);
1222             $ids = array_slice($window, $offset, $limit);
1223             return $ids;
1224         }
1225
1226         $laststr = $cache->get($idkey.';last');
1227
1228         if ($laststr !== false) {
1229             $window = explode(',', $laststr);
1230             $last_id = $window[0];
1231             $new_ids = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1232                                                                           $last_id, 0, null)));
1233
1234             $new_window = array_merge($new_ids, $window);
1235
1236             $new_windowstr = implode(',', $new_window);
1237
1238             $result = $cache->set($idkey, $new_windowstr);
1239             $result = $cache->set($idkey . ';last', $new_windowstr);
1240
1241             $ids = array_slice($new_window, $offset, $limit);
1242
1243             return $ids;
1244         }
1245
1246         $window = call_user_func_array($fn, array_merge($args, array(0, NOTICE_CACHE_WINDOW,
1247                                                                      0, 0, null)));
1248
1249         $windowstr = implode(',', $window);
1250
1251         $result = $cache->set($idkey, $windowstr);
1252         $result = $cache->set($idkey . ';last', $windowstr);
1253
1254         $ids = array_slice($window, $offset, $limit);
1255
1256         return $ids;
1257     }
1258
1259     /**
1260      * Determine which notice, if any, a new notice is in reply to.
1261      *
1262      * For conversation tracking, we try to see where this notice fits
1263      * in the tree. Rough algorithm is:
1264      *
1265      * if (reply_to is set and valid) {
1266      *     return reply_to;
1267      * } else if ((source not API or Web) and (content starts with "T NAME" or "@name ")) {
1268      *     return ID of last notice by initial @name in content;
1269      * }
1270      *
1271      * Note that all @nickname instances will still be used to save "reply" records,
1272      * so the notice shows up in the mentioned users' "replies" tab.
1273      *
1274      * @param integer $reply_to   ID passed in by Web or API
1275      * @param integer $profile_id ID of author
1276      * @param string  $source     Source tag, like 'web' or 'gwibber'
1277      * @param string  $content    Final notice content
1278      *
1279      * @return integer ID of replied-to notice, or null for not a reply.
1280      */
1281
1282     static function getReplyTo($reply_to, $profile_id, $source, $content)
1283     {
1284         static $lb = array('xmpp', 'mail', 'sms', 'omb');
1285
1286         // If $reply_to is specified, we check that it exists, and then
1287         // return it if it does
1288
1289         if (!empty($reply_to)) {
1290             $reply_notice = Notice::staticGet('id', $reply_to);
1291             if (!empty($reply_notice)) {
1292                 return $reply_to;
1293             }
1294         }
1295
1296         // If it's not a "low bandwidth" source (one where you can't set
1297         // a reply_to argument), we return. This is mostly web and API
1298         // clients.
1299
1300         if (!in_array($source, $lb)) {
1301             return null;
1302         }
1303
1304         // Is there an initial @ or T?
1305
1306         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $content, $match) ||
1307             preg_match('/^@([a-z0-9]{1,64})\s+/', $content, $match)) {
1308             $nickname = common_canonical_nickname($match[1]);
1309         } else {
1310             return null;
1311         }
1312
1313         // Figure out who that is.
1314
1315         $sender = Profile::staticGet('id', $profile_id);
1316         $recipient = common_relative_profile($sender, $nickname, common_sql_now());
1317
1318         if (empty($recipient)) {
1319             return null;
1320         }
1321
1322         // Get their last notice
1323
1324         $last = $recipient->getCurrentNotice();
1325
1326         if (!empty($last)) {
1327             return $last->id;
1328         }
1329     }
1330
1331     static function maxContent()
1332     {
1333         $contentlimit = common_config('notice', 'contentlimit');
1334         // null => use global limit (distinct from 0!)
1335         if (is_null($contentlimit)) {
1336             $contentlimit = common_config('site', 'textlimit');
1337         }
1338         return $contentlimit;
1339     }
1340
1341     static function contentTooLong($content)
1342     {
1343         $contentlimit = self::maxContent();
1344         return ($contentlimit > 0 && !empty($content) && (mb_strlen($content) > $contentlimit));
1345     }
1346
1347     function getLocation()
1348     {
1349         $location = null;
1350
1351         if (!empty($this->location_id) && !empty($this->location_ns)) {
1352             $location = Location::fromId($this->location_id, $this->location_ns);
1353         }
1354
1355         if (is_null($location)) { // no ID, or Location::fromId() failed
1356             if (!empty($this->lat) && !empty($this->lon)) {
1357                 $location = Location::fromLatLon($this->lat, $this->lon);
1358             }
1359         }
1360
1361         return $location;
1362     }
1363
1364     function repeat($repeater_id, $source)
1365     {
1366         $author = Profile::staticGet('id', $this->profile_id);
1367
1368         $content = sprintf(_('RT @%1$s %2$s'),
1369                            $author->nickname,
1370                            $this->content);
1371
1372         $maxlen = common_config('site', 'textlimit');
1373         if ($maxlen > 0 && mb_strlen($content) > $maxlen) {
1374             // Web interface and current Twitter API clients will
1375             // pull the original notice's text, but some older
1376             // clients and RSS/Atom feeds will see this trimmed text.
1377             //
1378             // Unfortunately this is likely to lose tags or URLs
1379             // at the end of long notices.
1380             $content = mb_substr($content, 0, $maxlen - 4) . ' ...';
1381         }
1382
1383         return self::saveNew($repeater_id, $content, $source,
1384                              array('repeat_of' => $this->id));
1385     }
1386
1387     // These are supposed to be in chron order!
1388
1389     function repeatStream($limit=100)
1390     {
1391         $cache = common_memcache();
1392
1393         if (empty($cache)) {
1394             $ids = $this->_repeatStreamDirect($limit);
1395         } else {
1396             $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
1397             if ($idstr !== false) {
1398                 $ids = explode(',', $idstr);
1399             } else {
1400                 $ids = $this->_repeatStreamDirect(100);
1401                 $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
1402             }
1403             if ($limit < 100) {
1404                 // We do a max of 100, so slice down to limit
1405                 $ids = array_slice($ids, 0, $limit);
1406             }
1407         }
1408
1409         return Notice::getStreamByIds($ids);
1410     }
1411
1412     function _repeatStreamDirect($limit)
1413     {
1414         $notice = new Notice();
1415
1416         $notice->selectAdd(); // clears it
1417         $notice->selectAdd('id');
1418
1419         $notice->repeat_of = $this->id;
1420
1421         $notice->orderBy('created'); // NB: asc!
1422
1423         if (!is_null($offset)) {
1424             $notice->limit($offset, $limit);
1425         }
1426
1427         $ids = array();
1428
1429         if ($notice->find()) {
1430             while ($notice->fetch()) {
1431                 $ids[] = $notice->id;
1432             }
1433         }
1434
1435         $notice->free();
1436         $notice = NULL;
1437
1438         return $ids;
1439     }
1440
1441     function locationOptions($lat, $lon, $location_id, $location_ns, $profile = null)
1442     {
1443         $options = array();
1444
1445         if (!empty($location_id) && !empty($location_ns)) {
1446
1447             $options['location_id'] = $location_id;
1448             $options['location_ns'] = $location_ns;
1449
1450             $location = Location::fromId($location_id, $location_ns);
1451
1452             if (!empty($location)) {
1453                 $options['lat'] = $location->lat;
1454                 $options['lon'] = $location->lon;
1455             }
1456
1457         } else if (!empty($lat) && !empty($lon)) {
1458
1459             $options['lat'] = $lat;
1460             $options['lon'] = $lon;
1461
1462             $location = Location::fromLatLon($lat, $lon);
1463
1464             if (!empty($location)) {
1465                 $options['location_id'] = $location->location_id;
1466                 $options['location_ns'] = $location->location_ns;
1467             }
1468         } else if (!empty($profile)) {
1469
1470             if (isset($profile->lat) && isset($profile->lon)) {
1471                 $options['lat'] = $profile->lat;
1472                 $options['lon'] = $profile->lon;
1473             }
1474
1475             if (isset($profile->location_id) && isset($profile->location_ns)) {
1476                 $options['location_id'] = $profile->location_id;
1477                 $options['location_ns'] = $profile->location_ns;
1478             }
1479         }
1480
1481         return $options;
1482     }
1483 }