4 * @file src/Object/Post.php
7 namespace Friendica\Object;
9 use Friendica\BaseObject;
10 use Friendica\Content\Feature;
11 use Friendica\Core\PConfig;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
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
26 private $data = array();
27 private $template = null;
28 private $available_templates = array(
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 = array();
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 items
86 if (($item['network'] == NETWORK_DIASPORA) && (local_user() == $item['uid'])) {
87 $item['writable'] = true;
90 $item['pagedrop'] = $data['pagedrop'];
91 $child = new Post($item);
92 $this->addChild($child);
98 * Get data in a form usable by a conversation template
100 * @param object $conv_responses conversation responses
101 * @param integer $thread_level default = 1
103 * @return mixed The data requested on success
106 public function getTemplateData($conv_responses, $thread_level = 1)
108 require_once "mod/proxy.php";
114 $item = $this->getData();
116 // If the time between "created" and "edited" differs we add
117 // a notice that the post was edited.
118 // Note: In some networks reshared items seem to have (sometimes) a difference
119 // between creation time and edit time of a second. Thats why we add the notice
120 // only if the difference is more than 1 second.
121 if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
123 'label' => t('This entry was edited'),
124 'date' => datetime_convert('UTC', date_default_timezone_get(), $item['edited'], 'r'),
125 'relative' => relative_date($item['edited'])
134 $isstarred = "unstarred";
138 $total_children = $this->countDescendants();
140 $conv = $this->getThread();
142 $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid'])
143 || strlen($item['deny_cid']) || strlen($item['deny_gid']))))
144 ? t('Private Message')
146 $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1;
148 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
149 if ($item["event-id"] != 0) {
150 $edpost = array("events/event/" . $item['event-id'], t("Edit"));
152 $edpost = array("editpost/" . $item['id'], t("Edit"));
154 $dropping = in_array($item['uid'], [0, local_user()]);
159 // Editing on items of not subscribed users isn't currently possible
160 // There are some issues on editing that prevent this.
161 // But also it is an issue of the supported protocols that doesn't allow editing at all.
162 if ($item['uid'] == 0) {
166 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
171 'dropping' => $dropping,
172 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
173 'select' => t('Select'),
174 'delete' => t('Delete'),
177 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
179 $diff_author = !link_compare($item['url'], $item['author-link']);
180 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
181 if ($item['author-link'] && (!$item['author-name'])) {
182 $profile_name = $item['author-link'];
186 $profile_link = best_link_url($item, $sp);
187 if ($profile_link === 'mailbox') {
192 $sparkle = ' sparkle';
194 $profile_link = zrl($profile_link);
197 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
198 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
199 if ($author_contact["thumb"]) {
200 $item['author-thumb'] = $author_contact["thumb"];
202 $item['author-thumb'] = $item['author-avatar'];
206 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
207 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
208 if ($owner_contact["thumb"]) {
209 $item['owner-thumb'] = $owner_contact["thumb"];
211 $item['owner-thumb'] = $item['owner-avatar'];
215 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
216 call_hooks('render_location', $locate);
217 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
219 // process action responses - e.g. like/dislike/attend/agree/whatever
220 $response_verbs = array('like', 'dislike');
224 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
225 $response_verbs[] = 'attendyes';
226 $response_verbs[] = 'attendno';
227 $response_verbs[] = 'attendmaybe';
228 if ($conv->isWritable()) {
230 $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
234 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
236 foreach ($response_verbs as $value => $verbs) {
237 $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']) : '';
241 * We should avoid doing this all the time, but it depends on the conversation mode
242 * And the conv mode may change when we change the conv, or it changes its mode
243 * Maybe we should establish a way to be notified about conversation changes
245 $this->checkWallToWall();
247 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
248 $osparkle = ' sparkle';
253 if ($this->isToplevel()) {
254 if ($conv->getProfileOwner() == local_user()) {
255 $isstarred = (($item['starred']) ? "starred" : "unstarred");
258 'do' => t("add star"),
259 'undo' => t("remove star"),
260 'toggle' => t("toggle star status"),
261 'classdo' => $item['starred'] ? "hidden" : "",
262 'classundo' => $item['starred'] ? "" : "hidden",
263 'starred' => t('starred'),
265 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
266 if (DBM::is_result($r)) {
268 'do' => t("ignore thread"),
269 'undo' => t("unignore thread"),
270 'toggle' => t("toggle ignore status"),
271 'classdo' => $r['ignored'] ? "hidden" : "",
272 'classundo' => $r['ignored'] ? "" : "hidden",
273 'ignored' => t('ignored'),
277 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
279 'add' => t("add tag"),
288 if ($conv->isWritable()) {
290 'like' => array(t("I like this \x28toggle\x29"), t("like")),
291 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
294 $buttons['share'] = array(t('Share this'), t('share'));
297 // If a contact isn't writable, we cannot send a like or dislike to it
298 if (!$item['writable']) {
299 unset($buttons["like"]);
300 unset($buttons["dislike"]);
304 $comment = $this->getCommentBox($indent);
306 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
310 localize_item($item);
312 $body = prepare_body($item, true);
314 list($categories, $folders) = get_cats_and_terms($item);
317 $text_e = strip_tags($body);
318 $name_e = $profile_name;
319 $title_e = $item['title'];
320 $location_e = $location;
321 $owner_name_e = $this->getOwnerName();
323 // Disable features that aren't available in several networks
324 /// @todo Add NETWORK_DIASPORA when it will pass this information
325 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
326 unset($buttons["dislike"]);
331 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
332 unset($buttons["like"]);
335 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
336 unset($buttons["like"]);
340 'template' => $this->getTemplate(),
341 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
342 'tags' => $item['tags'],
343 'hashtags' => $item['hashtags'],
344 'mentions' => $item['mentions'],
345 'txt_cats' => t('Categories:'),
346 'txt_folders' => t('Filed under:'),
347 'has_cats' => ((count($categories)) ? 'true' : ''),
348 'has_folders' => ((count($folders)) ? 'true' : ''),
349 'categories' => $categories,
350 'folders' => $folders,
353 'id' => $this->getId(),
354 'guid' => urlencode($item['guid']),
355 'isevent' => $isevent,
357 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
358 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
361 'wall' => t('Wall-to-Wall'),
362 'vwall' => t('via Wall-To-Wall:'),
363 'profile_url' => $profile_link,
364 'item_photo_menu' => item_photo_menu($item),
366 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
367 'osparkle' => $osparkle,
368 'sparkle' => $sparkle,
370 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
371 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
372 'app' => $item['app'],
373 'created' => relative_date($item['created']),
375 'location' => $location_e,
378 'owner_url' => $this->getOwnerUrl(),
379 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
380 'owner_name' => htmlentities($owner_name_e),
381 'plink' => get_plink($item),
382 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
383 'isstarred' => $isstarred,
384 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
385 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
387 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
390 'like' => $responses['like']['output'],
391 'dislike' => $responses['dislike']['output'],
392 'responses' => $responses,
393 'switchcomment' => t('Comment'),
394 'comment' => $comment,
395 'previewing' => $conv->isPreview() ? ' preview ' : '',
396 'wait' => t('Please wait'),
397 'thread_level' => $thread_level,
399 'network' => $item["item_network"],
400 'network_name' => network_to_name($item['item_network'], $profile_link),
401 'received' => $item['received'],
402 'commented' => $item['commented'],
403 'created_date' => $item['created'],
406 $arr = array('item' => $item, 'output' => $tmp_item);
407 call_hooks('display_item', $arr);
409 $result = $arr['output'];
411 $result['children'] = array();
412 $children = $this->getChildren();
413 $nb_children = count($children);
414 if ($nb_children > 0) {
415 foreach ($children as $child) {
416 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
419 if (($nb_children > 2) || ($thread_level > 1)) {
420 $result['children'][0]['comment_firstcollapsed'] = true;
421 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
422 $result['children'][0]['hidden_comments_num'] = $total_children;
423 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
424 $result['children'][0]['hide_text'] = t('show more');
425 if ($thread_level > 1) {
426 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
428 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
433 if ($this->isToplevel()) {
434 $result['total_comments_num'] = "$total_children";
435 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
438 $result['private'] = $item['private'];
439 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
441 if ($this->isThreaded()) {
442 $result['flatten'] = false;
443 $result['threaded'] = true;
445 $result['flatten'] = true;
446 $result['threaded'] = false;
455 public function getId()
457 return $this->getDataValue('id');
463 public function isThreaded()
465 return $this->threaded;
471 * @param object $item The child item to add
475 public function addChild(Post $item)
477 $item_id = $item->getId();
479 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
481 } elseif ($this->getChild($item->getId())) {
482 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
486 * Only add what will be displayed
488 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
490 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
494 $item->setParent($this);
495 $this->children[] = $item;
497 return end($this->children);
501 * Get a child by its ID
503 * @param integer $id The child id
507 public function getChild($id)
509 foreach ($this->getChildren() as $child) {
510 if ($child->getId() == $id) {
519 * Get all our children
523 public function getChildren()
525 return $this->children;
531 * @param object $item The item to set as parent
535 protected function setParent($item)
537 $parent = $this->getParent();
539 $parent->removeChild($this);
542 $this->parent = $item;
543 $this->setThread($item->getThread());
551 protected function removeParent()
553 $this->parent = null;
554 $this->thread = null;
560 * @param object $item The child to be removed
562 * @return boolean Success or failure
564 public function removeChild($item)
566 $id = $item->getId();
567 foreach ($this->getChildren() as $key => $child) {
568 if ($child->getId() == $id) {
569 $child->removeParent();
570 unset($this->children[$key]);
571 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
572 $this->children = array_values($this->children);
576 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
585 protected function getParent()
587 return $this->parent;
593 * @param object $conv The conversation
597 public function setThread($conv)
599 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
601 $this->thread = $conv;
603 // Set it on our children too
604 foreach ($this->getChildren() as $child) {
605 $child->setThread($conv);
614 public function getThread()
616 return $this->thread;
622 * We shouldn't need this
626 public function getData()
634 * @param object $name key
636 * @return mixed value on success
639 public function getDataValue($name)
641 if (!isset($this->data[$name])) {
642 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
646 return $this->data[$name];
652 * @param object $name template name
656 private function setTemplate($name)
658 if (!x($this->available_templates, $name)) {
659 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
663 $this->template = $this->available_templates[$name];
671 private function getTemplate()
673 return $this->template;
677 * Check if this is a toplevel post
681 private function isToplevel()
683 return $this->toplevel;
687 * Check if this is writable
691 private function isWritable()
693 $conv = $this->getThread();
696 // This will allow us to comment on wall-to-wall items owned by our friends
697 // and community forums even if somebody else wrote the post.
698 // bug #517 - this fixes for conversation owner
699 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
703 // this fixes for visitors
704 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
706 return $this->writable;
710 * Count the total of our descendants
714 private function countDescendants()
716 $children = $this->getChildren();
717 $total = count($children);
719 foreach ($children as $child) {
720 $total += $child->countDescendants();
728 * Get the template for the comment box
732 private function getCommentBoxTemplate()
734 return $this->comment_box_template;
738 * Get the comment box
740 * @param string $indent Indent value
742 * @return mixed The comment box string (empty if no comment box)
745 private function getCommentBox($indent)
750 $conv = $this->getThread();
752 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
756 if ($conv->isWritable() && $this->isWritable()) {
757 $qc = $qcomment = null;
760 * Hmmm, code depending on the presence of a particular plugin?
761 * This should be better if done by a hook
763 if (in_array('qcomment', $a->plugins)) {
764 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
765 $qcomment = (($qc) ? explode("\n", $qc) : null);
768 // Fetch the user id from the parent when the owner user is empty
769 $uid = $conv->getProfileOwner();
770 $parent_uid = $this->getDataValue('uid');
772 if (!empty($parent_uid) && empty($uid) && ($uid != $parent_uid)) {
776 $template = get_markup_template($this->getCommentBoxTemplate());
777 $comment_box = replace_macros($template, array(
778 '$return_path' => $a->query_string,
779 '$threaded' => $this->isThreaded(),
781 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
782 '$id' => $this->getId(),
783 '$parent' => $this->getId(),
784 '$qcomment' => $qcomment,
785 '$profile_uid' => $uid,
786 '$mylink' => $a->remove_baseurl($a->contact['url']),
787 '$mytitle' => t('This is you'),
788 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
789 '$comment' => t('Comment'),
790 '$submit' => t('Submit'),
791 '$edbold' => t('Bold'),
792 '$editalic' => t('Italic'),
793 '$eduline' => t('Underline'),
794 '$edquote' => t('Quote'),
795 '$edcode' => t('Code'),
796 '$edimg' => t('Image'),
797 '$edurl' => t('Link'),
798 '$edvideo' => t('Video'),
799 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
800 '$indent' => $indent,
801 '$sourceapp' => t($a->sourcename),
802 '$ww' => $conv->getMode() === 'network' ? $ww : '',
803 '$rand_num' => random_digits(12)
813 private function getRedirectUrl()
815 return $this->redirect_url;
819 * Check if we are a wall to wall item and set the relevant properties
823 protected function checkWallToWall()
826 $conv = $this->getThread();
827 $this->wall_to_wall = false;
829 if ($this->isToplevel()) {
830 if ($conv->getMode() !== 'profile') {
831 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
832 // On the network page, I am the owner. On the display page it will be the profile owner.
833 // This will have been stored in $a->page_contact by our calling page.
834 // Put this person as the wall owner of the wall-to-wall notice.
836 $this->owner_url = zrl($a->page_contact['url']);
837 $this->owner_photo = $a->page_contact['thumb'];
838 $this->owner_name = $a->page_contact['name'];
839 $this->wall_to_wall = true;
840 } elseif ($this->getDataValue('owner-link')) {
841 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
842 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
843 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
845 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
846 // The author url doesn't match the owner (typically the contact)
847 // and also doesn't match the contact alias.
848 // The name match is a hack to catch several weird cases where URLs are
849 // all over the park. It can be tricked, but this prevents you from
850 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
851 // well that it's the same Bob Smith.
852 // But it could be somebody else with the same name. It just isn't highly likely.
855 $this->owner_photo = $this->getDataValue('owner-avatar');
856 $this->owner_name = $this->getDataValue('owner-name');
857 $this->wall_to_wall = true;
858 // If it is our contact, use a friendly redirect link
859 if ($this->getDataValue('network') === NETWORK_DFRN
860 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
862 $this->owner_url = $this->getRedirectUrl();
864 $this->owner_url = zrl($this->getDataValue('owner-link'));
871 if (!$this->wall_to_wall) {
872 $this->setTemplate('wall');
873 $this->owner_url = '';
874 $this->owner_photo = '';
875 $this->owner_name = '';
882 private function isWallToWall()
884 return $this->wall_to_wall;
890 private function getOwnerUrl()
892 return $this->owner_url;
898 private function getOwnerName()
900 return $this->owner_name;
906 private function isVisiting()
908 return $this->visiting;