]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Merge pull request #8835 from tobiasd/20200701-lng
[friendica.git] / src / Object / Post.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Object;
23
24 use Friendica\Content\ContactSelector;
25 use Friendica\Content\Feature;
26 use Friendica\Core\Addon;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Crypto;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Proxy as ProxyUtils;
42 use Friendica\Util\Strings;
43 use Friendica\Util\Temporal;
44
45 /**
46  * An item
47  */
48 class Post
49 {
50         private $data = [];
51         private $template = null;
52         private $available_templates = [
53                 'wall' => 'wall_thread.tpl',
54                 'wall2wall' => 'wallwall_thread.tpl'
55         ];
56         private $comment_box_template = 'comment_item.tpl';
57         private $toplevel = false;
58         private $writable = false;
59         /**
60          * @var Post[]
61          */
62         private $children = [];
63         private $parent = null;
64
65         /**
66          * @var Thread
67          */
68         private $thread = null;
69         private $redirect_url = null;
70         private $owner_url = '';
71         private $owner_photo = '';
72         private $owner_name = '';
73         private $wall_to_wall = false;
74         private $threaded = false;
75         private $visiting = false;
76
77         /**
78          * Constructor
79          *
80          * @param array $data data array
81          * @throws \Exception
82          */
83         public function __construct(array $data)
84         {
85                 $this->data = $data;
86                 $this->setTemplate('wall');
87                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
88
89                 if (!empty(Session::getUserIDForVisitorContactID($this->getDataValue('contact-id')))) {
90                         $this->visiting = true;
91                 }
92
93                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
94                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
95                         'network' => $this->getDataValue('author-network'),
96                         'url' => $this->getDataValue('author-link')];
97                 $this->redirect_url = Contact::magicLinkByContact($author);
98                 if (!$this->isToplevel()) {
99                         $this->threaded = true;
100                 }
101
102                 // Prepare the children
103                 if (!empty($data['children'])) {
104                         foreach ($data['children'] as $item) {
105                                 // Only add will be displayed
106                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
107                                         continue;
108                                 } elseif (!visible_activity($item)) {
109                                         continue;
110                                 }
111
112                                 // You can always comment on Diaspora and OStatus items
113                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
114                                         $item['writable'] = true;
115                                 }
116
117                                 $item['pagedrop'] = $data['pagedrop'];
118                                 $child = new Post($item);
119                                 $this->addChild($child);
120                         }
121                 }
122         }
123
124         /**
125          * Get data in a form usable by a conversation template
126          *
127          * @param array   $conv_responses conversation responses
128          * @param integer $thread_level   default = 1
129          *
130          * @return mixed The data requested on success
131          *               false on failure
132          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
133          * @throws \ImagickException
134          */
135         public function getTemplateData(array $conv_responses, $thread_level = 1)
136         {
137                 $a = DI::app();
138
139                 $item = $this->getData();
140                 $edited = false;
141                 // If the time between "created" and "edited" differs we add
142                 // a notice that the post was edited.
143                 // Note: In some networks reshared items seem to have (sometimes) a difference
144                 // between creation time and edit time of a second. Thats why we add the notice
145                 // only if the difference is more than 1 second.
146                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
147                         $edited = [
148                                 'label'    => DI::l10n()->t('This entry was edited'),
149                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
150                                 'relative' => Temporal::getRelativeDate($item['edited'])
151                         ];
152                 }
153                 $sparkle = '';
154                 $buttons = [
155                         'like'    => null,
156                         'dislike' => null,
157                         'share'   => null,
158                 ];
159                 $dropping = false;
160                 $pinned = '';
161                 $pin = false;
162                 $star = false;
163                 $ignore = false;
164                 $ispinned = "unpinned";
165                 $isstarred = "unstarred";
166                 $indent = '';
167                 $shiny = '';
168                 $osparkle = '';
169                 $total_children = $this->countDescendants();
170
171                 $conv = $this->getThread();
172
173                 $lock = ((($item['private'] == Item::PRIVATE) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
174                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
175                         ? DI::l10n()->t('Private Message')
176                         : false);
177
178                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE;
179
180                 $edpost = false;
181
182                 if (local_user()) {
183                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
184                                 if ($item["event-id"] != 0) {
185                                         $edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")];
186                                 } else {
187                                         $edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")];
188                                 }
189                         }
190                         $dropping = in_array($item['uid'], [0, local_user()]);
191                 }
192
193                 // Editing on items of not subscribed users isn't currently possible
194                 // There are some issues on editing that prevent this.
195                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
196                 if ($item['uid'] == 0) {
197                         $edpost = false;
198                 }
199
200                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
201                         $dropping = true;
202                 }
203
204                 $origin = $item['origin'];
205
206                 if (!$origin) {
207                         /// @todo This shouldn't be done as query here, but better during the data creation.
208                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
209                         $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
210                         if (DBA::isResult($parent)) {
211                                 $origin = $parent['origin'];
212                         }
213                 } elseif ($item['pinned']) {
214                         $pinned = DI::l10n()->t('pinned item');
215                 }
216
217                 if ($origin && ($item['gravity'] != GRAVITY_PARENT) && ($item['network'] == Protocol::ACTIVITYPUB)) {
218                         // ActivityPub doesn't allow removal of remote comments
219                         $delete = DI::l10n()->t('Delete locally');
220                 } else {
221                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
222                         $delete = $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally');
223                 }
224
225                 $drop = [
226                         'dropping' => $dropping,
227                         'pagedrop' => $item['pagedrop'],
228                         'select'   => DI::l10n()->t('Select'),
229                         'delete'   => $delete,
230                 ];
231
232                 if (!local_user()) {
233                         $drop = false;
234                 }
235
236                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? DI::l10n()->t("save to folder") : false);
237
238                 $profile_name = $item['author-name'];
239                 if (!empty($item['author-link']) && empty($item['author-name'])) {
240                         $profile_name = $item['author-link'];
241                 }
242
243                 $author = ['uid' => 0, 'id' => $item['author-id'],
244                         'network' => $item['author-network'], 'url' => $item['author-link']];
245
246                 if (Session::isAuthenticated()) {
247                         $profile_link = Contact::magicLinkByContact($author);
248                 } else {
249                         $profile_link = $item['author-link'];
250                 }
251
252                 if (strpos($profile_link, 'redir/') === 0) {
253                         $sparkle = ' sparkle';
254                 }
255
256                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
257                 Hook::callAll('render_location', $locate);
258                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
259
260                 // process action responses - e.g. like/dislike/attend/agree/whatever
261                 $response_verbs = ['like', 'dislike', 'announce'];
262
263                 $isevent = false;
264                 $attend = [];
265                 if ($item['object-type'] === Activity\ObjectType::EVENT) {
266                         $response_verbs[] = 'attendyes';
267                         $response_verbs[] = 'attendno';
268                         $response_verbs[] = 'attendmaybe';
269                         if ($conv->isWritable()) {
270                                 $isevent = true;
271                                 $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
272                         }
273                 }
274
275                 $responses = [];
276                 foreach ($response_verbs as $value => $verb) {
277                         $responses[$verb] = [
278                                 'self'   => $conv_responses[$verb][$item['uri'] . '-self'] ?? 0,
279                                 'output' => !empty($conv_responses[$verb][$item['uri']]) ? format_like($conv_responses[$verb][$item['uri']], $conv_responses[$verb][$item['uri'] . '-l'], $verb, $item['uri']) : '',
280                         ];
281                 }
282
283                 /*
284                  * We should avoid doing this all the time, but it depends on the conversation mode
285                  * And the conv mode may change when we change the conv, or it changes its mode
286                  * Maybe we should establish a way to be notified about conversation changes
287                  */
288                 $this->checkWallToWall();
289
290                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
291                         $osparkle = ' sparkle';
292                 }
293
294                 $tagger = '';
295
296                 if ($this->isToplevel()) {
297                         if(local_user()) {
298                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
299                                 if (DBA::isResult($thread)) {
300                                         $ignore = [
301                                                 'do'        => DI::l10n()->t("ignore thread"),
302                                                 'undo'      => DI::l10n()->t("unignore thread"),
303                                                 'toggle'    => DI::l10n()->t("toggle ignore status"),
304                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
305                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
306                                                 'ignored'   => DI::l10n()->t('ignored'),
307                                         ];
308                                 }
309
310                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
311                                         if ($origin) {
312                                                 $ispinned = ($item['pinned'] ? 'pinned' : 'unpinned');
313
314                                                 $pin = [
315                                                         'do'        => DI::l10n()->t('pin'),
316                                                         'undo'      => DI::l10n()->t('unpin'),
317                                                         'toggle'    => DI::l10n()->t('toggle pin status'),
318                                                         'classdo'   => $item['pinned'] ? 'hidden' : '',
319                                                         'classundo' => $item['pinned'] ? '' : 'hidden',
320                                                         'pinned'   => DI::l10n()->t('pinned'),
321                                                 ];
322                                         }
323
324                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
325
326                                         $star = [
327                                                 'do'        => DI::l10n()->t("add star"),
328                                                 'undo'      => DI::l10n()->t("remove star"),
329                                                 'toggle'    => DI::l10n()->t("toggle star status"),
330                                                 'classdo'   => $item['starred'] ? "hidden" : "",
331                                                 'classundo' => $item['starred'] ? "" : "hidden",
332                                                 'starred'   => DI::l10n()->t('starred'),
333                                         ];
334
335                                         $tagger = [
336                                                 'add'   => DI::l10n()->t("add tag"),
337                                                 'class' => "",
338                                         ];
339                                 }
340                         }
341                 } else {
342                         $indent = 'comment';
343                 }
344
345                 if ($conv->isWritable()) {
346                         $buttons['like']    = [DI::l10n()->t("I like this \x28toggle\x29")      , DI::l10n()->t("like")];
347                         $buttons['dislike'] = [DI::l10n()->t("I don't like this \x28toggle\x29"), DI::l10n()->t("dislike")];
348                         if ($shareable) {
349                                 $buttons['share'] = [DI::l10n()->t('Share this'), DI::l10n()->t('share')];
350                         }
351                 }
352
353                 $comment = $this->getCommentBox($indent);
354
355                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
356                         $shiny = 'shiny';
357                 }
358
359                 localize_item($item);
360
361                 $body = Item::prepareBody($item, true);
362
363                 list($categories, $folders) = DI::contentItem()->determineCategoriesTerms($item);
364
365                 $body_e       = $body;
366                 $text_e       = strip_tags($body);
367                 $name_e       = $profile_name;
368
369                 if (!empty($item['content-warning']) && DI::pConfig()->get(local_user(), 'system', 'disable_cw', false)) {
370                         $title_e = ucfirst($item['content-warning']);
371                 } else {
372                         $title_e = $item['title'];
373                 }
374
375                 $location_e   = $location;
376                 $owner_name_e = $this->getOwnerName();
377
378                 if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) {
379                         $buttons['dislike'] = false;
380                 }
381
382                 // Disable features that aren't available in several networks
383                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
384                         if ($buttons["dislike"]) {
385                                 $buttons["dislike"] = false;
386                         }
387
388                         $isevent = false;
389                         $tagger = '';
390                 }
391
392                 if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) {
393                         $buttons["like"] = false;
394                 }
395
396                 $tags = Tag::populateFromItem($item);
397
398                 $ago = Temporal::getRelativeDate($item['created']);
399                 $ago_received = Temporal::getRelativeDate($item['received']);
400                 if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) {
401                         $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received);
402                 }
403
404                 // Fetching of Diaspora posts doesn't always work. There are issues with reshares and possibly comments
405                 if (($item['network'] != Protocol::DIASPORA) && empty($comment) && !empty(Session::get('remote_comment'))) {
406                         $remote_comment = [DI::l10n()->t('Comment this item on your system'), DI::l10n()->t('remote comment'),
407                                 str_replace('{uri}', urlencode($item['uri']), Session::get('remote_comment'))];
408                 } else {
409                         $remote_comment = '';
410                 }
411
412                 $direction = [];
413                 if (DI::config()->get('debug', 'show_direction')) {
414                         $conversation = DBA::selectFirst('conversation', ['direction'], ['item-uri' => $item['uri']]);
415                         if (!empty($conversation['direction']) && in_array($conversation['direction'], [1, 2])) {
416                                 $title = [1 => DI::l10n()->t('Pushed'), 2 => DI::l10n()->t('Pulled')];
417                                 $direction = ['direction' => $conversation['direction'], 'title' => $title[$conversation['direction']]];
418                         }
419                 }
420
421                 $tmp_item = [
422                         'template'        => $this->getTemplate(),
423                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
424                         'suppress_tags'   => DI::config()->get('system', 'suppress_tags'),
425                         'tags'            => $tags['tags'],
426                         'hashtags'        => $tags['hashtags'],
427                         'mentions'        => $tags['mentions'],
428                         'implicit_mentions' => $tags['implicit_mentions'],
429                         'txt_cats'        => DI::l10n()->t('Categories:'),
430                         'txt_folders'     => DI::l10n()->t('Filed under:'),
431                         'has_cats'        => ((count($categories)) ? 'true' : ''),
432                         'has_folders'     => ((count($folders)) ? 'true' : ''),
433                         'categories'      => $categories,
434                         'folders'         => $folders,
435                         'body'            => $body_e,
436                         'text'            => $text_e,
437                         'id'              => $this->getId(),
438                         'guid'            => urlencode($item['guid']),
439                         'isevent'         => $isevent,
440                         'attend'          => $attend,
441                         'linktitle'       => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
442                         'olinktitle'      => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
443                         'to'              => DI::l10n()->t('to'),
444                         'via'             => DI::l10n()->t('via'),
445                         'wall'            => DI::l10n()->t('Wall-to-Wall'),
446                         'vwall'           => DI::l10n()->t('via Wall-To-Wall:'),
447                         'profile_url'     => $profile_link,
448                         'item_photo_menu' => item_photo_menu($item),
449                         'name'            => $name_e,
450                         'thumb'           => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
451                         'osparkle'        => $osparkle,
452                         'sparkle'         => $sparkle,
453                         'title'           => $title_e,
454                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
455                         'ago'             => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago,
456                         'app'             => $item['app'],
457                         'created'         => $ago,
458                         'lock'            => $lock,
459                         'location'        => $location_e,
460                         'indent'          => $indent,
461                         'shiny'           => $shiny,
462                         'owner_self'      => $item['author-link'] == Session::get('my_url'),
463                         'owner_url'       => $this->getOwnerUrl(),
464                         'owner_photo'     => DI::baseUrl()->remove(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
465                         'owner_name'      => $owner_name_e,
466                         'plink'           => Item::getPlink($item),
467                         'edpost'          => $edpost,
468                         'ispinned'        => $ispinned,
469                         'pin'             => $pin,
470                         'pinned'          => $pinned,
471                         'isstarred'       => $isstarred,
472                         'star'            => $star,
473                         'ignore'          => $ignore,
474                         'tagger'          => $tagger,
475                         'filer'           => $filer,
476                         'drop'            => $drop,
477                         'vote'            => $buttons,
478                         'like'            => $responses['like']['output'],
479                         'dislike'         => $responses['dislike']['output'],
480                         'responses'       => $responses,
481                         'switchcomment'   => DI::l10n()->t('Comment'),
482                         'reply_label'     => DI::l10n()->t('Reply to %s', $name_e),
483                         'comment'         => $comment,
484                         'remote_comment'  => $remote_comment,
485                         'menu'            => DI::l10n()->t('More'),
486                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
487                         'wait'            => DI::l10n()->t('Please wait'),
488                         'thread_level'    => $thread_level,
489                         'edited'          => $edited,
490                         'network'         => $item["network"],
491                         'network_name'    => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network']),
492                         'network_icon'    => ContactSelector::networkToIcon($item['network'], $item['author-link']),
493                         'received'        => $item['received'],
494                         'commented'       => $item['commented'],
495                         'created_date'    => $item['created'],
496                         'return'          => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '',
497                         'direction'       => $direction,
498                         'delivery'        => [
499                                 'queue_count'       => $item['delivery_queue_count'],
500                                 'queue_done'        => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future
501                                 'notifier_pending'  => DI::l10n()->t('Notifier task is pending'),
502                                 'delivery_pending'  => DI::l10n()->t('Delivery to remote servers is pending'),
503                                 'delivery_underway' => DI::l10n()->t('Delivery to remote servers is underway'),
504                                 'delivery_almost'   => DI::l10n()->t('Delivery to remote servers is mostly done'),
505                                 'delivery_done'     => DI::l10n()->t('Delivery to remote servers is done'),
506                         ],
507                 ];
508
509                 $arr = ['item' => $item, 'output' => $tmp_item];
510                 Hook::callAll('display_item', $arr);
511
512                 $result = $arr['output'];
513
514                 $result['children'] = [];
515                 $children = $this->getChildren();
516                 $nb_children = count($children);
517                 if ($nb_children > 0) {
518                         foreach ($children as $child) {
519                                 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
520                         }
521
522                         // Collapse
523                         if (($nb_children > 2) || ($thread_level > 1)) {
524                                 $result['children'][0]['comment_firstcollapsed'] = true;
525                                 $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children);
526                                 $result['children'][0]['show_text'] = DI::l10n()->t('Show more');
527                                 $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer');
528                                 if ($thread_level > 1) {
529                                         $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
530                                 } else {
531                                         $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
532                                 }
533                         }
534                 }
535
536                 if ($this->isToplevel()) {
537                         $result['total_comments_num'] = "$total_children";
538                         $result['total_comments_text'] = DI::l10n()->tt('comment', 'comments', $total_children);
539                 }
540
541                 $result['private'] = $item['private'];
542                 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
543
544                 if ($this->isThreaded()) {
545                         $result['flatten'] = false;
546                         $result['threaded'] = true;
547                 } else {
548                         $result['flatten'] = true;
549                         $result['threaded'] = false;
550                 }
551
552                 return $result;
553         }
554
555         /**
556          * @return integer
557          */
558         public function getId()
559         {
560                 return $this->getDataValue('id');
561         }
562
563         /**
564          * @return boolean
565          */
566         public function isThreaded()
567         {
568                 return $this->threaded;
569         }
570
571         /**
572          * Add a child item
573          *
574          * @param Post $item The child item to add
575          *
576          * @return mixed
577          * @throws \Exception
578          */
579         public function addChild(Post $item)
580         {
581                 $item_id = $item->getId();
582                 if (!$item_id) {
583                         Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
584                         return false;
585                 } elseif ($this->getChild($item->getId())) {
586                         Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
587                         return false;
588                 }
589
590                 $activity = DI::activity();
591
592                 /*
593                  * Only add what will be displayed
594                  */
595                 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
596                         return false;
597                 } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) ||
598                           $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) {
599                         return false;
600                 }
601
602                 $item->setParent($this);
603                 $this->children[] = $item;
604
605                 return end($this->children);
606         }
607
608         /**
609          * Get a child by its ID
610          *
611          * @param integer $id The child id
612          *
613          * @return mixed
614          */
615         public function getChild($id)
616         {
617                 foreach ($this->getChildren() as $child) {
618                         if ($child->getId() == $id) {
619                                 return $child;
620                         }
621                 }
622
623                 return null;
624         }
625
626         /**
627          * Get all our children
628          *
629          * @return Post[]
630          */
631         public function getChildren()
632         {
633                 return $this->children;
634         }
635
636         /**
637          * Set our parent
638          *
639          * @param Post $item The item to set as parent
640          *
641          * @return void
642          */
643         protected function setParent(Post $item)
644         {
645                 $parent = $this->getParent();
646                 if ($parent) {
647                         $parent->removeChild($this);
648                 }
649
650                 $this->parent = $item;
651                 $this->setThread($item->getThread());
652         }
653
654         /**
655          * Remove our parent
656          *
657          * @return void
658          */
659         protected function removeParent()
660         {
661                 $this->parent = null;
662                 $this->thread = null;
663         }
664
665         /**
666          * Remove a child
667          *
668          * @param Post $item The child to be removed
669          *
670          * @return boolean Success or failure
671          * @throws \Exception
672          */
673         public function removeChild(Post $item)
674         {
675                 $id = $item->getId();
676                 foreach ($this->getChildren() as $key => $child) {
677                         if ($child->getId() == $id) {
678                                 $child->removeParent();
679                                 unset($this->children[$key]);
680                                 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
681                                 $this->children = array_values($this->children);
682                                 return true;
683                         }
684                 }
685                 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
686                 return false;
687         }
688
689         /**
690          * Get parent item
691          *
692          * @return object
693          */
694         protected function getParent()
695         {
696                 return $this->parent;
697         }
698
699         /**
700          * Set conversation thread
701          *
702          * @param Thread $thread
703          *
704          * @return void
705          */
706         public function setThread(Thread $thread = null)
707         {
708                 $this->thread = $thread;
709
710                 // Set it on our children too
711                 foreach ($this->getChildren() as $child) {
712                         $child->setThread($thread);
713                 }
714         }
715
716         /**
717          * Get conversation
718          *
719          * @return Thread
720          */
721         public function getThread()
722         {
723                 return $this->thread;
724         }
725
726         /**
727          * Get raw data
728          *
729          * We shouldn't need this
730          *
731          * @return array
732          */
733         public function getData()
734         {
735                 return $this->data;
736         }
737
738         /**
739          * Get a data value
740          *
741          * @param string $name key
742          *
743          * @return mixed value on success
744          *               false on failure
745          */
746         public function getDataValue($name)
747         {
748                 if (!isset($this->data[$name])) {
749                         // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
750                         return false;
751                 }
752
753                 return $this->data[$name];
754         }
755
756         /**
757          * Set template
758          *
759          * @param string $name template name
760          * @return bool
761          * @throws \Exception
762          */
763         private function setTemplate($name)
764         {
765                 if (empty($this->available_templates[$name])) {
766                         Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
767                         return false;
768                 }
769
770                 $this->template = $this->available_templates[$name];
771
772                 return true;
773         }
774
775         /**
776          * Get template
777          *
778          * @return object
779          */
780         private function getTemplate()
781         {
782                 return $this->template;
783         }
784
785         /**
786          * Check if this is a toplevel post
787          *
788          * @return boolean
789          */
790         private function isToplevel()
791         {
792                 return $this->toplevel;
793         }
794
795         /**
796          * Check if this is writable
797          *
798          * @return boolean
799          */
800         private function isWritable()
801         {
802                 $conv = $this->getThread();
803
804                 if ($conv) {
805                         // This will allow us to comment on wall-to-wall items owned by our friends
806                         // and community forums even if somebody else wrote the post.
807                         // bug #517 - this fixes for conversation owner
808                         if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
809                                 return true;
810                         }
811
812                         // this fixes for visitors
813                         return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
814                 }
815                 return $this->writable;
816         }
817
818         /**
819          * Count the total of our descendants
820          *
821          * @return integer
822          */
823         private function countDescendants()
824         {
825                 $children = $this->getChildren();
826                 $total = count($children);
827                 if ($total > 0) {
828                         foreach ($children as $child) {
829                                 $total += $child->countDescendants();
830                         }
831                 }
832
833                 return $total;
834         }
835
836         /**
837          * Get the template for the comment box
838          *
839          * @return string
840          */
841         private function getCommentBoxTemplate()
842         {
843                 return $this->comment_box_template;
844         }
845
846         /**
847          * Get default text for the comment box
848          *
849          * @return string
850          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
851          */
852         private function getDefaultText()
853         {
854                 $a = DI::app();
855
856                 if (!local_user()) {
857                         return '';
858                 }
859
860                 $owner = User::getOwnerDataById($a->user['uid']);
861
862                 if (!Feature::isEnabled(local_user(), 'explicit_mentions')) {
863                         return '';
864                 }
865
866                 $item = Item::selectFirst(['author-addr', 'uri-id'], ['id' => $this->getId()]);
867                 if (!DBA::isResult($item) || empty($item['author-addr'])) {
868                         // Should not happen
869                         return '';
870                 }
871
872                 if ($item['author-addr'] != $owner['addr']) {
873                         $text = '@' . $item['author-addr'] . ' ';
874                 } else {
875                         $text = '';
876                 }
877
878                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
879                 foreach ($terms as $term) {
880                         $profile = Contact::getDetailsByURL($term['url']);
881                         if (!empty($profile['addr']) && ((($profile['contact-type'] ?? '') ?: Contact::TYPE_UNKNOWN) != Contact::TYPE_COMMUNITY) &&
882                                 ($profile['addr'] != $owner['addr']) && !strstr($text, $profile['addr'])) {
883                                 $text .= '@' . $profile['addr'] . ' ';
884                         }
885                 }
886
887                 return $text;
888         }
889
890         /**
891          * Get the comment box
892          *
893          * @param string $indent Indent value
894          *
895          * @return mixed The comment box string (empty if no comment box)
896          *               false on failure
897          * @throws \Exception
898          */
899         private function getCommentBox($indent)
900         {
901                 $a = DI::app();
902
903                 $comment_box = '';
904                 $conv = $this->getThread();
905                 $ww = '';
906                 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
907                         $ww = 'ww';
908                 }
909
910                 if ($conv->isWritable() && $this->isWritable()) {
911                         $qcomment = null;
912
913                         /*
914                          * Hmmm, code depending on the presence of a particular addon?
915                          * This should be better if done by a hook
916                          */
917                         if (Addon::isEnabled('qcomment')) {
918                                 $qc = ((local_user()) ? DI::pConfig()->get(local_user(), 'qcomment', 'words') : null);
919                                 $qcomment = (($qc) ? explode("\n", $qc) : null);
920                         }
921
922                         // Fetch the user id from the parent when the owner user is empty
923                         $uid = $conv->getProfileOwner();
924                         $parent_uid = $this->getDataValue('uid');
925
926                         $default_text = $this->getDefaultText();
927
928                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
929                                 $uid = $parent_uid;
930                         }
931
932                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
933                         $comment_box = Renderer::replaceMacros($template, [
934                                 '$return_path' => DI::args()->getQueryString(),
935                                 '$threaded'    => $this->isThreaded(),
936                                 '$jsreload'    => '',
937                                 '$wall'        => ($conv->getMode() === 'profile'),
938                                 '$id'          => $this->getId(),
939                                 '$parent'      => $this->getId(),
940                                 '$qcomment'    => $qcomment,
941                                 '$default'     => $default_text,
942                                 '$profile_uid' => $uid,
943                                 '$mylink'      => DI::baseUrl()->remove($a->contact['url']),
944                                 '$mytitle'     => DI::l10n()->t('This is you'),
945                                 '$myphoto'     => DI::baseUrl()->remove($a->contact['thumb']),
946                                 '$comment'     => DI::l10n()->t('Comment'),
947                                 '$submit'      => DI::l10n()->t('Submit'),
948                                 '$loading'     => DI::l10n()->t('Loading...'),
949                                 '$edbold'      => DI::l10n()->t('Bold'),
950                                 '$editalic'    => DI::l10n()->t('Italic'),
951                                 '$eduline'     => DI::l10n()->t('Underline'),
952                                 '$edquote'     => DI::l10n()->t('Quote'),
953                                 '$edcode'      => DI::l10n()->t('Code'),
954                                 '$edimg'       => DI::l10n()->t('Image'),
955                                 '$edurl'       => DI::l10n()->t('Link'),
956                                 '$edattach'    => DI::l10n()->t('Link or Media'),
957                                 '$prompttext'  => DI::l10n()->t('Please enter a image/video/audio/webpage URL:'),
958                                 '$preview'     => DI::l10n()->t('Preview'),
959                                 '$indent'      => $indent,
960                                 '$sourceapp'   => DI::l10n()->t($a->sourcename),
961                                 '$ww'          => $conv->getMode() === 'network' ? $ww : '',
962                                 '$rand_num'    => Crypto::randomDigits(12)
963                         ]);
964                 }
965
966                 return $comment_box;
967         }
968
969         /**
970          * @return string
971          */
972         private function getRedirectUrl()
973         {
974                 return $this->redirect_url;
975         }
976
977         /**
978          * Check if we are a wall to wall item and set the relevant properties
979          *
980          * @return void
981          * @throws \Exception
982          */
983         protected function checkWallToWall()
984         {
985                 $a = DI::app();
986                 $conv = $this->getThread();
987                 $this->wall_to_wall = false;
988
989                 if ($this->isToplevel()) {
990                         if ($conv->getMode() !== 'profile') {
991                                 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
992                                         // On the network page, I am the owner. On the display page it will be the profile owner.
993                                         // This will have been stored in $a->page_contact by our calling page.
994                                         // Put this person as the wall owner of the wall-to-wall notice.
995
996                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
997                                         $this->owner_photo = $a->page_contact['thumb'];
998                                         $this->owner_name = $a->page_contact['name'];
999                                         $this->wall_to_wall = true;
1000                                 } elseif ($this->getDataValue('owner-link')) {
1001                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
1002                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
1003                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
1004
1005                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
1006                                                 // The author url doesn't match the owner (typically the contact)
1007                                                 // and also doesn't match the contact alias.
1008                                                 // The name match is a hack to catch several weird cases where URLs are
1009                                                 // all over the park. It can be tricked, but this prevents you from
1010                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
1011                                                 // well that it's the same Bob Smith.
1012                                                 // But it could be somebody else with the same name. It just isn't highly likely.
1013
1014
1015                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
1016                                                 $this->owner_name = $this->getDataValue('owner-name');
1017                                                 $this->wall_to_wall = true;
1018
1019                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
1020                                                         'network' => $this->getDataValue('owner-network'),
1021                                                         'url' => $this->getDataValue('owner-link')];
1022                                                 $this->owner_url = Contact::magicLinkByContact($owner);
1023                                         }
1024                                 }
1025                         }
1026                 }
1027
1028                 if (!$this->wall_to_wall) {
1029                         $this->setTemplate('wall');
1030                         $this->owner_url = '';
1031                         $this->owner_photo = '';
1032                         $this->owner_name = '';
1033                 }
1034         }
1035
1036         /**
1037          * @return boolean
1038          */
1039         private function isWallToWall()
1040         {
1041                 return $this->wall_to_wall;
1042         }
1043
1044         /**
1045          * @return string
1046          */
1047         private function getOwnerUrl()
1048         {
1049                 return $this->owner_url;
1050         }
1051
1052         /**
1053          * @return string
1054          */
1055         private function getOwnerName()
1056         {
1057                 return $this->owner_name;
1058         }
1059
1060         /**
1061          * @return boolean
1062          */
1063         private function isVisiting()
1064         {
1065                 return $this->visiting;
1066         }
1067 }