3 * @file src/Object/Post.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Content\ContactSelector;
9 use Friendica\Content\Feature;
10 use Friendica\Core\Addon;
11 use Friendica\Core\Config;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\Protocol;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Proxy as ProxyUtils;
22 use Friendica\Util\Temporal;
24 require_once 'include/dba.php';
25 require_once 'include/text.php';
26 require_once 'boot.php';
27 require_once 'include/conversation.php';
32 class Post extends BaseObject
35 private $template = null;
36 private $available_templates = [
37 'wall' => 'wall_thread.tpl',
38 'wall2wall' => 'wallwall_thread.tpl'
40 private $comment_box_template = 'comment_item.tpl';
41 private $toplevel = false;
42 private $writable = false;
43 private $children = [];
44 private $parent = null;
45 private $thread = null;
46 private $redirect_url = null;
47 private $owner_url = '';
48 private $owner_photo = '';
49 private $owner_name = '';
50 private $wall_to_wall = false;
51 private $threaded = false;
52 private $visiting = false;
57 * @param array $data data array
59 public function __construct(array $data)
64 $this->setTemplate('wall');
65 $this->toplevel = $this->getId() == $this->getDataValue('parent');
67 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
68 foreach ($_SESSION['remote'] as $visitor) {
69 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
70 $this->visiting = true;
76 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
77 $author = ['uid' => 0, 'id' => $this->getDataValue('author-id'),
78 'network' => $this->getDataValue('author-network'),
79 'url' => $this->getDataValue('author-link')];
80 $this->redirect_url = Contact::magicLinkbyContact($author);
81 if (!$this->isToplevel()) {
82 $this->threaded = true;
85 // Prepare the children
86 if (!empty($data['children'])) {
87 foreach ($data['children'] as $item) {
88 // Only add will be displayed
89 if ($item['network'] === Protocol::MAIL && local_user() != $item['uid']) {
91 } elseif (!visible_activity($item)) {
95 // You can always comment on Diaspora and OStatus items
96 if (in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA]) && (local_user() == $item['uid'])) {
97 $item['writable'] = true;
100 $item['pagedrop'] = $data['pagedrop'];
101 $child = new Post($item);
102 $this->addChild($child);
108 * Get data in a form usable by a conversation template
110 * @param object $conv_responses conversation responses
111 * @param integer $thread_level default = 1
113 * @return mixed The data requested on success
116 public function getTemplateData($conv_responses, $thread_level = 1)
122 $item = $this->getData();
124 // If the time between "created" and "edited" differs we add
125 // a notice that the post was edited.
126 // Note: In some networks reshared items seem to have (sometimes) a difference
127 // between creation time and edit time of a second. Thats why we add the notice
128 // only if the difference is more than 1 second.
129 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
131 'label' => L10n::t('This entry was edited'),
132 'date' => DateTimeFormat::local($item['edited'], 'r'),
133 'relative' => Temporal::getRelativeDate($item['edited'])
142 $isstarred = "unstarred";
146 $total_children = $this->countDescendants();
148 $conv = $this->getThread();
150 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
151 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
152 ? L10n::t('Private Message')
155 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
157 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
158 if ($item["event-id"] != 0) {
159 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
161 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
163 $dropping = in_array($item['uid'], [0, local_user()]);
168 // Editing on items of not subscribed users isn't currently possible
169 // There are some issues on editing that prevent this.
170 // But also it is an issue of the supported protocols that doesn't allow editing at all.
171 if ($item['uid'] == 0) {
175 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
179 $origin = $item['origin'];
182 /// @todo This shouldn't be done as query here, but better during the data creation.
183 // it is now done here, since during the RC phase we shouldn't make to intense changes.
184 $parent = Item::selectFirst(['origin'], ['id' => $item['parent']]);
185 if (DBA::isResult($parent)) {
186 $origin = $parent['origin'];
190 // Showing the one or the other text, depending upon if we can only hide it or really delete it.
191 $delete = $origin ? L10n::t('Delete globally') : L10n::t('Remove locally');
194 'dropping' => $dropping,
195 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
196 'select' => L10n::t('Select'),
200 if (!local_user() || ($item['uid'] == 0)) {
204 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
206 $profile_name = htmlentities($item['author-name']);
207 if (!empty($item['author-link']) && empty($item['author-name'])) {
208 $profile_name = $item['author-link'];
211 $author = ['uid' => 0, 'id' => $item['author-id'],
212 'network' => $item['author-network'], 'url' => $item['author-link']];
214 if (local_user() || remote_user()) {
215 $profile_link = Contact::magicLinkbyContact($author);
217 $profile_link = $item['author-link'];
220 if (strpos($profile_link, 'redir/') === 0) {
221 $sparkle = ' sparkle';
224 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
225 Addon::callHooks('render_location', $locate);
226 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
228 // process action responses - e.g. like/dislike/attend/agree/whatever
229 $response_verbs = ['like', 'dislike'];
233 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
234 $response_verbs[] = 'attendyes';
235 $response_verbs[] = 'attendno';
236 $response_verbs[] = 'attendmaybe';
237 if ($conv->isWritable()) {
239 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
243 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
245 foreach ($response_verbs as $value => $verbs) {
246 $responses[$verbs]['output'] = x($conv_responses[$verbs], $item['uri']) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : '';
250 * We should avoid doing this all the time, but it depends on the conversation mode
251 * And the conv mode may change when we change the conv, or it changes its mode
252 * Maybe we should establish a way to be notified about conversation changes
254 $this->checkWallToWall();
256 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
257 $osparkle = ' sparkle';
262 if ($this->isToplevel()) {
263 $thread = Item::selectFirstThreadForUser(local_user(), ['ignored'], ['iid' => $item['id']]);
264 if (DBA::isResult($thread)) {
266 'do' => L10n::t("ignore thread"),
267 'undo' => L10n::t("unignore thread"),
268 'toggle' => L10n::t("toggle ignore status"),
269 'classdo' => $thread['ignored'] ? "hidden" : "",
270 'classundo' => $thread['ignored'] ? "" : "hidden",
271 'ignored' => L10n::t('ignored'),
275 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
276 $isstarred = (($item['starred']) ? "starred" : "unstarred");
279 'do' => L10n::t("add star"),
280 'undo' => L10n::t("remove star"),
281 'toggle' => L10n::t("toggle star status"),
282 'classdo' => $item['starred'] ? "hidden" : "",
283 'classundo' => $item['starred'] ? "" : "hidden",
284 'starred' => L10n::t('starred'),
287 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
289 'add' => L10n::t("add tag"),
298 if ($conv->isWritable()) {
300 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
301 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
304 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
308 $comment = $this->getCommentBox($indent);
310 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
314 localize_item($item);
316 $body = prepare_body($item, true);
318 list($categories, $folders) = get_cats_and_terms($item);
321 $text_e = strip_tags($body);
322 $name_e = $profile_name;
324 if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) {
325 $title_e = ucfirst($item['content-warning']);
327 $title_e = $item['title'];
330 $location_e = $location;
331 $owner_name_e = $this->getOwnerName();
333 // Disable features that aren't available in several networks
334 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA]) && isset($buttons["dislike"])) {
335 unset($buttons["dislike"]);
340 if (($item["network"] == Protocol::FEED) && isset($buttons["like"])) {
341 unset($buttons["like"]);
344 if (($item["network"] == Protocol::MAIL) && isset($buttons["like"])) {
345 unset($buttons["like"]);
348 $tags = Term::populateTagsFromItem($item);
351 'template' => $this->getTemplate(),
352 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
353 'suppress_tags' => Config::get('system', 'suppress_tags'),
354 'tags' => $tags['tags'],
355 'hashtags' => $tags['hashtags'],
356 'mentions' => $tags['mentions'],
357 'txt_cats' => L10n::t('Categories:'),
358 'txt_folders' => L10n::t('Filed under:'),
359 'has_cats' => ((count($categories)) ? 'true' : ''),
360 'has_folders' => ((count($folders)) ? 'true' : ''),
361 'categories' => $categories,
362 'folders' => $folders,
365 'id' => $this->getId(),
366 'guid' => urlencode($item['guid']),
367 'isevent' => $isevent,
369 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, $item['author-link']),
370 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), $item['owner-link']),
371 'to' => L10n::t('to'),
372 'via' => L10n::t('via'),
373 'wall' => L10n::t('Wall-to-Wall'),
374 'vwall' => L10n::t('via Wall-To-Wall:'),
375 'profile_url' => $profile_link,
376 'item_photo_menu' => item_photo_menu($item),
378 'thumb' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['author-avatar'], false, ProxyUtils::SIZE_THUMB)),
379 'osparkle' => $osparkle,
380 'sparkle' => $sparkle,
382 'localtime' => DateTimeFormat::local($item['created'], 'r'),
383 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
384 'app' => $item['app'],
385 'created' => Temporal::getRelativeDate($item['created']),
387 'location' => $location_e,
390 'owner_url' => $this->getOwnerUrl(),
391 'owner_photo' => $a->removeBaseURL(ProxyUtils::proxifyUrl($item['owner-avatar'], false, ProxyUtils::SIZE_THUMB)),
392 'owner_name' => htmlentities($owner_name_e),
393 'plink' => get_plink($item),
394 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
395 'isstarred' => $isstarred,
396 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
397 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
399 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
402 'like' => $responses['like']['output'],
403 'dislike' => $responses['dislike']['output'],
404 'responses' => $responses,
405 'switchcomment' => L10n::t('Comment'),
406 'comment' => $comment,
407 'previewing' => $conv->isPreview() ? ' preview ' : '',
408 'wait' => L10n::t('Please wait'),
409 'thread_level' => $thread_level,
411 'network' => $item["network"],
412 'network_name' => ContactSelector::networkToName($item['network'], $item['author-link']),
413 'received' => $item['received'],
414 'commented' => $item['commented'],
415 'created_date' => $item['created'],
418 $arr = ['item' => $item, 'output' => $tmp_item];
419 Addon::callHooks('display_item', $arr);
421 $result = $arr['output'];
423 $result['children'] = [];
424 $children = $this->getChildren();
425 $nb_children = count($children);
426 if ($nb_children > 0) {
427 foreach ($children as $child) {
428 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
431 if (($nb_children > 2) || ($thread_level > 1)) {
432 $result['children'][0]['comment_firstcollapsed'] = true;
433 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
434 $result['children'][0]['hidden_comments_num'] = $total_children;
435 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
436 $result['children'][0]['hide_text'] = L10n::t('show more');
437 if ($thread_level > 1) {
438 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
440 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
445 if ($this->isToplevel()) {
446 $result['total_comments_num'] = "$total_children";
447 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
450 $result['private'] = $item['private'];
451 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
453 if ($this->isThreaded()) {
454 $result['flatten'] = false;
455 $result['threaded'] = true;
457 $result['flatten'] = true;
458 $result['threaded'] = false;
467 public function getId()
469 return $this->getDataValue('id');
475 public function isThreaded()
477 return $this->threaded;
483 * @param object $item The child item to add
487 public function addChild(Post $item)
489 $item_id = $item->getId();
491 Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
493 } elseif ($this->getChild($item->getId())) {
494 Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
498 * Only add what will be displayed
500 if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
502 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
506 $item->setParent($this);
507 $this->children[] = $item;
509 return end($this->children);
513 * Get a child by its ID
515 * @param integer $id The child id
519 public function getChild($id)
521 foreach ($this->getChildren() as $child) {
522 if ($child->getId() == $id) {
531 * Get all our children
535 public function getChildren()
537 return $this->children;
543 * @param object $item The item to set as parent
547 protected function setParent($item)
549 $parent = $this->getParent();
551 $parent->removeChild($this);
554 $this->parent = $item;
555 $this->setThread($item->getThread());
563 protected function removeParent()
565 $this->parent = null;
566 $this->thread = null;
572 * @param object $item The child to be removed
574 * @return boolean Success or failure
576 public function removeChild($item)
578 $id = $item->getId();
579 foreach ($this->getChildren() as $key => $child) {
580 if ($child->getId() == $id) {
581 $child->removeParent();
582 unset($this->children[$key]);
583 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
584 $this->children = array_values($this->children);
588 Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
597 protected function getParent()
599 return $this->parent;
605 * @param object $conv The conversation
609 public function setThread($conv)
611 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
613 $this->thread = $conv;
615 // Set it on our children too
616 foreach ($this->getChildren() as $child) {
617 $child->setThread($conv);
626 public function getThread()
628 return $this->thread;
634 * We shouldn't need this
638 public function getData()
646 * @param object $name key
648 * @return mixed value on success
651 public function getDataValue($name)
653 if (!isset($this->data[$name])) {
654 // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
658 return $this->data[$name];
664 * @param object $name template name
668 private function setTemplate($name)
670 if (!x($this->available_templates, $name)) {
671 Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
675 $this->template = $this->available_templates[$name];
683 private function getTemplate()
685 return $this->template;
689 * Check if this is a toplevel post
693 private function isToplevel()
695 return $this->toplevel;
699 * Check if this is writable
703 private function isWritable()
705 $conv = $this->getThread();
708 // This will allow us to comment on wall-to-wall items owned by our friends
709 // and community forums even if somebody else wrote the post.
710 // bug #517 - this fixes for conversation owner
711 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
715 // this fixes for visitors
716 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
718 return $this->writable;
722 * Count the total of our descendants
726 private function countDescendants()
728 $children = $this->getChildren();
729 $total = count($children);
731 foreach ($children as $child) {
732 $total += $child->countDescendants();
740 * Get the template for the comment box
744 private function getCommentBoxTemplate()
746 return $this->comment_box_template;
750 * Get the comment box
752 * @param string $indent Indent value
754 * @return mixed The comment box string (empty if no comment box)
757 private function getCommentBox($indent)
762 $conv = $this->getThread();
764 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
768 if ($conv->isWritable() && $this->isWritable()) {
769 $qc = $qcomment = null;
772 * Hmmm, code depending on the presence of a particular addon?
773 * This should be better if done by a hook
775 if (Addon::isEnabled('qcomment')) {
776 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
777 $qcomment = (($qc) ? explode("\n", $qc) : null);
780 // Fetch the user id from the parent when the owner user is empty
781 $uid = $conv->getProfileOwner();
782 $parent_uid = $this->getDataValue('uid');
784 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
788 $template = get_markup_template($this->getCommentBoxTemplate());
789 $comment_box = replace_macros($template, [
790 '$return_path' => $a->query_string,
791 '$threaded' => $this->isThreaded(),
793 '$wall' => ($conv->getMode() === 'profile'),
794 '$id' => $this->getId(),
795 '$parent' => $this->getId(),
796 '$qcomment' => $qcomment,
797 '$profile_uid' => $uid,
798 '$mylink' => $a->removeBaseURL($a->contact['url']),
799 '$mytitle' => L10n::t('This is you'),
800 '$myphoto' => $a->removeBaseURL($a->contact['thumb']),
801 '$comment' => L10n::t('Comment'),
802 '$submit' => L10n::t('Submit'),
803 '$edbold' => L10n::t('Bold'),
804 '$editalic' => L10n::t('Italic'),
805 '$eduline' => L10n::t('Underline'),
806 '$edquote' => L10n::t('Quote'),
807 '$edcode' => L10n::t('Code'),
808 '$edimg' => L10n::t('Image'),
809 '$edurl' => L10n::t('Link'),
810 '$edattach' => L10n::t('Link or Media'),
811 '$prompttext' => L10n::t('Please enter a image/video/audio/webpage URL:'),
812 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
813 '$indent' => $indent,
814 '$sourceapp' => L10n::t($a->sourcename),
815 '$ww' => $conv->getMode() === 'network' ? $ww : '',
816 '$rand_num' => random_digits(12)
826 private function getRedirectUrl()
828 return $this->redirect_url;
832 * Check if we are a wall to wall item and set the relevant properties
836 protected function checkWallToWall()
839 $conv = $this->getThread();
840 $this->wall_to_wall = false;
842 if ($this->isToplevel()) {
843 if ($conv->getMode() !== 'profile') {
844 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
845 // On the network page, I am the owner. On the display page it will be the profile owner.
846 // This will have been stored in $a->page_contact by our calling page.
847 // Put this person as the wall owner of the wall-to-wall notice.
849 $this->owner_url = Contact::magicLink($a->page_contact['url']);
850 $this->owner_photo = $a->page_contact['thumb'];
851 $this->owner_name = $a->page_contact['name'];
852 $this->wall_to_wall = true;
853 } elseif ($this->getDataValue('owner-link')) {
854 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
855 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
856 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
858 if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
859 // The author url doesn't match the owner (typically the contact)
860 // and also doesn't match the contact alias.
861 // The name match is a hack to catch several weird cases where URLs are
862 // all over the park. It can be tricked, but this prevents you from
863 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
864 // well that it's the same Bob Smith.
865 // But it could be somebody else with the same name. It just isn't highly likely.
868 $this->owner_photo = $this->getDataValue('owner-avatar');
869 $this->owner_name = $this->getDataValue('owner-name');
870 $this->wall_to_wall = true;
872 $owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'),
873 'network' => $this->getDataValue('owner-network'),
874 'url' => $this->getDataValue('owner-link')];
875 $this->owner_url = Contact::magicLinkbyContact($owner);
881 if (!$this->wall_to_wall) {
882 $this->setTemplate('wall');
883 $this->owner_url = '';
884 $this->owner_photo = '';
885 $this->owner_name = '';
892 private function isWallToWall()
894 return $this->wall_to_wall;
900 private function getOwnerUrl()
902 return $this->owner_url;
908 private function getOwnerName()
910 return $this->owner_name;
916 private function isVisiting()
918 return $this->visiting;