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