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