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"));
158 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
163 'dropping' => $dropping,
164 'pagedrop' => ((Feature::isEnabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
165 'select' => t('Select'),
166 'delete' => t('Delete'),
169 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
171 $diff_author = !link_compare($item['url'], $item['author-link']);
172 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
173 if ($item['author-link'] && (!$item['author-name'])) {
174 $profile_name = $item['author-link'];
178 $profile_link = best_link_url($item, $sp);
179 if ($profile_link === 'mailbox') {
184 $sparkle = ' sparkle';
186 $profile_link = zrl($profile_link);
189 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
190 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
191 if ($author_contact["thumb"]) {
192 $item['author-thumb'] = $author_contact["thumb"];
194 $item['author-thumb'] = $item['author-avatar'];
198 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
199 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
200 if ($owner_contact["thumb"]) {
201 $item['owner-thumb'] = $owner_contact["thumb"];
203 $item['owner-thumb'] = $item['owner-avatar'];
207 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
208 call_hooks('render_location', $locate);
209 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
211 // process action responses - e.g. like/dislike/attend/agree/whatever
212 $response_verbs = array('like', 'dislike');
216 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
217 $response_verbs[] = 'attendyes';
218 $response_verbs[] = 'attendno';
219 $response_verbs[] = 'attendmaybe';
220 if ($conv->isWritable()) {
222 $attend = array(t('I will attend'), t('I will not attend'), t('I might attend'));
226 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
228 foreach ($response_verbs as $value => $verbs) {
229 $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']) : '';
233 * We should avoid doing this all the time, but it depends on the conversation mode
234 * And the conv mode may change when we change the conv, or it changes its mode
235 * Maybe we should establish a way to be notified about conversation changes
237 $this->checkWallToWall();
239 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
240 $osparkle = ' sparkle';
245 if ($this->isToplevel()) {
246 if ($conv->getProfileOwner() == local_user()) {
247 $isstarred = (($item['starred']) ? "starred" : "unstarred");
250 'do' => t("add star"),
251 'undo' => t("remove star"),
252 'toggle' => t("toggle star status"),
253 'classdo' => $item['starred'] ? "hidden" : "",
254 'classundo' => $item['starred'] ? "" : "hidden",
255 'starred' => t('starred'),
257 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
258 if (DBM::is_result($r)) {
260 'do' => t("ignore thread"),
261 'undo' => t("unignore thread"),
262 'toggle' => t("toggle ignore status"),
263 'classdo' => $r['ignored'] ? "hidden" : "",
264 'classundo' => $r['ignored'] ? "" : "hidden",
265 'ignored' => t('ignored'),
269 if (Feature::isEnabled($conv->getProfileOwner(), 'commtag')) {
271 'add' => t("add tag"),
280 if ($conv->isWritable()) {
282 'like' => array(t("I like this \x28toggle\x29"), t("like")),
283 'dislike' => Feature::isEnabled($conv->getProfileOwner(), 'dislike') ? array(t("I don't like this \x28toggle\x29"), t("dislike")) : '',
286 $buttons['share'] = array(t('Share this'), t('share'));
290 $comment = $this->getCommentBox($indent);
292 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
296 localize_item($item);
298 $body = prepare_body($item, true);
300 list($categories, $folders) = get_cats_and_terms($item);
303 $text_e = strip_tags($body);
304 $name_e = $profile_name;
305 $title_e = $item['title'];
306 $location_e = $location;
307 $owner_name_e = $this->getOwnerName();
309 // Disable features that aren't available in several networks
310 /// @todo Add NETWORK_DIASPORA when it will pass this information
311 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
312 unset($buttons["dislike"]);
317 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
318 unset($buttons["like"]);
321 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
322 unset($buttons["like"]);
325 // If a contact isn't writable, we cannot send a like or dislike to it
326 if (!$item['writable']) {
327 unset($buttons["like"]);
328 unset($buttons["dislike"]);
332 'template' => $this->getTemplate(),
333 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
334 'tags' => $item['tags'],
335 'hashtags' => $item['hashtags'],
336 'mentions' => $item['mentions'],
337 'txt_cats' => t('Categories:'),
338 'txt_folders' => t('Filed under:'),
339 'has_cats' => ((count($categories)) ? 'true' : ''),
340 'has_folders' => ((count($folders)) ? 'true' : ''),
341 'categories' => $categories,
342 'folders' => $folders,
345 'id' => $this->getId(),
346 'guid' => urlencode($item['guid']),
347 'isevent' => $isevent,
349 'linktitle' => t('View %s\'s profile @ %s', $profile_name, defaults($item, 'author-link', $item['url'])),
350 'olinktitle' => t('View %s\'s profile @ %s', htmlentities($this->getOwnerName()), defaults($item, 'owner-link', $item['url'])),
353 'wall' => t('Wall-to-Wall'),
354 'vwall' => t('via Wall-To-Wall:'),
355 'profile_url' => $profile_link,
356 'item_photo_menu' => item_photo_menu($item),
358 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
359 'osparkle' => $osparkle,
360 'sparkle' => $sparkle,
362 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
363 'ago' => $item['app'] ? t('%s from %s', relative_date($item['created']), $item['app']) : relative_date($item['created']),
364 'app' => $item['app'],
365 'created' => relative_date($item['created']),
367 'location' => $location_e,
370 'owner_url' => $this->getOwnerUrl(),
371 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
372 'owner_name' => htmlentities($owner_name_e),
373 'plink' => get_plink($item),
374 'edpost' => Feature::isEnabled($conv->getProfileOwner(), 'edit_posts') ? $edpost : '',
375 'isstarred' => $isstarred,
376 'star' => Feature::isEnabled($conv->getProfileOwner(), 'star_posts') ? $star : '',
377 'ignore' => Feature::isEnabled($conv->getProfileOwner(), 'ignore_posts') ? $ignore : '',
379 'filer' => Feature::isEnabled($conv->getProfileOwner(), 'filing') ? $filer : '',
382 'like' => $responses['like']['output'],
383 'dislike' => $responses['dislike']['output'],
384 'responses' => $responses,
385 'switchcomment' => t('Comment'),
386 'comment' => $comment,
387 'previewing' => $conv->isPreview() ? ' preview ' : '',
388 'wait' => t('Please wait'),
389 'thread_level' => $thread_level,
391 'network' => $item["item_network"],
392 'network_name' => network_to_name($item['item_network'], $profile_link),
393 'received' => $item['received'],
394 'commented' => $item['commented'],
395 'created_date' => $item['created'],
398 $arr = array('item' => $item, 'output' => $tmp_item);
399 call_hooks('display_item', $arr);
401 $result = $arr['output'];
403 $result['children'] = array();
404 $children = $this->getChildren();
405 $nb_children = count($children);
406 if ($nb_children > 0) {
407 foreach ($children as $child) {
408 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
411 if (($nb_children > 2) || ($thread_level > 1)) {
412 $result['children'][0]['comment_firstcollapsed'] = true;
413 $result['children'][0]['num_comments'] = tt('%d comment', '%d comments', $total_children);
414 $result['children'][0]['hidden_comments_num'] = $total_children;
415 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
416 $result['children'][0]['hide_text'] = t('show more');
417 if ($thread_level > 1) {
418 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
420 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
425 if ($this->isToplevel()) {
426 $result['total_comments_num'] = "$total_children";
427 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
430 $result['private'] = $item['private'];
431 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
433 if ($this->isThreaded()) {
434 $result['flatten'] = false;
435 $result['threaded'] = true;
437 $result['flatten'] = true;
438 $result['threaded'] = false;
447 public function getId()
449 return $this->getDataValue('id');
455 public function isThreaded()
457 return $this->threaded;
463 * @param object $item The child item to add
467 public function addChild(Post $item)
469 $item_id = $item->getId();
471 logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG);
473 } elseif ($this->getChild($item->getId())) {
474 logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG);
478 * Only add what will be displayed
480 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
482 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
486 $item->setParent($this);
487 $this->children[] = $item;
489 return end($this->children);
493 * Get a child by its ID
495 * @param integer $id The child id
499 public function getChild($id)
501 foreach ($this->getChildren() as $child) {
502 if ($child->getId() == $id) {
511 * Get all our children
515 public function getChildren()
517 return $this->children;
523 * @param object $item The item to set as parent
527 protected function setParent($item)
529 $parent = $this->getParent();
531 $parent->removeChild($this);
534 $this->parent = $item;
535 $this->setThread($item->getThread());
543 protected function removeParent()
545 $this->parent = null;
546 $this->thread = null;
552 * @param object $item The child to be removed
554 * @return boolean Success or failure
556 public function removeChild($item)
558 $id = $item->getId();
559 foreach ($this->getChildren() as $key => $child) {
560 if ($child->getId() == $id) {
561 $child->removeParent();
562 unset($this->children[$key]);
563 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
564 $this->children = array_values($this->children);
568 logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG);
577 protected function getParent()
579 return $this->parent;
585 * @param object $conv The conversation
589 public function setThread($conv)
591 $previous_mode = ($this->thread ? $this->thread->getMode() : '');
593 $this->thread = $conv;
595 // Set it on our children too
596 foreach ($this->getChildren() as $child) {
597 $child->setThread($conv);
606 public function getThread()
608 return $this->thread;
614 * We shouldn't need this
618 public function getData()
626 * @param object $name key
628 * @return mixed value on success
631 public function getDataValue($name)
633 if (!isset($this->data[$name])) {
634 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
638 return $this->data[$name];
644 * @param object $name template name
648 private function setTemplate($name)
650 if (!x($this->available_templates, $name)) {
651 logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG);
655 $this->template = $this->available_templates[$name];
663 private function getTemplate()
665 return $this->template;
669 * Check if this is a toplevel post
673 private function isToplevel()
675 return $this->toplevel;
679 * Check if this is writable
683 private function isWritable()
685 $conv = $this->getThread();
688 // This will allow us to comment on wall-to-wall items owned by our friends
689 // and community forums even if somebody else wrote the post.
690 // bug #517 - this fixes for conversation owner
691 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
695 // this fixes for visitors
696 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
698 return $this->writable;
702 * Count the total of our descendants
706 private function countDescendants()
708 $children = $this->getChildren();
709 $total = count($children);
711 foreach ($children as $child) {
712 $total += $child->countDescendants();
720 * Get the template for the comment box
724 private function getCommentBoxTemplate()
726 return $this->comment_box_template;
730 * Get the comment box
732 * @param string $indent Indent value
734 * @return mixed The comment box string (empty if no comment box)
737 private function getCommentBox($indent)
742 $conv = $this->getThread();
744 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
748 if ($conv->isWritable() && $this->isWritable()) {
749 $qc = $qcomment = null;
752 * Hmmm, code depending on the presence of a particular plugin?
753 * This should be better if done by a hook
755 if (in_array('qcomment', $a->plugins)) {
756 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
757 $qcomment = (($qc) ? explode("\n", $qc) : null);
760 $template = get_markup_template($this->getCommentBoxTemplate());
761 $comment_box = replace_macros($template, array(
762 '$return_path' => $a->query_string,
763 '$threaded' => $this->isThreaded(),
765 '$type' => $conv->getMode() === 'profile' ? 'wall-comment' : 'net-comment',
766 '$id' => $this->getId(),
767 '$parent' => $this->getId(),
768 '$qcomment' => $qcomment,
769 '$profile_uid' => $conv->getProfileOwner(),
770 '$mylink' => $a->remove_baseurl($a->contact['url']),
771 '$mytitle' => t('This is you'),
772 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
773 '$comment' => t('Comment'),
774 '$submit' => t('Submit'),
775 '$edbold' => t('Bold'),
776 '$editalic' => t('Italic'),
777 '$eduline' => t('Underline'),
778 '$edquote' => t('Quote'),
779 '$edcode' => t('Code'),
780 '$edimg' => t('Image'),
781 '$edurl' => t('Link'),
782 '$edvideo' => t('Video'),
783 '$preview' => ((Feature::isEnabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
784 '$indent' => $indent,
785 '$sourceapp' => t($a->sourcename),
786 '$ww' => $conv->getMode() === 'network' ? $ww : '',
787 '$rand_num' => random_digits(12)
797 private function getRedirectUrl()
799 return $this->redirect_url;
803 * Check if we are a wall to wall item and set the relevant properties
807 protected function checkWallToWall()
810 $conv = $this->getThread();
811 $this->wall_to_wall = false;
813 if ($this->isToplevel()) {
814 if ($conv->getMode() !== 'profile') {
815 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
816 // On the network page, I am the owner. On the display page it will be the profile owner.
817 // This will have been stored in $a->page_contact by our calling page.
818 // Put this person as the wall owner of the wall-to-wall notice.
820 $this->owner_url = zrl($a->page_contact['url']);
821 $this->owner_photo = $a->page_contact['thumb'];
822 $this->owner_name = $a->page_contact['name'];
823 $this->wall_to_wall = true;
824 } elseif ($this->getDataValue('owner-link')) {
825 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
826 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
827 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
829 if ((!$owner_linkmatch) && (!$alias_linkmatch) && (!$owner_namematch)) {
830 // The author url doesn't match the owner (typically the contact)
831 // and also doesn't match the contact alias.
832 // The name match is a hack to catch several weird cases where URLs are
833 // all over the park. It can be tricked, but this prevents you from
834 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
835 // well that it's the same Bob Smith.
836 // But it could be somebody else with the same name. It just isn't highly likely.
839 $this->owner_photo = $this->getDataValue('owner-avatar');
840 $this->owner_name = $this->getDataValue('owner-name');
841 $this->wall_to_wall = true;
842 // If it is our contact, use a friendly redirect link
843 if ($this->getDataValue('network') === NETWORK_DFRN
844 && link_compare($this->getDataValue('owner-link'), $this->getDataValue('url'))
846 $this->owner_url = $this->getRedirectUrl();
848 $this->owner_url = zrl($this->getDataValue('owner-link'));
855 if (!$this->wall_to_wall) {
856 $this->setTemplate('wall');
857 $this->owner_url = '';
858 $this->owner_photo = '';
859 $this->owner_name = '';
866 private function isWallToWall()
868 return $this->wall_to_wall;
874 private function getOwnerUrl()
876 return $this->owner_url;
882 private function getOwnerName()
884 return $this->owner_name;
890 private function isVisiting()
892 return $this->visiting;