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\L10n;
12 use Friendica\Core\PConfig;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Profile;
18 require_once 'include/dba.php';
19 require_once 'include/text.php';
20 require_once 'boot.php';
21 require_once 'include/conversation.php';
26 class Post extends BaseObject
29 private $template = null;
30 private $available_templates = [
31 'wall' => 'wall_thread.tpl',
32 'wall2wall' => 'wallwall_thread.tpl'
34 private $comment_box_template = 'comment_item.tpl';
35 private $toplevel = false;
36 private $writable = false;
37 private $children = [];
38 private $parent = null;
39 private $thread = null;
40 private $redirect_url = null;
41 private $owner_url = '';
42 private $owner_photo = '';
43 private $owner_name = '';
44 private $wall_to_wall = false;
45 private $threaded = false;
46 private $visiting = false;
51 * @param array $data data array
53 public function __construct(array $data)
58 $this->setTemplate('wall');
59 $this->toplevel = $this->getId() == $this->getDataValue('parent');
61 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
62 foreach ($_SESSION['remote'] as $visitor) {
63 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
64 $this->visiting = true;
70 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
71 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
73 if (!$this->isToplevel()) {
74 $this->threaded = true;
77 // Prepare the children
78 if (count($data['children'])) {
79 foreach ($data['children'] as $item) {
80 // Only add will be displayed
81 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
83 } elseif (!visible_activity($item)) {
87 // You can always comment on Diaspora and OStatus items
88 if (in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA]) && (local_user() == $item['uid'])) {
89 $item['writable'] = true;
92 $item['pagedrop'] = $data['pagedrop'];
93 $child = new Post($item);
94 $this->addChild($child);
100 * Get data in a form usable by a conversation template
102 * @param object $conv_responses conversation responses
103 * @param integer $thread_level default = 1
105 * @return mixed The data requested on success
108 public function getTemplateData($conv_responses, $thread_level = 1)
110 require_once "mod/proxy.php";
116 $item = $this->getData();
118 // If the time between "created" and "edited" differs we add
119 // a notice that the post was edited.
120 // Note: In some networks reshared items seem to have (sometimes) a difference
121 // between creation time and edit time of a second. Thats why we add the notice
122 // only if the difference is more than 1 second.
123 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
125 'label' => L10n::t('This entry was edited'),
126 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
127 'relative' => relative_date($item['edited'])
136 $isstarred = "unstarred";
140 $total_children = $this->countDescendants();
142 $conv = $this->getThread();
144 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
145 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
146 ? L10n::t('Private Message')
148 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
150 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
151 if ($item["event-id"] != 0) {
152 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
154 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
156 $dropping = in_array($item['uid'], [0, local_user()]);
161 // Editing on items of not subscribed users isn't currently possible
162 // There are some issues on editing that prevent this.
163 // But also it is an issue of the supported protocols that doesn't allow editing at all.
164 if ($item['uid'] == 0) {
168 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
173 'dropping' => $dropping,
174 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
175 'select' => L10n::t('Select'),
176 'delete' => L10n::t('Delete'),
179 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
181 $diff_author = !link_compare($item['url'], $item['author-link']);
182 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
183 if ($item['author-link'] && (!$item['author-name'])) {
184 $profile_name = $item['author-link'];
188 $profile_link = best_link_url($item, $sp);
189 if ($profile_link === 'mailbox') {
194 $sparkle = ' sparkle';
196 $profile_link = Profile::zrl($profile_link);
199 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
200 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
201 if ($author_contact["thumb"]) {
202 $item['author-thumb'] = $author_contact["thumb"];
204 $item['author-thumb'] = $item['author-avatar'];
208 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
209 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
210 if ($owner_contact["thumb"]) {
211 $item['owner-thumb'] = $owner_contact["thumb"];
213 $item['owner-thumb'] = $item['owner-avatar'];
217 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
218 Addon::callHooks('render_location', $locate);
219 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
221 // process action responses - e.g. like/dislike/attend/agree/whatever
222 $response_verbs = ['like', 'dislike'];
226 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
227 $response_verbs[] = 'attendyes';
228 $response_verbs[] = 'attendno';
229 $response_verbs[] = 'attendmaybe';
230 if ($conv->isWritable()) {
232 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
236 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
238 foreach ($response_verbs as $value => $verbs) {
239 $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']) : '';
243 * We should avoid doing this all the time, but it depends on the conversation mode
244 * And the conv mode may change when we change the conv, or it changes its mode
245 * Maybe we should establish a way to be notified about conversation changes
247 $this->checkWallToWall();
249 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
250 $osparkle = ' sparkle';
255 if ($this->isToplevel()) {
256 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
257 $isstarred = (($item['starred']) ? "starred" : "unstarred");
260 'do' => L10n::t("add star"),
261 'undo' => L10n::t("remove star"),
262 'toggle' => L10n::t("toggle star status"),
263 'classdo' => $item['starred'] ? "hidden" : "",
264 'classundo' => $item['starred'] ? "" : "hidden",
265 'starred' => L10n::t('starred'),
268 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
269 if (DBM::is_result($thread)) {
271 'do' => L10n::t("ignore thread"),
272 'undo' => L10n::t("unignore thread"),
273 'toggle' => L10n::t("toggle ignore status"),
274 'classdo' => $thread['ignored'] ? "hidden" : "",
275 'classundo' => $thread['ignored'] ? "" : "hidden",
276 'ignored' => L10n::t('ignored'),
280 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
282 'add' => L10n::t("add tag"),
291 if ($conv->isWritable()) {
293 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
294 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
297 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
301 $comment = $this->getCommentBox($indent);
303 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
307 localize_item($item);
309 $body = prepare_body($item, true);
311 list($categories, $folders) = get_cats_and_terms($item);
314 $text_e = strip_tags($body);
315 $name_e = $profile_name;
316 $title_e = $item['title'];
317 $location_e = $location;
318 $owner_name_e = $this->getOwnerName();
320 // Disable features that aren't available in several networks
321 if (!in_array($item["item_network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
322 unset($buttons["dislike"]);
327 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
328 unset($buttons["like"]);
331 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
332 unset($buttons["like"]);
336 'template' => $this->getTemplate(),
337 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
338 'tags' => $item['tags'],
339 'hashtags' => $item['hashtags'],
340 'mentions' => $item['mentions'],
341 'txt_cats' => L10n::t('Categories:'),
342 'txt_folders' => L10n::t('Filed under:'),
343 'has_cats' => ((count($categories)) ? 'true' : ''),
344 'has_folders' => ((count($folders)) ? 'true' : ''),
345 'categories' => $categories,
346 'folders' => $folders,
349 'id' => $this->getId(),
350 'guid' => urlencode($item['guid']),
351 'isevent' => $isevent,
353 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
354 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
355 'to' => L10n::t('to'),
356 'via' => L10n::t('via'),
357 'wall' => L10n::t('Wall-to-Wall'),
358 'vwall' => L10n::t('via Wall-To-Wall:'),
359 'profile_url' => $profile_link,
360 'item_photo_menu' => item_photo_menu($item),
362 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
363 'osparkle' => $osparkle,
364 'sparkle' => $sparkle,
366 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
367 'ago' => $item['app'] ? L10n::t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
368 'app' => $item['app'],
369 'created' => relative_date($item['created']),
371 'location' => $location_e,
374 'owner_url' => $this->getOwnerUrl(),
375 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
376 'owner_name' => htmlentities($owner_name_e),
377 'plink' => get_plink($item),
378 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
379 'isstarred' => $isstarred,
380 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
381 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
383 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
386 'like' => $responses['like']['output'],
387 'dislike' => $responses['dislike']['output'],
388 'responses' => $responses,
389 'switchcomment' => L10n::t('Comment'),
390 'comment' => $comment,
391 'previewing' => $conv->isPreview() ? ' preview ' : '',
392 'wait' => L10n::t('Please wait'),
393 'thread_level' => $thread_level,
395 'network' => $item["item_network"],
396 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
397 'received' => $item['received'],
398 'commented' => $item['commented'],
399 'created_date' => $item['created'],
402 $arr = ['item' => $item, 'output' => $tmp_item];
403 Addon::callHooks('display_item', $arr);
405 $result = $arr['output'];
407 $result['children'] = [];
408 $children = $this->getChildren();
409 $nb_children = count($children);
410 if ($nb_children > 0) {
411 foreach ($children as $child) {
412 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
415 if (($nb_children > 2) || ($thread_level > 1)) {
416 $result['children'][0]['comment_firstcollapsed'] = true;
417 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
418 $result['children'][0]['hidden_comments_num'] = $total_children;
419 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
420 $result['children'][0]['hide_text'] = L10n::t('show more');
421 if ($thread_level > 1) {
422 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
424 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
429 if ($this->isToplevel()) {
430 $result['total_comments_num'] = "$total_children";
431 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
434 $result['private'] = $item['private'];
435 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
437 if ($this->isThreaded()) {
438 $result['flatten'] = false;
439 $result['threaded'] = true;
441 $result['flatten'] = true;
442 $result['threaded'] = false;
451 public function getId()
453 return $this->getDataValue('id');
459 public function isThreaded()
461 return $this->threaded;
467 * @param object $item The child item to add
471 public function addChild(Post $item)
473 $item_id = $item->getId();
475 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
477 } elseif ($this->getChild($item->getId())) {
478 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
482 * Only add what will be displayed
484 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
486 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
490 $item->setParent($this);
491 $this->children[] = $item;
493 return end($this->children);
497 * Get a child by its ID
499 * @param integer $id The child id
503 public function getChild($id)
505 foreach ($this->getChildren() as $child) {
506 if ($child->getId() == $id) {
515 * Get all our children
519 public function getChildren()
521 return $this->children;
527 * @param object $item The item to set as parent
531 protected function setParent($item)
533 $parent = $this->getParent();
535 $parent->removeChild($this);
538 $this->parent = $item;
539 $this->setThread($item->getThread());
547 protected function removeParent()
549 $this->parent = null;
550 $this->thread = null;
556 * @param object $item The child to be removed
558 * @return boolean Success or failure
560 public function removeChild($item)
562 $id = $item->getId();
563 foreach ($this->getChildren() as $key => $child) {
564 if ($child->getId() == $id) {
565 $child->removeParent();
566 unset($this->children[$key]);
567 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
568 $this->children = array_values($this->children);
572 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
581 protected function getParent()
583 return $this->parent;
589 * @param object $conv The conversation
593 public function setThread($conv)
595 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
597 $this->thread = $conv;
599 // Set it on our children too
600 foreach ($this->getChildren() as $child) {
601 $child->setThread($conv);
610 public function getThread()
612 return $this->thread;
618 * We shouldn't need this
622 public function getData()
630 * @param object $name key
632 * @return mixed value on success
635 public function getDataValue($name)
637 if (!isset($this->data[$name])) {
638 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
642 return $this->data[$name];
648 * @param object $name template name
652 private function setTemplate($name)
654 if (!x($this->available_templates, $name)) {
655 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
659 $this->template = $this->available_templates[$name];
667 private function getTemplate()
669 return $this->template;
673 * Check if this is a toplevel post
677 private function isToplevel()
679 return $this->toplevel;
683 * Check if this is writable
687 private function isWritable()
689 $conv = $this->getThread();
692 // This will allow us to comment on wall-to-wall items owned by our friends
693 // and community forums even if somebody else wrote the post.
694 // bug #517 - this fixes for conversation owner
695 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
699 // this fixes for visitors
700 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
702 return $this->writable;
706 * Count the total of our descendants
710 private function countDescendants()
712 $children = $this->getChildren();
713 $total = count($children);
715 foreach ($children as $child) {
716 $total += $child->countDescendants();
724 * Get the template for the comment box
728 private function getCommentBoxTemplate()
730 return $this->comment_box_template;
734 * Get the comment box
736 * @param string $indent Indent value
738 * @return mixed The comment box string (empty if no comment box)
741 private function getCommentBox($indent)
746 $conv = $this->getThread();
748 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
752 if ($conv->isWritable() && $this->isWritable()) {
753 $qc = $qcomment = null;
756 * Hmmm, code depending on the presence of a particular addon?
757 * This should be better if done by a hook
759 if (in_array('qcomment', $a->addons)) {
760 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
761 $qcomment = (($qc) ? explode("\n", $qc) : null);
764 // Fetch the user id from the parent when the owner user is empty
765 $uid = $conv->getProfileOwner();
766 $parent_uid = $this->getDataValue('uid');
768 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
772 $template = get_markup_template($this->getCommentBoxTemplate());
773 $comment_box = replace_macros($template, [
774 '$return_path' => $a->query_string,
775 '$threaded' => $this->isThreaded(),
777 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
778 '$id' => $this->getId(),
779 '$parent' => $this->getId(),
780 '$qcomment' => $qcomment,
781 '$profile_uid' => $uid,
782 '$mylink' => $a->remove_baseurl($a->contact['url']),
783 '$mytitle' => L10n::t('This is you'),
784 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
785 '$comment' => L10n::t('Comment'),
786 '$submit' => L10n::t('Submit'),
787 '$edbold' => L10n::t('Bold'),
788 '$editalic' => L10n::t('Italic'),
789 '$eduline' => L10n::t('Underline'),
790 '$edquote' => L10n::t('Quote'),
791 '$edcode' => L10n::t('Code'),
792 '$edimg' => L10n::t('Image'),
793 '$edurl' => L10n::t('Link'),
794 '$edvideo' => L10n::t('Video'),
795 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
796 '$indent' => $indent,
797 '$sourceapp' => L10n::t($a->sourcename),
798 '$ww' => $conv->getMode() === 'network' ? $ww : '',
799 '$rand_num' => random_digits(12)
809 private function getRedirectUrl()
811 return $this->redirect_url;
815 * Check if we are a wall to wall item and set the relevant properties
819 protected function checkWallToWall()
822 $conv = $this->getThread();
823 $this->wall_to_wall = false;
825 if ($this->isToplevel()) {
826 if ($conv->getMode() !== 'profile') {
827 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
828 // On the network page, I am the owner. On the display page it will be the profile owner.
829 // This will have been stored in $a->page_contact by our calling page.
830 // Put this person as the wall owner of the wall-to-wall notice.
832 $this->owner_url = Profile::zrl($a->page_contact['url']);
833 $this->owner_photo = $a->page_contact['thumb'];
834 $this->owner_name = $a->page_contact['name'];
835 $this->wall_to_wall = true;
836 } elseif ($this->getDataValue('owner-link')) {
837 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
838 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
839 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
841 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
842 // The author url doesn't match the owner (typically the contact)
843 // and also doesn't match the contact alias.
844 // The name match is a hack to catch several weird cases where URLs are
845 // all over the park. It can be tricked, but this prevents you from
846 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
847 // well that it's the same Bob Smith.
848 // But it could be somebody else with the same name. It just isn't highly likely.
851 $this->owner_photo = $this->getDataValue('owner-avatar');
852 $this->owner_name = $this->getDataValue('owner-name');
853 $this->wall_to_wall = true;
854 // If it is our contact, use a friendly redirect link
855 if ($this->getDataValue('network') === NETWORK_DFRN
856 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
858 $this->owner_url = $this->getRedirectUrl();
860 $this->owner_url = Profile::zrl($this->getDataValue('owner-link'));
867 if (!$this->wall_to_wall) {
868 $this->setTemplate('wall');
869 $this->owner_url = '';
870 $this->owner_photo = '';
871 $this->owner_name = '';
878 private function isWallToWall()
880 return $this->wall_to_wall;
886 private function getOwnerUrl()
888 return $this->owner_url;
894 private function getOwnerName()
896 return $this->owner_name;
902 private function isVisiting()
904 return $this->visiting;