]> git.mxchange.org Git - friendica.git/blob - src/Object/Post.php
Fix PHPDoc comments project-wide
[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\Conversation;
20 use Friendica\Model\Item;
21 use Friendica\Model\Term;
22 use Friendica\Util\Crypto;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\Proxy as ProxyUtils;
25 use Friendica\Util\Strings;
26 use Friendica\Util\Temporal;
27
28 /**
29  * An item
30  */
31 class Post extends BaseObject
32 {
33         private $data = [];
34         private $template = null;
35         private $available_templates = [
36                 'wall' => 'wall_thread.tpl',
37                 'wall2wall' => 'wallwall_thread.tpl'
38         ];
39         private $comment_box_template = 'comment_item.tpl';
40         private $toplevel = false;
41         private $writable = false;
42         /**
43          * @var Post[]
44          */
45         private $children = [];
46         private $parent = null;
47
48         /**
49          * @var Thread
50          */
51         private $thread = null;
52         private $redirect_url = null;
53         private $owner_url = '';
54         private $owner_photo = '';
55         private $owner_name = '';
56         private $wall_to_wall = false;
57         private $threaded = false;
58         private $visiting = false;
59
60         /**
61          * Constructor
62          *
63          * @param array $data data array
64          * @throws \Exception
65          */
66         public function __construct(array $data)
67         {
68                 $this->data = $data;
69                 $this->setTemplate('wall');
70                 $this->toplevel = $this->getId() == $this->getDataValue('parent');
71
72                 if (!empty($_SESSION['remote']) && is_array($_SESSION['remote'])) {
73                         foreach ($_SESSION['remote'] as $visitor) {
74                                 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
75                                         $this->visiting = true;
76                                         break;
77                                 }
78                         }
79                 }
80
81                 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
82                 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
83                         'network' => $this->getDataValue('author-network'),
84                         'url' => $this->getDataValue('author-link')];
85                 $this->redirect_url = Contact::magicLinkbyContact($author);
86                 if (!$this->isToplevel()) {
87                         $this->threaded = true;
88                 }
89
90                 // Prepare the children
91                 if (!empty($data['children'])) {
92                         foreach ($data['children'] as $item) {
93                                 // Only add will be displayed
94                                 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
95                                         continue;
96                                 } elseif (!visible_activity($item)) {
97                                         continue;
98                                 }
99
100                                 // You can always comment on Diaspora and OStatus items
101                                 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
102                                         $item['writable'] = true;
103                                 }
104
105                                 $item['pagedrop'] = $data['pagedrop'];
106                                 $child = new Post($item);
107                                 $this->addChild($child);
108                         }
109                 }
110         }
111
112         /**
113          * Get data in a form usable by a conversation template
114          *
115          * @param array   $conv_responses conversation responses
116          * @param integer $thread_level   default = 1
117          *
118          * @return mixed The data requested on success
119          *               false on failure
120          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121          * @throws \ImagickException
122          */
123         public function getTemplateData(array $conv_responses, $thread_level = 1)
124         {
125                 $a = self::getApp();
126
127                 $item = $this->getData();
128                 $edited = false;
129                 // If the time between "created" and "edited" differs we add
130                 // a notice that the post was edited.
131                 // Note: In some networks reshared items seem to have (sometimes) a difference
132                 // between creation time and edit time of a second. Thats why we add the notice
133                 // only if the difference is more than 1 second.
134                 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
135                         $edited = [
136                                 'label'    => L10n::t('This entry was edited'),
137                                 'date'     => DateTimeFormat::local($item['edited'], 'r'),
138                                 'relative' => Temporal::getRelativeDate($item['edited'])
139                         ];
140                 }
141                 $sparkle = '';
142                 $buttons = '';
143                 $dropping = false;
144                 $star = false;
145                 $ignore = false;
146                 $isstarred = "unstarred";
147                 $indent = '';
148                 $shiny = '';
149                 $osparkle = '';
150                 $total_children = $this->countDescendants();
151
152                 $conv = $this->getThread();
153
154                 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
155                         || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
156                         ? L10n::t('Private Message')
157                         : false);
158
159                 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
160
161                 $edpost = false;
162
163                 if (local_user()) {
164                         if (Strings::compareLink($a->contact['url'], $item['author-link'])) {
165                                 if ($item["event-id"] != 0) {
166                                         $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
167                                 } else {
168                                         $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
169                                 }
170                         }
171                         $dropping = in_array($item['uid'], [0, local_user()]);
172                 }
173
174                 // Editing on items of not subscribed users isn't currently possible
175                 // There are some issues on editing that prevent this.
176                 // But also it is an issue of the supported protocols that doesn't allow editing at all.
177                 if ($item['uid'] == 0) {
178                         $edpost = false;
179                 }
180
181                 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
182                         $dropping = true;
183                 }
184
185                 $origin = $item['origin'];
186
187                 if (!$origin) {
188                         /// @todo This shouldn't be done as query here, but better during the data creation.
189                         // it is now done here, since during the RC phase we shouldn't make to intense changes.
190                         $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
191                         if (DBA::isResult($parent)) {
192                                 $origin = $parent['origin'];
193                         }
194                 }
195
196                 if ($origin && ($item['id'] != $item['parent']) && ($item['network'] == Protocol::ACTIVITYPUB)) {
197                         // ActivityPub doesn't allow removal of remote comments
198                         $delete = L10n::t('Delete locally');
199                 } else {
200                         // Showing the one or the other text, depending upon if we can only hide it or really delete it.
201                         $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
202                 }
203
204                 $drop = [
205                         'dropping' => $dropping,
206                         'pagedrop' => $item['pagedrop'],
207                         'select'   => L10n::t('Select'),
208                         'delete'   => $delete,
209                 ];
210
211                 if (!local_user()) {
212                         $drop = false;
213                 }
214
215                 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
216
217                 $profile_name = $item['author-name'];
218                 if (!empty($item['author-link']) && empty($item['author-name'])) {
219                         $profile_name = $item['author-link'];
220                 }
221
222                 $author = ['uid' => 0, 'id' => $item['author-id'],
223                         'network' => $item['author-network'], 'url' => $item['author-link']];
224
225                 if (local_user() || remote_user()) {
226                         $profile_link = Contact::magicLinkbyContact($author);
227                 } else {
228                         $profile_link = $item['author-link'];
229                 }
230
231                 if (strpos($profile_link, 'redir/') === 0) {
232                         $sparkle = ' sparkle';
233                 }
234
235                 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
236                 Hook::callAll('render_location', $locate);
237                 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
238
239                 // process action responses - e.g. like/dislike/attend/agree/whatever
240                 $response_verbs = ['like', 'dislike'];
241
242                 $isevent = false;
243                 $attend = [];
244                 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
245                         $response_verbs[] = 'attendyes';
246                         $response_verbs[] = 'attendno';
247                         $response_verbs[] = 'attendmaybe';
248                         if ($conv->isWritable()) {
249                                 $isevent = true;
250                                 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
251                         }
252                 }
253
254                 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
255
256                 foreach ($response_verbs as $value => $verbs) {
257                         $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']) : '';
258                 }
259
260                 /*
261                  * We should avoid doing this all the time, but it depends on the conversation mode
262                  * And the conv mode may change when we change the conv, or it changes its mode
263                  * Maybe we should establish a way to be notified about conversation changes
264                  */
265                 $this->checkWallToWall();
266
267                 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
268                         $osparkle = ' sparkle';
269                 }
270
271                 $tagger = '';
272
273                 if ($this->isToplevel()) {
274                         if(local_user()) {
275                                 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
276                                 if (DBA::isResult($thread)) {
277                                         $ignore = [
278                                                 'do'        => L10n::t("ignore thread"),
279                                                 'undo'      => L10n::t("unignore thread"),
280                                                 'toggle'    => L10n::t("toggle ignore status"),
281                                                 'classdo'   => $thread['ignored'] ? "hidden" : "",
282                                                 'classundo' => $thread['ignored'] ? "" : "hidden",
283                                                 'ignored'   => L10n::t('ignored'),
284                                         ];
285                                 }
286
287                                 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
288                                         $isstarred = (($item['starred']) ? "starred" : "unstarred");
289
290                                         $star = [
291                                                 'do'        => L10n::t("add star"),
292                                                 'undo'      => L10n::t("remove star"),
293                                                 'toggle'    => L10n::t("toggle star status"),
294                                                 'classdo'   => $item['starred'] ? "hidden" : "",
295                                                 'classundo' => $item['starred'] ? "" : "hidden",
296                                                 'starred'   => L10n::t('starred'),
297                                         ];
298
299                                         $tagger = [
300                                                 'add'   => L10n::t("add tag"),
301                                                 'class' => "",
302                                         ];
303                                 }
304                         }
305                 } else {
306                         $indent = 'comment';
307                 }
308
309                 if ($conv->isWritable()) {
310                         $buttons = [
311                                 'like'    => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
312                                 'dislike' => [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")],
313                         ];
314                         if ($shareable) {
315                                 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
316                         }
317                 }
318
319                 $comment = $this->getCommentBox($indent);
320
321                 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
322                         $shiny = 'shiny';
323                 }
324
325                 localize_item($item);
326
327                 $body = Item::prepareBody($item, true);
328
329                 list($categories, $folders) = get_cats_and_terms($item);
330
331                 $body_e       = $body;
332                 $text_e       = strip_tags($body);
333                 $name_e       = $profile_name;
334
335                 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
336                         $title_e = ucfirst($item['content-warning']);
337                 } else {
338                         $title_e = $item['title'];
339                 }
340
341                 $location_e   = $location;
342                 $owner_name_e = $this->getOwnerName();
343
344                 // Disable features that aren't available in several networks
345                 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
346                         unset($buttons["dislike"]);
347                         $isevent = false;
348                         $tagger = '';
349                 }
350
351                 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
352                         unset($buttons["like"]);
353                 }
354
355                 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
356                         unset($buttons["like"]);
357                 }
358
359                 $tags = Term::populateTagsFromItem($item);
360
361                 $tmp_item = [
362                         'template'        => $this->getTemplate(),
363                         'type'            => implode("", array_slice(explode("/", $item['verb']), -1)),
364                         'suppress_tags'   => Config::get('system', 'suppress_tags'),
365                         'tags'            => $tags['tags'],
366                         'hashtags'        => $tags['hashtags'],
367                         'mentions'        => $tags['mentions'],
368                         'txt_cats'        => L10n::t('Categories:'),
369                         'txt_folders'     => L10n::t('Filed under:'),
370                         'has_cats'        => ((count($categories)) ? 'true' : ''),
371                         'has_folders'     => ((count($folders)) ? 'true' : ''),
372                         'categories'      => $categories,
373                         'folders'         => $folders,
374                         'body'            => $body_e,
375                         'text'            => $text_e,
376                         'id'              => $this->getId(),
377                         'guid'            => urlencode($item['guid']),
378                         'isevent'         => $isevent,
379                         'attend'          => $attend,
380                         'linktitle'       => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
381                         'olinktitle'      => L10n::t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']),
382                         'to'              => L10n::t('to'),
383                         'via'             => L10n::t('via'),
384                         'wall'            => L10n::t('Wall-to-Wall'),
385                         'vwall'           => L10n::t('via Wall-To-Wall:'),
386                         'profile_url'     => $profile_link,
387                         'item_photo_menu' => item_photo_menu($item),
388                         'name'            => $name_e,
389                         'thumb'           => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
390                         'osparkle'        => $osparkle,
391                         'sparkle'         => $sparkle,
392                         'title'           => $title_e,
393                         'localtime'       => DateTimeFormat::local($item['created'], 'r'),
394                         'ago'             => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
395                         'app'             => $item['app'],
396                         'created'         => Temporal::getRelativeDate($item['created']),
397                         'lock'            => $lock,
398                         'location'        => $location_e,
399                         'indent'          => $indent,
400                         'shiny'           => $shiny,
401                         'owner_self'      => $item['author-link'] == defaults($_SESSION, 'my_url', null),
402                         'owner_url'       => $this->getOwnerUrl(),
403                         'owner_photo'     => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
404                         'owner_name'      => $owner_name_e,
405                         'plink'           => Item::getPlink($item),
406                         'edpost'          => $edpost,
407                         'isstarred'       => $isstarred,
408                         'star'            => $star,
409                         'ignore'          => $ignore,
410                         'tagger'          => $tagger,
411                         'filer'           => $filer,
412                         'drop'            => $drop,
413                         'vote'            => $buttons,
414                         'like'            => $responses['like']['output'],
415                         'dislike'         => $responses['dislike']['output'],
416                         'responses'       => $responses,
417                         'switchcomment'   => L10n::t('Comment'),
418                         'comment'         => $comment,
419                         'previewing'      => $conv->isPreview() ? ' preview ' : '',
420                         'wait'            => L10n::t('Please wait'),
421                         'thread_level'    => $thread_level,
422                         'edited'          => $edited,
423                         'network'         => $item["network"],
424                         'network_name'    => ContactSelector::networkToName($item['network'], $item['author-link']),
425                         'received'        => $item['received'],
426                         'commented'       => $item['commented'],
427                         'created_date'    => $item['created'],
428                         'return'          => ($a->cmd) ? bin2hex($a->cmd) : '',
429                         'delivery'        => [
430                                 'queue_count'       => $item['delivery_queue_count'],
431                                 'queue_done'        => $item['delivery_queue_done'],
432                                 'notifier_pending'  => L10n::t('Notifier task is pending'),
433                                 'delivery_pending'  => L10n::t('Delivery to remote servers is pending'),
434                                 'delivery_underway' => L10n::t('Delivery to remote servers is underway'),
435                                 'delivery_almost'   => L10n::t('Delivery to remote servers is mostly 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 the comment box
774          *
775          * @param string $indent Indent value
776          *
777          * @return mixed The comment box string (empty if no comment box)
778          *               false on failure
779          * @throws \Exception
780          */
781         private function getCommentBox($indent)
782         {
783                 $a = self::getApp();
784
785                 $comment_box = '';
786                 $conv = $this->getThread();
787                 $ww = '';
788                 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
789                         $ww = 'ww';
790                 }
791
792                 if ($conv->isWritable() && $this->isWritable()) {
793                         $qc = $qcomment = null;
794
795                         /*
796                          * Hmmm, code depending on the presence of a particular addon?
797                          * This should be better if done by a hook
798                          */
799                         if (Addon::isEnabled('qcomment')) {
800                                 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
801                                 $qcomment = (($qc) ? explode("\n", $qc) : null);
802                         }
803
804                         // Fetch the user id from the parent when the owner user is empty
805                         $uid = $conv->getProfileOwner();
806                         $parent_uid = $this->getDataValue('uid');
807
808                         if (!is_null($parent_uid) && ($uid != $parent_uid)) {
809                                 $uid = $parent_uid;
810                         }
811
812                         $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate());
813                         $comment_box = Renderer::replaceMacros($template, [
814                                 '$return_path' => $a->query_string,
815                                 '$threaded'    => $this->isThreaded(),
816                                 '$jsreload'    => '',
817                                 '$wall'        => ($conv->getMode() === 'profile'),
818                                 '$id'          => $this->getId(),
819                                 '$parent'      => $this->getId(),
820                                 '$qcomment'    => $qcomment,
821                                 '$profile_uid' => $uid,
822                                 '$mylink'      => $a->removeBaseURL($a->contact['url']),
823                                 '$mytitle'     => L10n::t('This is you'),
824                                 '$myphoto'     => $a->removeBaseURL($a->contact['thumb']),
825                                 '$comment'     => L10n::t('Comment'),
826                                 '$submit'      => L10n::t('Submit'),
827                                 '$edbold'      => L10n::t('Bold'),
828                                 '$editalic'    => L10n::t('Italic'),
829                                 '$eduline'     => L10n::t('Underline'),
830                                 '$edquote'     => L10n::t('Quote'),
831                                 '$edcode'      => L10n::t('Code'),
832                                 '$edimg'       => L10n::t('Image'),
833                                 '$edurl'       => L10n::t('Link'),
834                                 '$edattach'    => L10n::t('Link or Media'),
835                                 '$prompttext'  => L10n::t('Please enter a image/video/audio/webpage URL:'),
836                                 '$preview'     => L10n::t('Preview'),
837                                 '$indent'      => $indent,
838                                 '$sourceapp'   => L10n::t($a->sourcename),
839                                 '$ww'          => $conv->getMode() === 'network' ? $ww : '',
840                                 '$rand_num'    => Crypto::randomDigits(12)
841                         ]);
842                 }
843
844                 return $comment_box;
845         }
846
847         /**
848          * @return string
849          */
850         private function getRedirectUrl()
851         {
852                 return $this->redirect_url;
853         }
854
855         /**
856          * Check if we are a wall to wall item and set the relevant properties
857          *
858          * @return void
859          * @throws \Exception
860          */
861         protected function checkWallToWall()
862         {
863                 $a = self::getApp();
864                 $conv = $this->getThread();
865                 $this->wall_to_wall = false;
866
867                 if ($this->isToplevel()) {
868                         if ($conv->getMode() !== 'profile') {
869                                 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
870                                         // On the network page, I am the owner. On the display page it will be the profile owner.
871                                         // This will have been stored in $a->page_contact by our calling page.
872                                         // Put this person as the wall owner of the wall-to-wall notice.
873
874                                         $this->owner_url = Contact::magicLink($a->page_contact['url']);
875                                         $this->owner_photo = $a->page_contact['thumb'];
876                                         $this->owner_name = $a->page_contact['name'];
877                                         $this->wall_to_wall = true;
878                                 } elseif ($this->getDataValue('owner-link')) {
879                                         $owner_linkmatch = (($this->getDataValue('owner-link')) && Strings::compareLink($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
880                                         $alias_linkmatch = (($this->getDataValue('alias')) && Strings::compareLink($this->getDataValue('alias'), $this->getDataValue('author-link')));
881                                         $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
882
883                                         if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
884                                                 // The author url doesn't match the owner (typically the contact)
885                                                 // and also doesn't match the contact alias.
886                                                 // The name match is a hack to catch several weird cases where URLs are
887                                                 // all over the park. It can be tricked, but this prevents you from
888                                                 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
889                                                 // well that it's the same Bob Smith.
890                                                 // But it could be somebody else with the same name. It just isn't highly likely.
891
892
893                                                 $this->owner_photo = $this->getDataValue('owner-avatar');
894                                                 $this->owner_name = $this->getDataValue('owner-name');
895                                                 $this->wall_to_wall = true;
896
897                                                 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
898                                                         'network' => $this->getDataValue('owner-network'),
899                                                         'url' => $this->getDataValue('owner-link')];
900                                                 $this->owner_url = Contact::magicLinkbyContact($owner);
901                                         }
902                                 }
903                         }
904                 }
905
906                 if (!$this->wall_to_wall) {
907                         $this->setTemplate('wall');
908                         $this->owner_url = '';
909                         $this->owner_photo = '';
910                         $this->owner_name = '';
911                 }
912         }
913
914         /**
915          * @return boolean
916          */
917         private function isWallToWall()
918         {
919                 return $this->wall_to_wall;
920         }
921
922         /**
923          * @return string
924          */
925         private function getOwnerUrl()
926         {
927                 return $this->owner_url;
928         }
929
930         /**
931          * @return string
932          */
933         private function getOwnerName()
934         {
935                 return $this->owner_name;
936         }
937
938         /**
939          * @return boolean
940          */
941         private function isVisiting()
942         {
943                 return $this->visiting;
944         }
945 }