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\PConfig;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Profile;
17 require_once 'include/dba.php';
18 require_once 'include/text.php';
19 require_once 'boot.php';
20 require_once 'include/conversation.php';
25 class Post extends BaseObject
28 private $template = null;
29 private $available_templates = [
30 'wall' => 'wall_thread.tpl',
31 'wall2wall' => 'wallwall_thread.tpl'
33 private $comment_box_template = 'comment_item.tpl';
34 private $toplevel = false;
35 private $writable = false;
36 private $children = [];
37 private $parent = null;
38 private $thread = null;
39 private $redirect_url = null;
40 private $owner_url = '';
41 private $owner_photo = '';
42 private $owner_name = '';
43 private $wall_to_wall = false;
44 private $threaded = false;
45 private $visiting = false;
50 * @param array $data data array
52 public function __construct(array $data)
57 $this->setTemplate('wall');
58 $this->toplevel = $this->getId() == $this->getDataValue('parent');
60 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
61 foreach ($_SESSION['remote'] as $visitor) {
62 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
63 $this->visiting = true;
69 $this->writable = $this->getDataValue('writable') || $this->getDataValue('self');
70 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
72 if (!$this->isToplevel()) {
73 $this->threaded = true;
76 // Prepare the children
77 if (count($data['children'])) {
78 foreach ($data['children'] as $item) {
79 // Only add will be displayed
80 if ($item['network'] === NETWORK_MAIL && local_user() != $item['uid']) {
82 } elseif (!visible_activity($item)) {
86 // You can always comment on Diaspora and OStatus items
87 // The empty network can happen with your local (self) contact
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' => 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 ? 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'], t("Edit")];
154 $edpost = ["editpost/" . $item['id'], 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' => t('Select'),
176 'delete' => t('Delete'),
179 $filer = (($conv->getProfileOwner() == local_user() && ($item['uid'] != 0)) ? 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 = [t('I will attend'), t('I will not attend'), 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' => t("add star"),
261 'undo' => t("remove star"),
262 'toggle' => t("toggle star status"),
263 'classdo' => $item['starred'] ? "hidden" : "",
264 'classundo' => $item['starred'] ? "" : "hidden",
265 'starred' => t('starred'),
268 $thread = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]);
269 if (DBM::is_result($thread)) {
271 'do' => t("ignore thread"),
272 'undo' => t("unignore thread"),
273 'toggle' => t("toggle ignore status"),
274 'classdo' => $thread['ignored'] ? "hidden" : "",
275 'classundo' => $thread['ignored'] ? "" : "hidden",
276 'ignored' => t('ignored'),
280 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
282 'add' => t("add tag"),
291 if ($conv->isWritable()) {
293 'like' => [t("I like this \x28toggle\x29"), t("like")],
294 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? [t("I don't like this \x28toggle\x29"), t("dislike")] : '',
297 $buttons['share'] = [t('Share this'), t('share')];
300 // If a contact isn't writable, we cannot send a like or dislike to it
301 if (!$item['writable']) {
302 unset($buttons["like"]);
303 unset($buttons["dislike"]);
307 $comment = $this->getCommentBox($indent);
309 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
313 localize_item($item);
315 $body = prepare_body($item, true);
317 list($categories, $folders) = get_cats_and_terms($item);
320 $text_e = strip_tags($body);
321 $name_e = $profile_name;
322 $title_e = $item['title'];
323 $location_e = $location;
324 $owner_name_e = $this->getOwnerName();
326 // Disable features that aren't available in several networks
327 if (!in_array($item["item_network"], [NETWORK_DFRN, NETWORK_DIASPORA]) && isset($buttons["dislike"])) {
328 unset($buttons["dislike"]);
333 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
334 unset($buttons["like"]);
337 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
338 unset($buttons["like"]);
342 'template' => $this->getTemplate(),
343 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
344 'tags' => $item['tags'],
345 'hashtags' => $item['hashtags'],
346 'mentions' => $item['mentions'],
347 'txt_cats' => t('Categories:'),
348 'txt_folders' => t('Filed under:'),
349 'has_cats' => ((count($categories)) ? 'true' : ''),
350 'has_folders' => ((count($folders)) ? 'true' : ''),
351 'categories' => $categories,
352 'folders' => $folders,
355 'id' => $this->getId(),
356 'guid' => urlencode($item['guid']),
357 'isevent' => $isevent,
359 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
360 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
363 'wall' => t('Wall-to-Wall'),
364 'vwall' => t('via Wall-To-Wall:'),
365 'profile_url' => $profile_link,
366 'item_photo_menu' => item_photo_menu($item),
368 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
369 'osparkle' => $osparkle,
370 'sparkle' => $sparkle,
372 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
373 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
374 'app' => $item['app'],
375 'created' => relative_date($item['created']),
377 'location' => $location_e,
380 'owner_url' => $this->getOwnerUrl(),
381 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
382 'owner_name' => htmlentities($owner_name_e),
383 'plink' => get_plink($item),
384 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
385 'isstarred' => $isstarred,
386 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
387 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
389 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
392 'like' => $responses['like']['output'],
393 'dislike' => $responses['dislike']['output'],
394 'responses' => $responses,
395 'switchcomment' => t('Comment'),
396 'comment' => $comment,
397 'previewing' => $conv->isPreview() ? ' preview ' : '',
398 'wait' => t('Please wait'),
399 'thread_level' => $thread_level,
401 'network' => $item["item_network"],
402 'network_name' => ContactSelector::networkToName($item['item_network'], $profile_link),
403 'received' => $item['received'],
404 'commented' => $item['commented'],
405 'created_date' => $item['created'],
408 $arr = ['item' => $item, 'output' => $tmp_item];
409 Addon::callHooks('display_item', $arr);
411 $result = $arr['output'];
413 $result['children'] = [];
414 $children = $this->getChildren();
415 $nb_children = count($children);
416 if ($nb_children > 0) {
417 foreach ($children as $child) {
418 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
421 if (($nb_children > 2) || ($thread_level > 1)) {
422 $result['children'][0]['comment_firstcollapsed'] = true;
423 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
424 $result['children'][0]['hidden_comments_num'] = $total_children;
425 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
426 $result['children'][0]['hide_text'] = t('show more');
427 if ($thread_level > 1) {
428 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
430 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
435 if ($this->isToplevel()) {
436 $result['total_comments_num'] = "$total_children";
437 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
440 $result['private'] = $item['private'];
441 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
443 if ($this->isThreaded()) {
444 $result['flatten'] = false;
445 $result['threaded'] = true;
447 $result['flatten'] = true;
448 $result['threaded'] = false;
457 public function getId()
459 return $this->getDataValue('id');
465 public function isThreaded()
467 return $this->threaded;
473 * @param object $item The child item to add
477 public function addChild(Post $item)
479 $item_id = $item->getId();
481 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
483 } elseif ($this->getChild($item->getId())) {
484 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
488 * Only add what will be displayed
490 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
492 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
496 $item->setParent($this);
497 $this->children[] = $item;
499 return end($this->children);
503 * Get a child by its ID
505 * @param integer $id The child id
509 public function getChild($id)
511 foreach ($this->getChildren() as $child) {
512 if ($child->getId() == $id) {
521 * Get all our children
525 public function getChildren()
527 return $this->children;
533 * @param object $item The item to set as parent
537 protected function setParent($item)
539 $parent = $this->getParent();
541 $parent->removeChild($this);
544 $this->parent = $item;
545 $this->setThread($item->getThread());
553 protected function removeParent()
555 $this->parent = null;
556 $this->thread = null;
562 * @param object $item The child to be removed
564 * @return boolean Success or failure
566 public function removeChild($item)
568 $id = $item->getId();
569 foreach ($this->getChildren() as $key => $child) {
570 if ($child->getId() == $id) {
571 $child->removeParent();
572 unset($this->children[$key]);
573 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
574 $this->children = array_values($this->children);
578 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
587 protected function getParent()
589 return $this->parent;
595 * @param object $conv The conversation
599 public function setThread($conv)
601 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
603 $this->thread = $conv;
605 // Set it on our children too
606 foreach ($this->getChildren() as $child) {
607 $child->setThread($conv);
616 public function getThread()
618 return $this->thread;
624 * We shouldn't need this
628 public function getData()
636 * @param object $name key
638 * @return mixed value on success
641 public function getDataValue($name)
643 if (!isset($this->data[$name])) {
644 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
648 return $this->data[$name];
654 * @param object $name template name
658 private function setTemplate($name)
660 if (!x($this->available_templates, $name)) {
661 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
665 $this->template = $this->available_templates[$name];
673 private function getTemplate()
675 return $this->template;
679 * Check if this is a toplevel post
683 private function isToplevel()
685 return $this->toplevel;
689 * Check if this is writable
693 private function isWritable()
695 $conv = $this->getThread();
698 // This will allow us to comment on wall-to-wall items owned by our friends
699 // and community forums even if somebody else wrote the post.
700 // bug #517 - this fixes for conversation owner
701 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
705 // this fixes for visitors
706 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
708 return $this->writable;
712 * Count the total of our descendants
716 private function countDescendants()
718 $children = $this->getChildren();
719 $total = count($children);
721 foreach ($children as $child) {
722 $total += $child->countDescendants();
730 * Get the template for the comment box
734 private function getCommentBoxTemplate()
736 return $this->comment_box_template;
740 * Get the comment box
742 * @param string $indent Indent value
744 * @return mixed The comment box string (empty if no comment box)
747 private function getCommentBox($indent)
752 $conv = $this->getThread();
754 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
758 if ($conv->isWritable() && $this->isWritable()) {
759 $qc = $qcomment = null;
762 * Hmmm, code depending on the presence of a particular plugin?
763 * This should be better if done by a hook
765 if (in_array('qcomment', $a->plugins)) {
766 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
767 $qcomment = (($qc) ? explode("\n", $qc) : null);
770 // Fetch the user id from the parent when the owner user is empty
771 $uid = $conv->getProfileOwner();
772 $parent_uid = $this->getDataValue('uid');
774 if (!is_null($parent_uid) && ($uid != $parent_uid)) {
778 $template = get_markup_template($this->getCommentBoxTemplate());
779 $comment_box = replace_macros($template, [
780 '$return_path' => $a->query_string,
781 '$threaded' => $this->isThreaded(),
783 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
784 '$id' => $this->getId(),
785 '$parent' => $this->getId(),
786 '$qcomment' => $qcomment,
787 '$profile_uid' => $uid,
788 '$mylink' => $a->remove_baseurl($a->contact['url']),
789 '$mytitle' => t('This is you'),
790 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
791 '$comment' => t('Comment'),
792 '$submit' => t('Submit'),
793 '$edbold' => t('Bold'),
794 '$editalic' => t('Italic'),
795 '$eduline' => t('Underline'),
796 '$edquote' => t('Quote'),
797 '$edcode' => t('Code'),
798 '$edimg' => t('Image'),
799 '$edurl' => t('Link'),
800 '$edvideo' => t('Video'),
801 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
802 '$indent' => $indent,
803 '$sourceapp' => t($a->sourcename),
804 '$ww' => $conv->getMode() === 'network' ? $ww : '',
805 '$rand_num' => random_digits(12)
815 private function getRedirectUrl()
817 return $this->redirect_url;
821 * Check if we are a wall to wall item and set the relevant properties
825 protected function checkWallToWall()
828 $conv = $this->getThread();
829 $this->wall_to_wall = false;
831 if ($this->isToplevel()) {
832 if ($conv->getMode() !== 'profile') {
833 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
834 // On the network page, I am the owner. On the display page it will be the profile owner.
835 // This will have been stored in $a->page_contact by our calling page.
836 // Put this person as the wall owner of the wall-to-wall notice.
838 $this->owner_url = Profile::zrl($a->page_contact['url']);
839 $this->owner_photo = $a->page_contact['thumb'];
840 $this->owner_name = $a->page_contact['name'];
841 $this->wall_to_wall = true;
842 } elseif ($this->getDataValue('owner-link')) {
843 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
844 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
845 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
847 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
848 // The author url doesn't match the owner (typically the contact)
849 // and also doesn't match the contact alias.
850 // The name match is a hack to catch several weird cases where URLs are
851 // all over the park. It can be tricked, but this prevents you from
852 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
853 // well that it's the same Bob Smith.
854 // But it could be somebody else with the same name. It just isn't highly likely.
857 $this->owner_photo = $this->getDataValue('owner-avatar');
858 $this->owner_name = $this->getDataValue('owner-name');
859 $this->wall_to_wall = true;
860 // If it is our contact, use a friendly redirect link
861 if ($this->getDataValue('network') === NETWORK_DFRN
862 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
864 $this->owner_url = $this->getRedirectUrl();
866 $this->owner_url = Profile::zrl($this->getDataValue('owner-link'));
873 if (!$this->wall_to_wall) {
874 $this->setTemplate('wall');
875 $this->owner_url = '';
876 $this->owner_photo = '';
877 $this->owner_name = '';
884 private function isWallToWall()
886 return $this->wall_to_wall;
892 private function getOwnerUrl()
894 return $this->owner_url;
900 private function getOwnerName()
902 return $this->owner_name;
908 private function isVisiting()
910 return $this->visiting;