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;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Temporal;
20 require_once 'include/dba.php';
21 require_once 'include/text.php';
22 require_once 'boot.php';
23 require_once 'include/conversation.php';
28 class Post extends BaseObject
31 private $template = null;
32 private $available_templates = [
33 'wall' => 'wall_thread.tpl',
34 'wall2wall' => 'wallwall_thread.tpl'
36 private $comment_box_template = 'comment_item.tpl';
37 private $toplevel = false;
38 private $writable = false;
39 private $children = [];
40 private $parent = null;
41 private $thread = null;
42 private $redirect_url = null;
43 private $owner_url = '';
44 private $owner_photo = '';
45 private $owner_name = '';
46 private $wall_to_wall = false;
47 private $threaded = false;
48 private $visiting = false;
53 * @param array $data data array
55 public function __construct(array $data)
60 $this->setTemplate('wall');
61 $this->toplevel = $this->getId() == $this->getDataValue('parent');
63 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
64 foreach ($_SESSION['remote'] as $visitor) {
65 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
66 $this->visiting = true;
72 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
73 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
75 if (!$this->isToplevel()) {
76 $this->threaded = true;
79 // Prepare the children
80 if (count($data['children'])) {
81 foreach ($data['children'] as $item) {
82 // Only add will be displayed
83 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
85 } elseif (!visible_activity($item)) {
89 // You can always comment on Diaspora and OStatus items
90 if (in_array($item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA]) && (local_user() == $item['uid'])) {
91 $item['writable'] = true;
94 $item['pagedrop'] = $data['pagedrop'];
95 $child = new Post($item);
96 $this->addChild($child);
102 * Get data in a form usable by a conversation template
104 * @param object $conv_responses conversation responses
105 * @param integer $thread_level default = 1
107 * @return mixed The data requested on success
110 public function getTemplateData($conv_responses, $thread_level = 1)
112 require_once "mod/proxy.php";
118 $item = $this->getData();
120 // If the time between "created" and "edited" differs we add
121 // a notice that the post was edited.
122 // Note: In some networks reshared items seem to have (sometimes) a difference
123 // between creation time and edit time of a second. Thats why we add the notice
124 // only if the difference is more than 1 second.
125 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
127 'label' => L10n::t('This entry was edited'),
128 'date' => DateTimeFormat::local($item['edited'], 'r'),
129 'relative' => Temporal::getRelativeDate($item['edited'])
138 $isstarred = "unstarred";
142 $total_children = $this->countDescendants();
144 $conv = $this->getThread();
146 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
147 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
148 ? L10n::t('Private Message')
150 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
152 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
153 if ($item["event-id"] != 0) {
154 $edpost = ["events/event/" . $item['event-id'], L10n::t("Edit")];
156 $edpost = ["editpost/" . $item['id'], L10n::t("Edit")];
158 $dropping = in_array($item['uid'], [0, local_user()]);
163 // Editing on items of not subscribed users isn't currently possible
164 // There are some issues on editing that prevent this.
165 // But also it is an issue of the supported protocols that doesn't allow editing at all.
166 if ($item['uid'] == 0) {
170 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
175 'dropping' => $dropping,
176 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
177 'select' => L10n::t('Select'),
178 'delete' => L10n::t('Delete'),
181 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? L10n::t("save to folder") : false);
183 $diff_author = !link_compare($item['url'], $item['author-link']);
184 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
185 if ($item['author-link'] && (!$item['author-name'])) {
186 $profile_name = $item['author-link'];
190 $profile_link = best_link_url($item, $sp);
191 if ($profile_link === 'mailbox') {
196 $sparkle = ' sparkle';
198 $profile_link = Profile::zrl($profile_link);
201 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
202 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
203 if ($author_contact["thumb"]) {
204 $item['author-thumb'] = $author_contact["thumb"];
206 $item['author-thumb'] = $item['author-avatar'];
210 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
211 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
212 if ($owner_contact["thumb"]) {
213 $item['owner-thumb'] = $owner_contact["thumb"];
215 $item['owner-thumb'] = $item['owner-avatar'];
219 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
220 Addon::callHooks('render_location', $locate);
221 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
223 // process action responses - e.g. like/dislike/attend/agree/whatever
224 $response_verbs = ['like', 'dislike'];
228 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
229 $response_verbs[] = 'attendyes';
230 $response_verbs[] = 'attendno';
231 $response_verbs[] = 'attendmaybe';
232 if ($conv->isWritable()) {
234 $attend = [L10n::t('I will attend'), L10n::t('I will not attend'), L10n::t('I might attend')];
238 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
240 foreach ($response_verbs as $value => $verbs) {
241 $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']) : '';
245 * We should avoid doing this all the time, but it depends on the conversation mode
246 * And the conv mode may change when we change the conv, or it changes its mode
247 * Maybe we should establish a way to be notified about conversation changes
249 $this->checkWallToWall();
251 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
252 $osparkle = ' sparkle';
257 if ($this->isToplevel()) {
258 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
259 $isstarred = (($item['starred']) ? "starred" : "unstarred");
262 'do' => L10n::t("add star"),
263 'undo' => L10n::t("remove star"),
264 'toggle' => L10n::t("toggle star status"),
265 'classdo' => $item['starred'] ? "hidden" : "",
266 'classundo' => $item['starred'] ? "" : "hidden",
267 'starred' => L10n::t('starred'),
270 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
271 if (DBM::is_result($thread)) {
273 'do' => L10n::t("ignore thread"),
274 'undo' => L10n::t("unignore thread"),
275 'toggle' => L10n::t("toggle ignore status"),
276 'classdo' => $thread['ignored'] ? "hidden" : "",
277 'classundo' => $thread['ignored'] ? "" : "hidden",
278 'ignored' => L10n::t('ignored'),
282 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
284 'add' => L10n::t("add tag"),
293 if ($conv->isWritable()) {
295 'like' => [L10n::t("I like this \x28toggle\x29"), L10n::t("like")],
296 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [L10n::t("I don't like this \x28toggle\x29"), L10n::t("dislike")] : '',
299 $buttons['share'] = [L10n::t('Share this'), L10n::t('share')];
303 $comment = $this->getCommentBox($indent);
305 if (strcmp(DateTimeFormat::utc($item['created']), DateTimeFormat::utc('now - 12 hours')) > 0) {
309 localize_item($item);
311 $body = prepare_body($item, true);
313 list($categories, $folders) = get_cats_and_terms($item);
316 $text_e = strip_tags($body);
317 $name_e = $profile_name;
318 $title_e = $item['title'];
319 $location_e = $location;
320 $owner_name_e = $this->getOwnerName();
322 // Disable features that aren't available in several networks
323 if (!in_array($item["item_network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
324 unset($buttons["dislike"]);
329 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
330 unset($buttons["like"]);
333 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
334 unset($buttons["like"]);
338 'template' => $this->getTemplate(),
339 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
340 'tags' => $item['tags'],
341 'hashtags' => $item['hashtags'],
342 'mentions' => $item['mentions'],
343 'txt_cats' => L10n::t('Categories:'),
344 'txt_folders' => L10n::t('Filed under:'),
345 'has_cats' => ((count($categories)) ? 'true' : ''),
346 'has_folders' => ((count($folders)) ? 'true' : ''),
347 'categories' => $categories,
348 'folders' => $folders,
351 'id' => $this->getId(),
352 'guid' => urlencode($item['guid']),
353 'isevent' => $isevent,
355 'linktitle' => L10n::t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
356 'olinktitle' => L10n::t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
357 'to' => L10n::t('to'),
358 'via' => L10n::t('via'),
359 'wall' => L10n::t('Wall-to-Wall'),
360 'vwall' => L10n::t('via Wall-To-Wall:'),
361 'profile_url' => $profile_link,
362 'item_photo_menu' => item_photo_menu($item),
364 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
365 'osparkle' => $osparkle,
366 'sparkle' => $sparkle,
368 'localtime' => DateTimeFormat::local($item['created'], 'r'),
369 'ago' => $item['app'] ? L10n::t('%s from %s', Temporal::getRelativeDate($item['created']), $item['app']) : Temporal::getRelativeDate($item['created']),
370 'app' => $item['app'],
371 'created' => Temporal::getRelativeDate($item['created']),
373 'location' => $location_e,
376 'owner_url' => $this->getOwnerUrl(),
377 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
378 'owner_name' => htmlentities($owner_name_e),
379 'plink' => get_plink($item),
380 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
381 'isstarred' => $isstarred,
382 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
383 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
385 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
388 'like' => $responses['like']['output'],
389 'dislike' => $responses['dislike']['output'],
390 'responses' => $responses,
391 'switchcomment' => L10n::t('Comment'),
392 'comment' => $comment,
393 'previewing' => $conv->isPreview() ? ' preview ' : '',
394 'wait' => L10n::t('Please wait'),
395 'thread_level' => $thread_level,
397 'network' => $item["item_network"],
398 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
399 'received' => $item['received'],
400 'commented' => $item['commented'],
401 'created_date' => $item['created'],
404 $arr = ['item' => $item, 'output' => $tmp_item];
405 Addon::callHooks('display_item', $arr);
407 $result = $arr['output'];
409 $result['children'] = [];
410 $children = $this->getChildren();
411 $nb_children = count($children);
412 if ($nb_children > 0) {
413 foreach ($children as $child) {
414 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
417 if (($nb_children > 2) || ($thread_level > 1)) {
418 $result['children'][0]['comment_firstcollapsed'] = true;
419 $result['children'][0]['num_comments'] = L10n::tt('%d comment', '%d comments', $total_children);
420 $result['children'][0]['hidden_comments_num'] = $total_children;
421 $result['children'][0]['hidden_comments_text'] = L10n::tt('comment', 'comments', $total_children);
422 $result['children'][0]['hide_text'] = L10n::t('show more');
423 if ($thread_level > 1) {
424 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
426 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
431 if ($this->isToplevel()) {
432 $result['total_comments_num'] = "$total_children";
433 $result['total_comments_text'] = L10n::tt('comment', 'comments', $total_children);
436 $result['private'] = $item['private'];
437 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
439 if ($this->isThreaded()) {
440 $result['flatten'] = false;
441 $result['threaded'] = true;
443 $result['flatten'] = true;
444 $result['threaded'] = false;
453 public function getId()
455 return $this->getDataValue('id');
461 public function isThreaded()
463 return $this->threaded;
469 * @param object $item The child item to add
473 public function addChild(Post $item)
475 $item_id = $item->getId();
477 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
479 } elseif ($this->getChild($item->getId())) {
480 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
484 * Only add what will be displayed
486 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
488 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
492 $item->setParent($this);
493 $this->children[] = $item;
495 return end($this->children);
499 * Get a child by its ID
501 * @param integer $id The child id
505 public function getChild($id)
507 foreach ($this->getChildren() as $child) {
508 if ($child->getId() == $id) {
517 * Get all our children
521 public function getChildren()
523 return $this->children;
529 * @param object $item The item to set as parent
533 protected function setParent($item)
535 $parent = $this->getParent();
537 $parent->removeChild($this);
540 $this->parent = $item;
541 $this->setThread($item->getThread());
549 protected function removeParent()
551 $this->parent = null;
552 $this->thread = null;
558 * @param object $item The child to be removed
560 * @return boolean Success or failure
562 public function removeChild($item)
564 $id = $item->getId();
565 foreach ($this->getChildren() as $key => $child) {
566 if ($child->getId() == $id) {
567 $child->removeParent();
568 unset($this->children[$key]);
569 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
570 $this->children = array_values($this->children);
574 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
583 protected function getParent()
585 return $this->parent;
591 * @param object $conv The conversation
595 public function setThread($conv)
597 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
599 $this->thread = $conv;
601 // Set it on our children too
602 foreach ($this->getChildren() as $child) {
603 $child->setThread($conv);
612 public function getThread()
614 return $this->thread;
620 * We shouldn't need this
624 public function getData()
632 * @param object $name key
634 * @return mixed value on success
637 public function getDataValue($name)
639 if (!isset($this->data[$name])) {
640 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
644 return $this->data[$name];
650 * @param object $name template name
654 private function setTemplate($name)
656 if (!x($this->available_templates, $name)) {
657 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
661 $this->template = $this->available_templates[$name];
669 private function getTemplate()
671 return $this->template;
675 * Check if this is a toplevel post
679 private function isToplevel()
681 return $this->toplevel;
685 * Check if this is writable
689 private function isWritable()
691 $conv = $this->getThread();
694 // This will allow us to comment on wall-to-wall items owned by our friends
695 // and community forums even if somebody else wrote the post.
696 // bug #517 - this fixes for conversation owner
697 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
701 // this fixes for visitors
702 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
704 return $this->writable;
708 * Count the total of our descendants
712 private function countDescendants()
714 $children = $this->getChildren();
715 $total = count($children);
717 foreach ($children as $child) {
718 $total += $child->countDescendants();
726 * Get the template for the comment box
730 private function getCommentBoxTemplate()
732 return $this->comment_box_template;
736 * Get the comment box
738 * @param string $indent Indent value
740 * @return mixed The comment box string (empty if no comment box)
743 private function getCommentBox($indent)
748 $conv = $this->getThread();
750 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
754 if ($conv->isWritable() && $this->isWritable()) {
755 $qc = $qcomment = null;
758 * Hmmm, code depending on the presence of a particular addon?
759 * This should be better if done by a hook
761 if (in_array('qcomment', $a->addons)) {
762 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
763 $qcomment = (($qc) ? explode("\n", $qc) : null);
766 // Fetch the user id from the parent when the owner user is empty
767 $uid = $conv->getProfileOwner();
768 $parent_uid = $this->getDataValue('uid');
770 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
774 $template = get_markup_template($this->getCommentBoxTemplate());
775 $comment_box = replace_macros($template, [
776 '$return_path' => $a->query_string,
777 '$threaded' => $this->isThreaded(),
779 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
780 '$id' => $this->getId(),
781 '$parent' => $this->getId(),
782 '$qcomment' => $qcomment,
783 '$profile_uid' => $uid,
784 '$mylink' => $a->remove_baseurl($a->contact['url']),
785 '$mytitle' => L10n::t('This is you'),
786 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
787 '$comment' => L10n::t('Comment'),
788 '$submit' => L10n::t('Submit'),
789 '$edbold' => L10n::t('Bold'),
790 '$editalic' => L10n::t('Italic'),
791 '$eduline' => L10n::t('Underline'),
792 '$edquote' => L10n::t('Quote'),
793 '$edcode' => L10n::t('Code'),
794 '$edimg' => L10n::t('Image'),
795 '$edurl' => L10n::t('Link'),
796 '$edvideo' => L10n::t('Video'),
797 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? L10n::t('Preview') : ''),
798 '$indent' => $indent,
799 '$sourceapp' => L10n::t($a->sourcename),
800 '$ww' => $conv->getMode() === 'network' ? $ww : '',
801 '$rand_num' => random_digits(12)
811 private function getRedirectUrl()
813 return $this->redirect_url;
817 * Check if we are a wall to wall item and set the relevant properties
821 protected function checkWallToWall()
824 $conv = $this->getThread();
825 $this->wall_to_wall = false;
827 if ($this->isToplevel()) {
828 if ($conv->getMode() !== 'profile') {
829 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
830 // On the network page, I am the owner. On the display page it will be the profile owner.
831 // This will have been stored in $a->page_contact by our calling page.
832 // Put this person as the wall owner of the wall-to-wall notice.
834 $this->owner_url = Profile::zrl($a->page_contact['url']);
835 $this->owner_photo = $a->page_contact['thumb'];
836 $this->owner_name = $a->page_contact['name'];
837 $this->wall_to_wall = true;
838 } elseif ($this->getDataValue('owner-link')) {
839 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
840 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
841 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
843 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
844 // The author url doesn't match the owner (typically the contact)
845 // and also doesn't match the contact alias.
846 // The name match is a hack to catch several weird cases where URLs are
847 // all over the park. It can be tricked, but this prevents you from
848 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
849 // well that it's the same Bob Smith.
850 // But it could be somebody else with the same name. It just isn't highly likely.
853 $this->owner_photo = $this->getDataValue('owner-avatar');
854 $this->owner_name = $this->getDataValue('owner-name');
855 $this->wall_to_wall = true;
856 // If it is our contact, use a friendly redirect link
857 if ($this->getDataValue('network') === NETWORK_DFRN
858 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
860 $this->owner_url = $this->getRedirectUrl();
862 $this->owner_url = Profile::zrl($this->getDataValue('owner-link'));
869 if (!$this->wall_to_wall) {
870 $this->setTemplate('wall');
871 $this->owner_url = '';
872 $this->owner_photo = '';
873 $this->owner_name = '';
880 private function isWallToWall()
882 return $this->wall_to_wall;
888 private function getOwnerUrl()
890 return $this->owner_url;
896 private function getOwnerName()
898 return $this->owner_name;
904 private function isVisiting()
906 return $this->visiting;