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