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