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\PConfig;
11 use Friendica\Database\DBM;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Profile;
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
18 require_once 'boot.php';
19 require_once 'include/conversation.php';
24 class Post extends BaseObject
27 private $template = null;
28 private $available_templates = [
29 'wall' => 'wall_thread.tpl',
30 'wall2wall' => 'wallwall_thread.tpl'
32 private $comment_box_template = 'comment_item.tpl';
33 private $toplevel = false;
34 private $writable = false;
35 private $children = [];
36 private $parent = null;
37 private $thread = null;
38 private $redirect_url = null;
39 private $owner_url = '';
40 private $owner_photo = '';
41 private $owner_name = '';
42 private $wall_to_wall = false;
43 private $threaded = false;
44 private $visiting = false;
49 * @param array $data data array
51 public function __construct(array $data)
56 $this->setTemplate('wall');
57 $this->toplevel = $this->getId() == $this->getDataValue('parent');
59 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
60 foreach ($_SESSION['remote'] as $visitor) {
61 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
62 $this->visiting = true;
68 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
69 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
71 if (!$this->isToplevel()) {
72 $this->threaded = true;
75 // Prepare the children
76 if (count($data['children'])) {
77 foreach ($data['children'] as $item) {
78 // Only add will be displayed
79 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
81 } elseif (!visible_activity($item)) {
85 // You can always comment on Diaspora and OStatus items
86 // The empty network can happen with your local (self) contact
87 if (in_array($item['network'], ['', NETWORK_OSTATUS, NETWORK_DIASPORA]) && (local_user() == $item['uid'])) {
88 $item['writable'] = true;
91 $item['pagedrop'] = $data['pagedrop'];
92 $child = new Post($item);
93 $this->addChild($child);
99 * Get data in a form usable by a conversation template
101 * @param object $conv_responses conversation responses
102 * @param integer $thread_level default = 1
104 * @return mixed The data requested on success
107 public function getTemplateData($conv_responses, $thread_level = 1)
109 require_once "mod/proxy.php";
115 $item = $this->getData();
117 // If the time between "created" and "edited" differs we add
118 // a notice that the post was edited.
119 // Note: In some networks reshared items seem to have (sometimes) a difference
120 // between creation time and edit time of a second. Thats why we add the notice
121 // only if the difference is more than 1 second.
122 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
124 'label' => t('This entry was edited'),
125 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
126 'relative' => relative_date($item['edited'])
135 $isstarred = "unstarred";
139 $total_children = $this->countDescendants();
141 $conv = $this->getThread();
143 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
144 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
145 ? t('Private Message')
147 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
149 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
150 if ($item["event-id"] != 0) {
151 $edpost = ["events/event/" . $item['event-id'], t("Edit")];
153 $edpost = ["editpost/" . $item['id'], t("Edit")];
155 $dropping = in_array($item['uid'], [0, local_user()]);
160 // Editing on items of not subscribed users isn't currently possible
161 // There are some issues on editing that prevent this.
162 // But also it is an issue of the supported protocols that doesn't allow editing at all.
163 if ($item['uid'] == 0) {
167 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
172 'dropping' => $dropping,
173 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
174 'select' => t('Select'),
175 'delete' => t('Delete'),
178 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? t("save to folder") : false);
180 $diff_author = !link_compare($item['url'], $item['author-link']);
181 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
182 if ($item['author-link'] && (!$item['author-name'])) {
183 $profile_name = $item['author-link'];
187 $profile_link = best_link_url($item, $sp);
188 if ($profile_link === 'mailbox') {
193 $sparkle = ' sparkle';
195 $profile_link = Profile::zrl($profile_link);
198 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
199 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
200 if ($author_contact["thumb"]) {
201 $item['author-thumb'] = $author_contact["thumb"];
203 $item['author-thumb'] = $item['author-avatar'];
207 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
208 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
209 if ($owner_contact["thumb"]) {
210 $item['owner-thumb'] = $owner_contact["thumb"];
212 $item['owner-thumb'] = $item['owner-avatar'];
216 $locate = ['location' => $item['location'], 'coord' => $item['coord'], 'html' => ''];
217 call_hooks('render_location', $locate);
218 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
220 // process action responses - e.g. like/dislike/attend/agree/whatever
221 $response_verbs = ['like', 'dislike'];
225 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
226 $response_verbs[] = 'attendyes';
227 $response_verbs[] = 'attendno';
228 $response_verbs[] = 'attendmaybe';
229 if ($conv->isWritable()) {
231 $attend = [t('I will attend'), t('I will not attend'), t('I might attend')];
235 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
237 foreach ($response_verbs as $value => $verbs) {
238 $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']) : '';
242 * We should avoid doing this all the time, but it depends on the conversation mode
243 * And the conv mode may change when we change the conv, or it changes its mode
244 * Maybe we should establish a way to be notified about conversation changes
246 $this->checkWallToWall();
248 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
249 $osparkle = ' sparkle';
254 if ($this->isToplevel()) {
255 if ($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) {
256 $isstarred = (($item['starred']) ? "starred" : "unstarred");
259 'do' => t("add star"),
260 'undo' => t("remove star"),
261 'toggle' => t("toggle star status"),
262 'classdo' => $item['starred'] ? "hidden" : "",
263 'classundo' => $item['starred'] ? "" : "hidden",
264 'starred' => t('starred'),
267 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
268 if (DBM::is_result($thread)) {
270 'do' => t("ignore thread"),
271 'undo' => t("unignore thread"),
272 'toggle' => t("toggle ignore status"),
273 'classdo' => $thread['ignored'] ? "hidden" : "",
274 'classundo' => $thread['ignored'] ? "" : "hidden",
275 'ignored' => t('ignored'),
279 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
281 'add' => t("add tag"),
290 if ($conv->isWritable()) {
292 'like' => [t("I like this \x28toggle\x29"), t("like")],
293 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [t("I don't like this \x28toggle\x29"), t("dislike")] : '',
296 $buttons['share'] = [t('Share this'), t('share')];
299 // If a contact isn't writable, we cannot send a like or dislike to it
300 if (!$item['writable']) {
301 unset($buttons["like"]);
302 unset($buttons["dislike"]);
306 $comment = $this->getCommentBox($indent);
308 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
312 localize_item($item);
314 $body = prepare_body($item, true);
316 list($categories, $folders) = get_cats_and_terms($item);
319 $text_e = strip_tags($body);
320 $name_e = $profile_name;
321 $title_e = $item['title'];
322 $location_e = $location;
323 $owner_name_e = $this->getOwnerName();
325 // Disable features that aren't available in several networks
326 if (!in_array($item["item_network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
327 unset($buttons["dislike"]);
332 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
333 unset($buttons["like"]);
336 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
337 unset($buttons["like"]);
341 'template' => $this->getTemplate(),
342 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
343 'tags' => $item['tags'],
344 'hashtags' => $item['hashtags'],
345 'mentions' => $item['mentions'],
346 'txt_cats' => t('Categories:'),
347 'txt_folders' => t('Filed under:'),
348 'has_cats' => ((count($categories)) ? 'true' : ''),
349 'has_folders' => ((count($folders)) ? 'true' : ''),
350 'categories' => $categories,
351 'folders' => $folders,
354 'id' => $this->getId(),
355 'guid' => urlencode($item['guid']),
356 'isevent' => $isevent,
358 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
359 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
362 'wall' => t('Wall-to-Wall'),
363 'vwall' => t('via Wall-To-Wall:'),
364 'profile_url' => $profile_link,
365 'item_photo_menu' => item_photo_menu($item),
367 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
368 'osparkle' => $osparkle,
369 'sparkle' => $sparkle,
371 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
372 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
373 'app' => $item['app'],
374 'created' => relative_date($item['created']),
376 'location' => $location_e,
379 'owner_url' => $this->getOwnerUrl(),
380 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
381 'owner_name' => htmlentities($owner_name_e),
382 'plink' => get_plink($item),
383 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
384 'isstarred' => $isstarred,
385 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
386 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
388 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
391 'like' => $responses['like']['output'],
392 'dislike' => $responses['dislike']['output'],
393 'responses' => $responses,
394 'switchcomment' => t('Comment'),
395 'comment' => $comment,
396 'previewing' => $conv->isPreview() ? ' preview ' : '',
397 'wait' => t('Please wait'),
398 'thread_level' => $thread_level,
400 'network' => $item["item_network"],
401 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
402 'received' => $item['received'],
403 'commented' => $item['commented'],
404 'created_date' => $item['created'],
407 $arr = ['item' => $item, 'output' => $tmp_item];
408 call_hooks('display_item', $arr);
410 $result = $arr['output'];
412 $result['children'] = [];
413 $children = $this->getChildren();
414 $nb_children = count($children);
415 if ($nb_children > 0) {
416 foreach ($children as $child) {
417 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
420 if (($nb_children > 2) || ($thread_level > 1)) {
421 $result['children'][0]['comment_firstcollapsed'] = true;
422 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
423 $result['children'][0]['hidden_comments_num'] = $total_children;
424 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
425 $result['children'][0]['hide_text'] = t('show more');
426 if ($thread_level > 1) {
427 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
429 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
434 if ($this->isToplevel()) {
435 $result['total_comments_num'] = "$total_children";
436 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
439 $result['private'] = $item['private'];
440 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
442 if ($this->isThreaded()) {
443 $result['flatten'] = false;
444 $result['threaded'] = true;
446 $result['flatten'] = true;
447 $result['threaded'] = false;
456 public function getId()
458 return $this->getDataValue('id');
464 public function isThreaded()
466 return $this->threaded;
472 * @param object $item The child item to add
476 public function addChild(Post $item)
478 $item_id = $item->getId();
480 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
482 } elseif ($this->getChild($item->getId())) {
483 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
487 * Only add what will be displayed
489 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
491 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
495 $item->setParent($this);
496 $this->children[] = $item;
498 return end($this->children);
502 * Get a child by its ID
504 * @param integer $id The child id
508 public function getChild($id)
510 foreach ($this->getChildren() as $child) {
511 if ($child->getId() == $id) {
520 * Get all our children
524 public function getChildren()
526 return $this->children;
532 * @param object $item The item to set as parent
536 protected function setParent($item)
538 $parent = $this->getParent();
540 $parent->removeChild($this);
543 $this->parent = $item;
544 $this->setThread($item->getThread());
552 protected function removeParent()
554 $this->parent = null;
555 $this->thread = null;
561 * @param object $item The child to be removed
563 * @return boolean Success or failure
565 public function removeChild($item)
567 $id = $item->getId();
568 foreach ($this->getChildren() as $key => $child) {
569 if ($child->getId() == $id) {
570 $child->removeParent();
571 unset($this->children[$key]);
572 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
573 $this->children = array_values($this->children);
577 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
586 protected function getParent()
588 return $this->parent;
594 * @param object $conv The conversation
598 public function setThread($conv)
600 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
602 $this->thread = $conv;
604 // Set it on our children too
605 foreach ($this->getChildren() as $child) {
606 $child->setThread($conv);
615 public function getThread()
617 return $this->thread;
623 * We shouldn't need this
627 public function getData()
635 * @param object $name key
637 * @return mixed value on success
640 public function getDataValue($name)
642 if (!isset($this->data[$name])) {
643 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
647 return $this->data[$name];
653 * @param object $name template name
657 private function setTemplate($name)
659 if (!x($this->available_templates, $name)) {
660 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
664 $this->template = $this->available_templates[$name];
672 private function getTemplate()
674 return $this->template;
678 * Check if this is a toplevel post
682 private function isToplevel()
684 return $this->toplevel;
688 * Check if this is writable
692 private function isWritable()
694 $conv = $this->getThread();
697 // This will allow us to comment on wall-to-wall items owned by our friends
698 // and community forums even if somebody else wrote the post.
699 // bug #517 - this fixes for conversation owner
700 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
704 // this fixes for visitors
705 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
707 return $this->writable;
711 * Count the total of our descendants
715 private function countDescendants()
717 $children = $this->getChildren();
718 $total = count($children);
720 foreach ($children as $child) {
721 $total += $child->countDescendants();
729 * Get the template for the comment box
733 private function getCommentBoxTemplate()
735 return $this->comment_box_template;
739 * Get the comment box
741 * @param string $indent Indent value
743 * @return mixed The comment box string (empty if no comment box)
746 private function getCommentBox($indent)
751 $conv = $this->getThread();
753 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
757 if ($conv->isWritable() && $this->isWritable()) {
758 $qc = $qcomment = null;
761 * Hmmm, code depending on the presence of a particular plugin?
762 * This should be better if done by a hook
764 if (in_array('qcomment', $a->plugins)) {
765 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
766 $qcomment = (($qc) ? explode("\n", $qc) : null);
769 // Fetch the user id from the parent when the owner user is empty
770 $uid = $conv->getProfileOwner();
771 $parent_uid = $this->getDataValue('uid');
773 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
777 $template = get_markup_template($this->getCommentBoxTemplate());
778 $comment_box = replace_macros($template, [
779 '$return_path' => $a->query_string,
780 '$threaded' => $this->isThreaded(),
782 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
783 '$id' => $this->getId(),
784 '$parent' => $this->getId(),
785 '$qcomment' => $qcomment,
786 '$profile_uid' => $uid,
787 '$mylink' => $a->remove_baseurl($a->contact['url']),
788 '$mytitle' => t('This is you'),
789 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
790 '$comment' => t('Comment'),
791 '$submit' => t('Submit'),
792 '$edbold' => t('Bold'),
793 '$editalic' => t('Italic'),
794 '$eduline' => t('Underline'),
795 '$edquote' => t('Quote'),
796 '$edcode' => t('Code'),
797 '$edimg' => t('Image'),
798 '$edurl' => t('Link'),
799 '$edvideo' => t('Video'),
800 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
801 '$indent' => $indent,
802 '$sourceapp' => t($a->sourcename),
803 '$ww' => $conv->getMode() === 'network' ? $ww : '',
804 '$rand_num' => random_digits(12)
814 private function getRedirectUrl()
816 return $this->redirect_url;
820 * Check if we are a wall to wall item and set the relevant properties
824 protected function checkWallToWall()
827 $conv = $this->getThread();
828 $this->wall_to_wall = false;
830 if ($this->isToplevel()) {
831 if ($conv->getMode() !== 'profile') {
832 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
833 // On the network page, I am the owner. On the display page it will be the profile owner.
834 // This will have been stored in $a->page_contact by our calling page.
835 // Put this person as the wall owner of the wall-to-wall notice.
837 $this->owner_url = Profile::zrl($a->page_contact['url']);
838 $this->owner_photo = $a->page_contact['thumb'];
839 $this->owner_name = $a->page_contact['name'];
840 $this->wall_to_wall = true;
841 } elseif ($this->getDataValue('owner-link')) {
842 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
843 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
844 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
846 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
847 // The author url doesn't match the owner (typically the contact)
848 // and also doesn't match the contact alias.
849 // The name match is a hack to catch several weird cases where URLs are
850 // all over the park. It can be tricked, but this prevents you from
851 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
852 // well that it's the same Bob Smith.
853 // But it could be somebody else with the same name. It just isn't highly likely.
856 $this->owner_photo = $this->getDataValue('owner-avatar');
857 $this->owner_name = $this->getDataValue('owner-name');
858 $this->wall_to_wall = true;
859 // If it is our contact, use a friendly redirect link
860 if ($this->getDataValue('network') === NETWORK_DFRN
861 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
863 $this->owner_url = $this->getRedirectUrl();
865 $this->owner_url = Profile::zrl($this->getDataValue('owner-link'));
872 if (!$this->wall_to_wall) {
873 $this->setTemplate('wall');
874 $this->owner_url = '';
875 $this->owner_photo = '';
876 $this->owner_name = '';
883 private function isWallToWall()
885 return $this->wall_to_wall;
891 private function getOwnerUrl()
893 return $this->owner_url;
899 private function getOwnerName()
901 return $this->owner_name;
907 private function isVisiting()
909 return $this->visiting;