3 * @file src/Object/Item.php
5 namespace Friendica\Object;
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Database\DBM;
11 use Friendica\Object\Contact;
14 require_once 'include/text.php';
15 require_once 'boot.php';
20 class Item extends BaseObject
22 private $data = array();
23 private $template = null;
24 private $available_templates = array(
25 'wall' => 'wall_thread.tpl',
26 'wall2wall' => 'wallwall_thread.tpl'
28 private $comment_box_template = 'comment_item.tpl';
29 private $toplevel = false;
30 private $writable = false;
31 private $children = array();
32 private $parent = null;
33 private $conversation = null;
34 private $redirect_url = null;
35 private $owner_url = '';
36 private $owner_photo = '';
37 private $owner_name = '';
38 private $wall_to_wall = false;
39 private $threaded = false;
40 private $visiting = false;
45 * @param array $data data array
47 public function __construct($data)
52 $this->setTemplate('wall');
53 $this->toplevel = ($this->getId() == $this->getDataValue('parent'));
55 if (is_array($_SESSION['remote'])) {
56 foreach ($_SESSION['remote'] as $visitor) {
57 if ($visitor['cid'] == $this->getDataValue('contact-id')) {
58 $this->visiting = true;
64 $this->writable = ($this->getDataValue('writable') || $this->getDataValue('self'));
66 $ssl_state = ((local_user()) ? true : false);
67 $this->redirect_url = 'redir/' . $this->getDataValue('cid');
69 if (Config::get('system', 'thread_allow') && $a->theme_thread_allow && !$this->isToplevel()) {
70 $this->threaded = true;
73 // Prepare the children
74 if (count($data['children'])) {
75 foreach ($data['children'] as $item) {
77 * 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 Item($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->getConversation();
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 = ((($conv->getProfileOwner() == local_user()) && ($item['private'] != 1)) ? true : false);
147 if (local_user() && link_compare($a->contact['url'], $item['author-link'])) {
148 if ($item["event-id"] != 0) {
149 $edpost = array("events/event/".$item['event-id'], t("Edit"));
151 $edpost = array("editpost/".$item['id'], t("Edit"));
157 if (($this->getDataValue('uid') == local_user()) || $this->isVisiting()) {
162 'dropping' => $dropping,
163 'pagedrop' => ((feature_enabled($conv->getProfileOwner(), 'multi_delete')) ? $item['pagedrop'] : ''),
164 'select' => t('Select'),
165 'delete' => t('Delete'),
168 $filer = (($conv->getProfileOwner() == local_user()) ? t("save to folder") : false);
170 $diff_author = ((link_compare($item['url'], $item['author-link'])) ? false : true);
171 $profile_name = htmlentities(((strlen($item['author-name'])) && $diff_author) ? $item['author-name'] : $item['name']);
172 if ($item['author-link'] && (! $item['author-name'])) {
173 $profile_name = $item['author-link'];
177 $profile_link = best_link_url($item, $sp);
178 if ($profile_link === 'mailbox') {
183 $sparkle = ' sparkle';
185 $profile_link = zrl($profile_link);
188 if (!isset($item['author-thumb']) || ($item['author-thumb'] == "")) {
189 $author_contact = Contact::getDetailsByURL($item['author-link'], $conv->getProfileOwner());
190 if ($author_contact["thumb"]) {
191 $item['author-thumb'] = $author_contact["thumb"];
193 $item['author-thumb'] = $item['author-avatar'];
197 if (!isset($item['owner-thumb']) || ($item['owner-thumb'] == "")) {
198 $owner_contact = Contact::getDetailsByURL($item['owner-link'], $conv->getProfileOwner());
199 if ($owner_contact["thumb"]) {
200 $item['owner-thumb'] = $owner_contact["thumb"];
202 $item['owner-thumb'] = $item['owner-avatar'];
206 $locate = array('location' => $item['location'], 'coord' => $item['coord'], 'html' => '');
207 call_hooks('render_location', $locate);
208 $location = ((strlen($locate['html'])) ? $locate['html'] : render_location_dummy($locate));
214 /*foreach(explode(',',$item['tag']) as $tag){
226 // process action responses - e.g. like/dislike/attend/agree/whatever
227 $response_verbs = array('like', 'dislike');
229 if ($item['object-type'] === ACTIVITY_OBJ_EVENT) {
230 $response_verbs[] = 'attendyes';
231 $response_verbs[] = 'attendno';
232 $response_verbs[] = 'attendmaybe';
233 if ($conv->isWritable()) {
235 $attend = array( t('I will attend'), t('I will not attend'), t('I might attend'));
239 $responses = get_responses($conv_responses, $response_verbs, $this, $item);
241 foreach ($response_verbs as $value => $verbs) {
242 $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']) : '');
246 * We should avoid doing this all the time, but it depends on the conversation mode
247 * And the conv mode may change when we change the conv, or it changes its mode
248 * Maybe we should establish a way to be notified about conversation changes
250 $this->checkWallToWall();
252 if ($this->isWallToWall() && ($this->getOwnerUrl() == $this->getRedirectUrl())) {
253 $osparkle = ' sparkle';
256 if ($this->isToplevel()) {
257 if ($conv->getProfileOwner() == local_user()) {
258 $isstarred = (($item['starred']) ? "starred" : "unstarred");
261 'do' => t("add star"),
262 'undo' => t("remove star"),
263 'toggle' => t("toggle star status"),
264 'classdo' => (($item['starred']) ? "hidden" : ""),
265 'classundo' => (($item['starred']) ? "" : "hidden"),
266 'starred' => t('starred'),
268 $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1));
269 if (DBM::is_result($r)) {
271 'do' => t("ignore thread"),
272 'undo' => t("unignore thread"),
273 'toggle' => t("toggle ignore status"),
274 'classdo' => (($r['ignored']) ? "hidden" : ""),
275 'classundo' => (($r['ignored']) ? "" : "hidden"),
276 'ignored' => t('ignored'),
281 if (feature_enabled($conv->getProfileOwner(), 'commtag')) {
283 'add' => t("add tag"),
292 if ($conv->isWritable()) {
294 'like' => array( t("I like this \x28toggle\x29"), t("like")),
295 'dislike' => ((feature_enabled($conv->getProfileOwner(), 'dislike')) ? array( t("I don't like this \x28toggle\x29"), t("dislike")) : ''),
298 $buttons['share'] = array( t('Share this'), t('share'));
302 $comment = $this->getCommentBox($indent);
304 if (strcmp(datetime_convert('UTC', 'UTC', $item['created']), datetime_convert('UTC', 'UTC', 'now - 12 hours')) > 0) {
308 localize_item($item);
310 $body = prepare_body($item, true);
312 list($categories, $folders) = get_cats_and_terms($item);
314 if ($a->theme['template_engine'] === 'internal') {
315 $body_e = template_escape($body);
316 $text_e = strip_tags(template_escape($body));
317 $name_e = template_escape($profile_name);
318 $title_e = template_escape($item['title']);
319 $location_e = template_escape($location);
320 $owner_name_e = template_escape($this->getOwnerName());
323 $text_e = strip_tags($body);
324 $name_e = $profile_name;
325 $title_e = $item['title'];
326 $location_e = $location;
327 $owner_name_e = $this->getOwnerName();
330 // Disable features that aren't available in several networks
332 /// @todo Add NETWORK_DIASPORA when it will pass this information
333 if (!in_array($item["item_network"], array(NETWORK_DFRN)) && isset($buttons["dislike"])) {
334 unset($buttons["dislike"], $isevent);
338 if (($item["item_network"] == NETWORK_FEED) && isset($buttons["like"])) {
339 unset($buttons["like"]);
342 if (($item["item_network"] == NETWORK_MAIL) && isset($buttons["like"])) {
343 unset($buttons["like"]);
347 'template' => $this->getTemplate(),
348 'type' => implode("", array_slice(explode("/", $item['verb']), -1)),
349 'tags' => $item['tags'],
350 'hashtags' => $item['hashtags'],
351 'mentions' => $item['mentions'],
352 'txt_cats' => t('Categories:'),
353 'txt_folders' => t('Filed under:'),
354 'has_cats' => ((count($categories)) ? 'true' : ''),
355 'has_folders' => ((count($folders)) ? 'true' : ''),
356 'categories' => $categories,
357 'folders' => $folders,
360 'id' => $this->getId(),
361 'guid' => urlencode($item['guid']),
362 'isevent' => $isevent,
364 'linktitle' => sprintf(t('View %s\'s profile @ %s'), $profile_name, ((strlen($item['author-link'])) ? $item['author-link'] : $item['url'])),
365 'olinktitle' => sprintf(t('View %s\'s profile @ %s'), htmlentities($this->getOwnerName()), ((strlen($item['owner-link'])) ? $item['owner-link'] : $item['url'])),
368 'wall' => t('Wall-to-Wall'),
369 'vwall' => t('via Wall-To-Wall:'),
370 'profile_url' => $profile_link,
371 'item_photo_menu' => item_photo_menu($item),
373 'thumb' => $a->remove_baseurl(proxy_url($item['author-thumb'], false, PROXY_SIZE_THUMB)),
374 'osparkle' => $osparkle,
375 'sparkle' => $sparkle,
377 'localtime' => datetime_convert('UTC', date_default_timezone_get(), $item['created'], 'r'),
378 'ago' => (($item['app']) ? sprintf(t('%s from %s'), relative_date($item['created']), $item['app']) : relative_date($item['created'])),
379 'app' => $item['app'],
380 'created' => relative_date($item['created']),
382 'location' => $location_e,
385 'owner_url' => $this->getOwnerUrl(),
386 'owner_photo' => $a->remove_baseurl(proxy_url($item['owner-thumb'], false, PROXY_SIZE_THUMB)),
387 'owner_name' => htmlentities($owner_name_e),
388 'plink' => get_plink($item),
389 'edpost' => ((feature_enabled($conv->getProfileOwner(), 'edit_posts')) ? $edpost : ''),
390 'isstarred' => $isstarred,
391 'star' => ((feature_enabled($conv->getProfileOwner(), 'star_posts')) ? $star : ''),
392 'ignore' => ((feature_enabled($conv->getProfileOwner(), 'ignore_posts')) ? $ignore : ''),
394 'filer' => ((feature_enabled($conv->getProfileOwner(), 'filing')) ? $filer : ''),
397 'like' => $responses['like']['output'],
398 'dislike' => $responses['dislike']['output'],
399 'responses' => $responses,
400 'switchcomment' => t('Comment'),
401 'comment' => $comment,
402 'previewing' => ($conv->isPreview() ? ' preview ' : ''),
403 'wait' => t('Please wait'),
404 'thread_level' => $thread_level,
406 'network' => $item["item_network"],
407 'network_name' => network_to_name($item['item_network'], $profile_link),
408 'received' => $item['received'],
409 'commented' => $item['commented'],
410 'created_date' => $item['created'],
413 $arr = array('item' => $item, 'output' => $tmp_item);
414 call_hooks('display_item', $arr);
416 $result = $arr['output'];
418 $result['children'] = array();
419 $children = $this->getChildren();
420 $nb_children = count($children);
421 if ($nb_children > 0) {
422 foreach ($children as $child) {
423 $result['children'][] = $child->getTemplateData($conv_responses, $thread_level + 1);
426 if (($nb_children > 2) || ($thread_level > 1)) {
427 $result['children'][0]['comment_firstcollapsed'] = true;
428 $result['children'][0]['num_comments'] = sprintf(tt('%d comment', '%d comments', $total_children), $total_children);
429 $result['children'][0]['hidden_comments_num'] = $total_children;
430 $result['children'][0]['hidden_comments_text'] = tt('comment', 'comments', $total_children);
431 $result['children'][0]['hide_text'] = t('show more');
432 if ($thread_level > 1) {
433 $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true;
435 $result['children'][$nb_children - 3]['comment_lastcollapsed'] = true;
440 if ($this->isToplevel()) {
441 $result['total_comments_num'] = "$total_children";
442 $result['total_comments_text'] = tt('comment', 'comments', $total_children);
445 $result['private'] = $item['private'];
446 $result['toplevel'] = ($this->isToplevel() ? 'toplevel_item' : '');
448 if ($this->isThreaded()) {
449 $result['flatten'] = false;
450 $result['threaded'] = true;
452 $result['flatten'] = true;
453 $result['threaded'] = false;
462 public function getId()
464 return $this->getDataValue('id');
470 public function isThreaded()
472 return $this->threaded;
478 * @param object $item The child item to add
482 public function addChild(Item $item)
484 $item_id = $item->getId();
486 logger('[ERROR] Item::addChild : Item has no ID!!', LOGGER_DEBUG);
488 } elseif ($this->getChild($item->getId())) {
489 logger('[WARN] Item::addChild : Item already exists ('. $item->getId() .').', LOGGER_DEBUG);
493 * Only add what will be displayed
495 if ($item->getDataValue('network') === NETWORK_MAIL && local_user() != $item->getDataValue('uid')) {
497 } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) {
501 $item->setParent($this);
502 $this->children[] = $item;
504 return end($this->children);
508 * Get a child by its ID
510 * @param integer $id The child id
514 public function getChild($id)
516 foreach ($this->getChildren() as $child) {
517 if ($child->getId() == $id) {
526 * Get all our children
530 public function getChildren()
532 return $this->children;
538 * @param object $item The item to set as parent
542 protected function setParent($item)
544 $parent = $this->getParent();
546 $parent->removeChild($this);
549 $this->parent = $item;
550 $this->setConversation($item->getConversation());
558 protected function removeParent()
560 $this->parent = null;
561 $this->conversation = null;
567 * @param object $item The child to be removed
569 * @return boolean Success or failure
571 public function removeChild($item)
573 $id = $item->getId();
574 foreach ($this->getChildren() as $key => $child) {
575 if ($child->getId() == $id) {
576 $child->removeParent();
577 unset($this->children[$key]);
578 // Reindex the array, in order to make sure there won't be any trouble on loops using count()
579 $this->children = array_values($this->children);
583 logger('[WARN] Item::removeChild : Item is not a child ('. $id .').', LOGGER_DEBUG);
592 protected function getParent()
594 return $this->parent;
600 * @param object $conv The conversation
604 public function setConversation($conv)
606 $previous_mode = ($this->conversation ? $this->conversation->getMode() : '');
608 $this->conversation = $conv;
610 // Set it on our children too
611 foreach ($this->getChildren() as $child) {
612 $child->setConversation($conv);
621 public function getConversation()
623 return $this->conversation;
629 * We shouldn't need this
633 public function getData()
641 * @param object $name key
643 * @return mixed value on success
646 public function getDataValue($name)
648 if (!isset($this->data[$name])) {
649 // logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG);
653 return $this->data[$name];
659 * @param object $name template name
663 private function setTemplate($name)
665 if (!x($this->available_templates, $name)) {
666 logger('[ERROR] Item::setTemplate : Template not available ("'. $name .'").', LOGGER_DEBUG);
670 $this->template = $this->available_templates[$name];
678 private function getTemplate()
680 return $this->template;
684 * Check if this is a toplevel post
688 private function isToplevel()
690 return $this->toplevel;
694 * Check if this is writable
698 private function isWritable()
700 $conv = $this->getConversation();
703 // This will allow us to comment on wall-to-wall items owned by our friends
704 // and community forums even if somebody else wrote the post.
706 // bug #517 - this fixes for conversation owner
707 if ($conv->getMode() == 'profile' && $conv->getProfileOwner() == local_user()) {
711 // this fixes for visitors
712 return ($this->writable || ($this->isVisiting() && $conv->getMode() == 'profile'));
714 return $this->writable;
718 * Count the total of our descendants
722 private function countDescendants()
724 $children = $this->getChildren();
725 $total = count($children);
727 foreach ($children as $child) {
728 $total += $child->countDescendants();
736 * Get the template for the comment box
740 private function getCommentBoxTemplate()
742 return $this->comment_box_template;
746 * Get the comment box
748 * @param string $indent Indent value
750 * @return mixed The comment box string (empty if no comment box)
753 private function getCommentBox($indent)
756 if (!$this->isToplevel() && !(Config::get('system', 'thread_allow') && $a->theme_thread_allow)) {
761 $conv = $this->getConversation();
762 $template = get_markup_template($this->getCommentBoxTemplate());
764 if (($conv->getMode() === 'network') && $this->isWallToWall()) {
768 if ($conv->isWritable() && $this->isWritable()) {
769 $qc = $qcomment = null;
772 * Hmmm, code depending on the presence of a particular plugin?
773 * This should be better if done by a hook
775 if (in_array('qcomment', $a->plugins)) {
776 $qc = ((local_user()) ? PConfig::get(local_user(), 'qcomment', 'words') : null);
777 $qcomment = (($qc) ? explode("\n", $qc) : null);
780 $comment_box = replace_macros(
783 '$return_path' => $a->query_string,
784 '$threaded' => $this->isThreaded(),
785 // '$jsreload' => (($conv->getMode() === 'display') ? $_SESSION['return_url'] : ''),
787 '$type' => (($conv->getMode() === 'profile') ? 'wall-comment' : 'net-comment'),
788 '$id' => $this->getId(),
789 '$parent' => $this->getId(),
790 '$qcomment' => $qcomment,
791 '$profile_uid' => $conv->getProfileOwner(),
792 '$mylink' => $a->remove_baseurl($a->contact['url']),
793 '$mytitle' => t('This is you'),
794 '$myphoto' => $a->remove_baseurl($a->contact['thumb']),
795 '$comment' => t('Comment'),
796 '$submit' => t('Submit'),
797 '$edbold' => t('Bold'),
798 '$editalic' => t('Italic'),
799 '$eduline' => t('Underline'),
800 '$edquote' => t('Quote'),
801 '$edcode' => t('Code'),
802 '$edimg' => t('Image'),
803 '$edurl' => t('Link'),
804 '$edvideo' => t('Video'),
805 '$preview' => ((feature_enabled($conv->getProfileOwner(), 'preview')) ? t('Preview') : ''),
806 '$indent' => $indent,
807 '$sourceapp' => t($a->sourcename),
808 '$ww' => (($conv->getMode() === 'network') ? $ww : ''),
809 '$rand_num' => random_digits(12))
819 private function getRedirectUrl()
821 return $this->redirect_url;
825 * Check if we are a wall to wall item and set the relevant properties
829 protected function checkWallToWall()
832 $conv = $this->getConversation();
833 $this->wall_to_wall = false;
835 if ($this->isToplevel()) {
836 if ($conv->getMode() !== 'profile') {
837 if ($this->getDataValue('wall') && !$this->getDataValue('self')) {
838 // On the network page, I am the owner. On the display page it will be the profile owner.
839 // This will have been stored in $a->page_contact by our calling page.
840 // Put this person as the wall owner of the wall-to-wall notice.
842 $this->owner_url = zrl($a->page_contact['url']);
843 $this->owner_photo = $a->page_contact['thumb'];
844 $this->owner_name = $a->page_contact['name'];
845 $this->wall_to_wall = true;
846 } elseif ($this->getDataValue('owner-link')) {
847 $owner_linkmatch = (($this->getDataValue('owner-link')) && link_compare($this->getDataValue('owner-link'), $this->getDataValue('author-link')));
848 $alias_linkmatch = (($this->getDataValue('alias')) && link_compare($this->getDataValue('alias'), $this->getDataValue('author-link')));
849 $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
851 if ((! $owner_linkmatch) && (! $alias_linkmatch) && (! $owner_namematch)) {
852 // The author url doesn't match the owner (typically the contact)
853 // and also doesn't match the contact alias.
854 // The name match is a hack to catch several weird cases where URLs are
855 // all over the park. It can be tricked, but this prevents you from
856 // seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
857 // well that it's the same Bob Smith.
859 // But it could be somebody else with the same name. It just isn't highly likely.
862 $this->owner_photo = $this->getDataValue('owner-avatar');
863 $this->owner_name = $this->getDataValue('owner-name');
864 $this->wall_to_wall = true;
865 // If it is our contact, use a friendly redirect link
866 if ((link_compare($this->getDataValue('owner-link'), $this->getDataValue('url')))
867 && ($this->getDataValue('network') === NETWORK_DFRN)
869 $this->owner_url = $this->getRedirectUrl();
871 $this->owner_url = zrl($this->getDataValue('owner-link'));
878 if (!$this->wall_to_wall) {
879 $this->setTemplate('wall');
880 $this->owner_url = '';
881 $this->owner_photo = '';
882 $this->owner_name = '';
889 private function isWallToWall()
891 return $this->wall_to_wall;
897 private function getOwnerUrl()
899 return $this->owner_url;
905 private function getOwnerPhoto()
907 return $this->owner_photo;
913 private function getOwnerName()
915 return $this->owner_name;
921 private function isVisiting()
923 return $this->visiting;