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