]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - classes/Notice.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline into 1.0.x
[quix0rs-gnu-social.git] / classes / Notice.php
index 592e2f3842fabd9172843564458ca788013f40da..a8ec0529f26b419a9a25f85d92681ba213ddd857 100644 (file)
@@ -93,7 +93,9 @@ class Notice extends Memcached_DataObject
         $profile = Profile::staticGet('id', $this->profile_id);
 
         if (empty($profile)) {
-            throw new ServerException(sprintf(_('No such profile (%d) for notice (%d)'), $this->profile_id, $this->id));
+            // TRANS: Server exception thrown when a user profile for a notice cannot be found.
+            // TRANS: %1$d is a profile ID (number), %2$d is a notice ID (number).
+            throw new ServerException(sprintf(_('No such profile (%1$d) for notice (%2$d).'), $this->profile_id, $this->id));
         }
 
         return $profile;
@@ -119,16 +121,19 @@ class Notice extends Memcached_DataObject
             $deleted->insert();
         }
 
-        // Clear related records
+        if (Event::handle('NoticeDeleteRelated', array($this))) {
 
-        $this->clearReplies();
-        $this->clearRepeats();
-        $this->clearFaves();
-        $this->clearTags();
-        $this->clearGroupInboxes();
+            // Clear related records
 
-        // NOTE: we don't clear inboxes
-        // NOTE: we don't clear queue items
+            $this->clearReplies();
+            $this->clearRepeats();
+            $this->clearFaves();
+            $this->clearTags();
+            $this->clearGroupInboxes();
+
+            // NOTE: we don't clear inboxes
+            // NOTE: we don't clear queue items
+        }
 
         $result = parent::delete();
 
@@ -243,6 +248,8 @@ class Notice extends Memcached_DataObject
         if (!empty($options)) {
             $options = $options + $defaults;
             extract($options);
+        } else {
+            extract($defaults);
         }
 
         if (!isset($is_local)) {
@@ -254,28 +261,34 @@ class Notice extends Memcached_DataObject
         $final = common_shorten_links($content);
 
         if (Notice::contentTooLong($final)) {
+            // TRANS: Client exception thrown if a notice contains too many characters.
             throw new ClientException(_('Problem saving notice. Too long.'));
         }
 
         if (empty($profile)) {
+            // TRANS: Client exception thrown when trying to save a notice for an unknown user.
             throw new ClientException(_('Problem saving notice. Unknown user.'));
         }
 
         if (common_config('throttle', 'enabled') && !Notice::checkEditThrottle($profile_id)) {
             common_log(LOG_WARNING, 'Excessive posting by profile #' . $profile_id . '; throttled.');
+            // TRANS: Client exception thrown when a user tries to post too many notices in a given time frame.
             throw new ClientException(_('Too many notices too fast; take a breather '.
                                         'and post again in a few minutes.'));
         }
 
         if (common_config('site', 'dupelimit') > 0 && !Notice::checkDupes($profile_id, $final)) {
             common_log(LOG_WARNING, 'Dupe posting by profile #' . $profile_id . '; throttled.');
+            // TRANS: Client exception thrown when a user tries to post too many duplicate notices in a given time frame.
             throw new ClientException(_('Too many duplicate messages too quickly;'.
                                         ' take a breather and post again in a few minutes.'));
         }
 
         if (!$profile->hasRight(Right::NEWNOTICE)) {
             common_log(LOG_WARNING, "Attempted post from user disallowed to post: " . $profile->nickname);
-            throw new ClientException(_('You are banned from posting notices on this site.'));
+
+            // TRANS: Client exception thrown when a user tries to post while being banned.
+            throw new ClientException(_('You are banned from posting notices on this site.'), 403);
         }
 
         $notice = new Notice();
@@ -341,6 +354,7 @@ class Notice extends Memcached_DataObject
 
             if (!$id) {
                 common_log_db_error($notice, 'INSERT', __FILE__);
+                // TRANS: Server exception thrown when a notice cannot be saved.
                 throw new ServerException(_('Problem saving notice.'));
             }
 
@@ -367,6 +381,7 @@ class Notice extends Memcached_DataObject
             if ($changed) {
                 if (!$notice->update($orig)) {
                     common_log_db_error($notice, 'UPDATE', __FILE__);
+                    // TRANS: Server exception thrown when a notice cannot be updated.
                     throw new ServerException(_('Problem saving notice.'));
                 }
             }
@@ -475,7 +490,7 @@ class Notice extends Memcached_DataObject
     function saveKnownUrls($urls)
     {
         // @fixme validation?
-        foreach ($urls as $url) {
+        foreach (array_unique($urls) as $url) {
             File::processNew($url, $this->id);
         }
     }
@@ -568,7 +583,9 @@ class Notice extends Memcached_DataObject
         if ($f2p->find()) {
             while ($f2p->fetch()) {
                 $f = File::staticGet($f2p->file_id);
-                $att[] = clone($f);
+                if ($f) {
+                    $att[] = clone($f);
+                }
             }
         }
         return $att;
@@ -576,7 +593,7 @@ class Notice extends Memcached_DataObject
 
     function getStreamByIds($ids)
     {
-        $cache = common_memcache();
+        $cache = Cache::instance();
 
         if (!empty($cache)) {
             $notices = array();
@@ -728,6 +745,7 @@ class Notice extends Memcached_DataObject
                 1,
                 1
             );
+
             if ($conversation->N > 0) {
                 return true;
             }
@@ -736,15 +754,22 @@ class Notice extends Memcached_DataObject
     }
 
     /**
-     * @param $groups array of Group *objects*
-     * @param $recipients array of profile *ids*
+     * Pull up a full list of local recipients who will be getting
+     * this notice in their inbox. Results will be cached, so don't
+     * change the input data wily-nilly!
+     *
+     * @param array $groups optional list of Group objects;
+     *              if left empty, will be loaded from group_inbox records
+     * @param array $recipient optional list of reply profile ids
+     *              if left empty, will be loaded from reply records
+     * @return array associating recipient user IDs with an inbox source constant
      */
     function whoGets($groups=null, $recipients=null)
     {
         $c = self::memcache();
 
         if (!empty($c)) {
-            $ni = $c->get(common_cache_key('notice:who_gets:'.$this->id));
+            $ni = $c->get(Cache::key('notice:who_gets:'.$this->id));
             if ($ni !== false) {
                 return $ni;
             }
@@ -770,33 +795,33 @@ class Notice extends Memcached_DataObject
             $ni[$id] = NOTICE_INBOX_SOURCE_SUB;
         }
 
-        $profile = $this->getProfile();
-
         foreach ($groups as $group) {
             $users = $group->getUserMembers();
             foreach ($users as $id) {
                 if (!array_key_exists($id, $ni)) {
-                    $user = User::staticGet('id', $id);
-                    if (!$user->hasBlocked($profile)) {
-                        $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
-                    }
+                    $ni[$id] = NOTICE_INBOX_SOURCE_GROUP;
                 }
             }
         }
 
         foreach ($recipients as $recipient) {
-
             if (!array_key_exists($recipient, $ni)) {
-                $recipientUser = User::staticGet('id', $recipient);
-                if (!empty($recipientUser)) {
-                    $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
-                }
+                $ni[$recipient] = NOTICE_INBOX_SOURCE_REPLY;
+            }
+        }
+
+        // Exclude any deleted, non-local, or blocking recipients.
+        $profile = $this->getProfile();
+        foreach ($ni as $id => $source) {
+            $user = User::staticGet('id', $id);
+            if (empty($user) || $user->hasBlocked($profile)) {
+                unset($ni[$id]);
             }
         }
 
         if (!empty($c)) {
             // XXX: pack this data better
-            $c->set(common_cache_key('notice:who_gets:'.$this->id), $ni);
+            $c->set(Cache::key('notice:who_gets:'.$this->id), $ni);
         }
 
         return $ni;
@@ -878,11 +903,12 @@ class Notice extends Memcached_DataObject
     function saveKnownGroups($group_ids)
     {
         if (!is_array($group_ids)) {
-            throw new ServerException("Bad type provided to saveKnownGroups");
+            // TRANS: Server exception thrown when no array is provided to the method saveKnownGroups().
+            throw new ServerException(_("Bad type provided to saveKnownGroups"));
         }
 
         $groups = array();
-        foreach ($group_ids as $id) {
+        foreach (array_unique($group_ids) as $id) {
             $group = User_group::staticGet('id', $id);
             if ($group) {
                 common_log(LOG_ERR, "Local delivery to group id $id, $group->nickname");
@@ -976,6 +1002,7 @@ class Notice extends Memcached_DataObject
 
             if (!$result) {
                 common_log_db_error($gi, 'INSERT', __FILE__);
+                // TRANS: Server exception thrown when an update for a group inbox fails.
                 throw new ServerException(_('Problem saving group inbox.'));
             }
 
@@ -1002,24 +1029,31 @@ class Notice extends Memcached_DataObject
         if (empty($uris)) {
             return;
         }
+
         $sender = Profile::staticGet($this->profile_id);
 
-        foreach ($uris as $uri) {
+        foreach (array_unique($uris) as $uri) {
 
-            $user = User::staticGet('uri', $uri);
+            $profile = Profile::fromURI($uri);
 
-            if (!empty($user)) {
-                if ($user->hasBlocked($sender)) {
-                    continue;
-                }
+            if (empty($profile)) {
+                common_log(LOG_WARNING, "Unable to determine profile for URI '$uri'");
+                continue;
+            }
 
-                $reply = new Reply();
+            if ($profile->hasBlocked($sender)) {
+                common_log(LOG_INFO, "Not saving reply to profile {$profile->id} ($uri) from sender {$sender->id} because of a block.");
+                continue;
+            }
 
-                $reply->notice_id  = $this->id;
-                $reply->profile_id = $user->id;
+            $reply = new Reply();
 
-                $id = $reply->insert();
-            }
+            $reply->notice_id  = $this->id;
+            $reply->profile_id = $profile->id;
+
+            common_log(LOG_INFO, __METHOD__ . ": saving reply: notice $this->id to profile $profile->id");
+
+            $id = $reply->insert();
         }
 
         return;
@@ -1081,7 +1115,9 @@ class Notice extends Memcached_DataObject
 
                 if (!$id) {
                     common_log_db_error($reply, 'INSERT', __FILE__);
-                    throw new ServerException("Couldn't save reply for {$this->id}, {$mentioned->id}");
+                    // TRANS: Server exception thrown when a reply cannot be saved.
+                    // TRANS: %1$d is a notice ID, %2$d is the ID of the mentioned user.
+                    throw new ServerException(sprintf(_("Could not save reply for %1$d, %2$d."), $this->id, $mentioned->id));
                 } else {
                     $replied[$mentioned->id] = 1;
                     self::blow('reply:stream:%d', $mentioned->id);
@@ -1184,6 +1220,64 @@ class Notice extends Memcached_DataObject
         return $groups;
     }
 
+    function asActivity()
+    {
+        $profile = $this->getProfile();
+
+        $act = new Activity();
+
+        $act->actor     = ActivityObject::fromProfile($profile);
+        $act->verb      = ActivityVerb::POST;
+        $act->objects[] = ActivityObject::fromNotice($this);
+
+        $act->time    = strtotime($this->created);
+        $act->link    = $this->bestUrl();
+
+        $act->content = common_xml_safe_str($this->rendered);
+        $act->id      = $this->uri;
+        $act->title   = common_xml_safe_str($this->content);
+
+        $ctx = new ActivityContext();
+
+        if (!empty($this->reply_to)) {
+            $reply = Notice::staticGet('id', $this->reply_to);
+            if (!empty($reply)) {
+                $ctx->replyToID  = $reply->uri;
+                $ctx->replyToUrl = $reply->bestUrl();
+            }
+        }
+
+        $ctx->location = $this->getLocation();
+
+        $conv = null;
+
+        if (!empty($this->conversation)) {
+            $conv = Conversation::staticGet('id', $this->conversation);
+            if (!empty($conv)) {
+                $ctx->conversation = $conv->uri;
+            }
+        }
+
+        $reply_ids = $this->getReplies();
+
+        foreach ($reply_ids as $id) {
+            $profile = Profile::staticGet('id', $id);
+            if (!empty($profile)) {
+                $ctx->attention[] = $profile->getUri();
+            }
+        }
+
+        $groups = $this->getGroups();
+
+        foreach ($groups as $group) {
+            $ctx->attention[] = $group->uri;
+        }
+
+        $act->context = $ctx;
+
+        return $act;
+    }
+
     // This has gotten way too long. Needs to be sliced up into functional bits
     // or ideally exported to a utility class.
 
@@ -1212,32 +1306,45 @@ class Notice extends Memcached_DataObject
         }
 
         if (Event::handle('StartActivitySource', array(&$this, &$xs))) {
-
             if ($source) {
+                $atom_feed = $profile->getAtomFeed();
+
+                if (!empty($atom_feed)) {
+                    $xs->elementStart('source');
 
-                $xs->elementStart('source');
+                    // XXX: we should store the actual feed ID
 
-                $xs->element('id', null, $profile->profileurl);
-                $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
-                $xs->element('link', array('href' => $profile->profileurl));
+                    $xs->element('id', null, $atom_feed);
 
-                $user = User::staticGet('id', $profile->id);
+                    // XXX: we should store the actual feed title
+
+                    $xs->element('title', null, $profile->getBestName());
+
+                    $xs->element('link', array('rel' => 'alternate',
+                                               'type' => 'text/html',
+                                               'href' => $profile->profileurl));
 
-                if (!empty($user)) {
-                    $atom_feed = common_local_url('ApiTimelineUser',
-                                                  array('format' => 'atom',
-                                                        'id' => $profile->nickname));
                     $xs->element('link', array('rel' => 'self',
                                                'type' => 'application/atom+xml',
-                                               'href' => $profile->profileurl));
-                    $xs->element('link', array('rel' => 'license',
-                                               'href' => common_config('license', 'url')));
-                }
+                                               'href' => $atom_feed));
+
+                    $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
+
+                    $notice = $profile->getCurrentNotice();
+
+                    if (!empty($notice)) {
+                        $xs->element('updated', null, self::utcDate($notice->created));
+                    }
 
-                $xs->element('icon', null, $profile->avatarUrl(AVATAR_PROFILE_SIZE));
-                $xs->element('updated', null, common_date_w3dtf($this->created)); // FIXME: not true!
+                    $user = User::staticGet('id', $profile->id);
 
-                $xs->elementEnd('source');
+                    if (!empty($user)) {
+                        $xs->element('link', array('rel' => 'license',
+                                                   'href' => common_config('license', 'url')));
+                    }
+
+                    $xs->elementEnd('source');
+                }
             }
             Event::handle('EndActivitySource', array(&$this, &$xs));
         }
@@ -1291,7 +1398,7 @@ class Notice extends Memcached_DataObject
             Event::handle('EndActivityId', array(&$this, &$xs, $id));
         }
 
-        $published = common_date_w3dtf($this->created);
+        $published = self::utcDate($this->created);
 
         if (Event::handle('StartActivityPublished', array(&$this, &$xs, &$published))) {
             $xs->element('published', null, $published);
@@ -1391,7 +1498,7 @@ class Notice extends Memcached_DataObject
                 $xs->element('thr:in-reply-to',
                              array('ref' => $replyNotice->uri,
                                    'href' => $replyNotice->bestUrl()));
-                Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyUri, $replyUrl));
+                Event::handle('EndActivityInReplyTo', array(&$this, &$xs, $replyNotice));
             }
         }
 
@@ -1424,6 +1531,8 @@ class Notice extends Memcached_DataObject
             foreach ($replyProfiles as $profile) {
                 $xs->element('link', array('rel' => 'ostatus:attention',
                                            'href' => $profile->getUri()));
+                $xs->element('link', array('rel' => 'mentioned',
+                                           'href' => $profile->getUri()));
             }
             Event::handle('EndActivityAttentionProfiles', array(&$this, &$xs, $replyProfiles));
         }
@@ -1434,6 +1543,8 @@ class Notice extends Memcached_DataObject
             foreach ($groups as $group) {
                 $xs->element('link', array('rel' => 'ostatus:attention',
                                            'href' => $group->permalink()));
+                $xs->element('link', array('rel' => 'mentioned',
+                                           'href' => $group->permalink()));
             }
             Event::handle('EndActivityAttentionGroups', array(&$this, &$xs, $groups));
         }
@@ -1539,7 +1650,7 @@ class Notice extends Memcached_DataObject
 
     function stream($fn, $args, $cachekey, $offset=0, $limit=20, $since_id=0, $max_id=0)
     {
-        $cache = common_memcache();
+        $cache = Cache::instance();
 
         if (empty($cache) ||
             $since_id != 0 || $max_id != 0 ||
@@ -1549,7 +1660,7 @@ class Notice extends Memcached_DataObject
                                                                       $max_id)));
         }
 
-        $idkey = common_cache_key($cachekey);
+        $idkey = Cache::key($cachekey);
 
         $idstr = $cache->get($idkey);
 
@@ -1731,17 +1842,17 @@ class Notice extends Memcached_DataObject
 
     function repeatStream($limit=100)
     {
-        $cache = common_memcache();
+        $cache = Cache::instance();
 
         if (empty($cache)) {
             $ids = $this->_repeatStreamDirect($limit);
         } else {
-            $idstr = $cache->get(common_cache_key('notice:repeats:'.$this->id));
+            $idstr = $cache->get(Cache::key('notice:repeats:'.$this->id));
             if ($idstr !== false) {
                 $ids = explode(',', $idstr);
             } else {
                 $ids = $this->_repeatStreamDirect(100);
-                $cache->set(common_cache_key('notice:repeats:'.$this->id), implode(',', $ids));
+                $cache->set(Cache::key('notice:repeats:'.$this->id), implode(',', $ids));
             }
             if ($limit < 100) {
                 // We do a max of 100, so slice down to limit
@@ -1786,7 +1897,6 @@ class Notice extends Memcached_DataObject
         $options = array();
 
         if (!empty($location_id) && !empty($location_ns)) {
-
             $options['location_id'] = $location_id;
             $options['location_ns'] = $location_ns;
 
@@ -1798,7 +1908,6 @@ class Notice extends Memcached_DataObject
             }
 
         } else if (!empty($lat) && !empty($lon)) {
-
             $options['lat'] = $lat;
             $options['lon'] = $lon;
 
@@ -1809,7 +1918,6 @@ class Notice extends Memcached_DataObject
                 $options['location_ns'] = $location->location_ns;
             }
         } else if (!empty($profile)) {
-
             if (isset($profile->lat) && isset($profile->lon)) {
                 $options['lat'] = $profile->lat;
                 $options['lon'] = $profile->lon;
@@ -1895,10 +2003,10 @@ class Notice extends Memcached_DataObject
 
         if ($tag->find()) {
             while ($tag->fetch()) {
-                self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, common_keyize($tag->tag));
-                self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, common_keyize($tag->tag));
-                self::blow('notice_tag:notice_ids:%s', common_keyize($tag->tag));
-                self::blow('notice_tag:notice_ids:%s;last', common_keyize($tag->tag));
+                self::blow('profile:notice_ids_tagged:%d:%s', $this->profile_id, Cache::keyize($tag->tag));
+                self::blow('profile:notice_ids_tagged:%d:%s;last', $this->profile_id, Cache::keyize($tag->tag));
+                self::blow('notice_tag:notice_ids:%s', Cache::keyize($tag->tag));
+                self::blow('notice_tag:notice_ids:%s;last', Cache::keyize($tag->tag));
                 $tag->delete();
             }
         }
@@ -1926,6 +2034,7 @@ class Notice extends Memcached_DataObject
     {
         // We always insert for the author so they don't
         // have to wait
+        Event::handle('StartNoticeDistribute', array($this));
 
         $user = User::staticGet('id', $this->profile_id);
         if (!empty($user)) {
@@ -2039,4 +2148,11 @@ class Notice extends Memcached_DataObject
         $tag->free();
         return $tags;
     }
+
+    static private function utcDate($dt)
+    {
+        $dateStr = date('d F Y H:i:s', strtotime($dt));
+        $d = new DateTime($dateStr, new DateTimeZone('UTC'));
+        return $d->format(DATE_W3C);
+    }
 }