Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

946 lines
27 KiB

10 years ago
  1. <?php
  2. /**
  3. * @file include/event.php
  4. * @brief functions specific to event handling
  5. */
  6. use Friendica\App;
  7. require_once 'include/bbcode.php';
  8. require_once 'include/map.php';
  9. require_once 'include/datetime.php';
  10. function format_event_html($ev, $simple = false) {
  11. if (! ((is_array($ev)) && count($ev))) {
  12. return '';
  13. }
  14. $bd_format = t('l F d, Y \@ g:i A') ; // Friday January 18, 2011 @ 8 AM
  15. $event_start = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
  16. $ev['start'] , $bd_format ))
  17. : day_translate(datetime_convert('UTC', 'UTC',
  18. $ev['start'] , $bd_format)));
  19. $event_end = (($ev['adjust']) ? day_translate(datetime_convert('UTC', date_default_timezone_get(),
  20. $ev['finish'] , $bd_format ))
  21. : day_translate(datetime_convert('UTC', 'UTC',
  22. $ev['finish'] , $bd_format )));
  23. if ($simple) {
  24. $o = "<h3>" . bbcode($ev['summary']) . "</h3>";
  25. $o .= "<p>" . bbcode($ev['desc']) . "</p>";
  26. $o .= "<h4>" . t('Starts:') . "</h4><p>" . $event_start . "</p>";
  27. if (! $ev['nofinish']) {
  28. $o .= "<h4>" . t('Finishes:') . "</h4><p>" . $event_end ."</p>";
  29. }
  30. if (strlen($ev['location'])) {
  31. $o .= "<h4>" . t('Location:') . "</h4><p>" . $ev['location'] . "</p>";
  32. }
  33. return $o;
  34. }
  35. $o = '<div class="vevent">' . "\r\n";
  36. $o .= '<p class="summary event-summary">' . bbcode($ev['summary']) . '</p>' . "\r\n";
  37. $o .= '<p class="description event-description">' . bbcode($ev['desc']) . '</p>' . "\r\n";
  38. $o .= '<p class="event-start">' . t('Starts:') . ' <abbr class="dtstart" title="'
  39. . datetime_convert('UTC', 'UTC', $ev['start'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
  40. . '" >'.$event_start
  41. . '</abbr></p>' . "\r\n";
  42. if (! $ev['nofinish']) {
  43. $o .= '<p class="event-end" >' . t('Finishes:') . ' <abbr class="dtend" title="'
  44. . datetime_convert('UTC', 'UTC', $ev['finish'], (($ev['adjust']) ? ATOM_TIME : 'Y-m-d\TH:i:s' ))
  45. . '" >'.$event_end
  46. . '</abbr></p>' . "\r\n";
  47. }
  48. if (strlen($ev['location'])) {
  49. $o .= '<p class="event-location"> ' . t('Location:') . ' <span class="location">'
  50. . bbcode($ev['location'])
  51. . '</span></p>' . "\r\n";
  52. // Include a map of the location if the [map] BBCode is used
  53. if (strpos($ev['location'], "[map") !== false) {
  54. $map = generate_named_map($ev['location']);
  55. if ($map !== $ev['location']) {
  56. $o.= $map;
  57. }
  58. }
  59. }
  60. $o .= '</div>' . "\r\n";
  61. return $o;
  62. }
  63. /*
  64. @TODO old-lost code found?
  65. function parse_event($h) {
  66. require_once('include/Scrape.php');
  67. require_once('include/html2bbcode');
  68. $h = '<html><body>' . $h . '</body></html>';
  69. $ret = array();
  70. try {
  71. $dom = HTML5_Parser::parse($h);
  72. } catch (DOMException $e) {
  73. logger('parse_event: parse error: ' . $e);
  74. }
  75. if (! $dom)
  76. return $ret;
  77. $items = $dom->getElementsByTagName('*');
  78. foreach ($items as $item) {
  79. if (attribute_contains($item->getAttribute('class'), 'vevent')) {
  80. $level2 = $item->getElementsByTagName('*');
  81. foreach ($level2 as $x) {
  82. if (attribute_contains($x->getAttribute('class'),'dtstart') && $x->getAttribute('title')) {
  83. $ret['start'] = $x->getAttribute('title');
  84. if (! strpos($ret['start'],'Z'))
  85. $ret['adjust'] = true;
  86. }
  87. if (attribute_contains($x->getAttribute('class'),'dtend') && $x->getAttribute('title'))
  88. $ret['finish'] = $x->getAttribute('title');
  89. if (attribute_contains($x->getAttribute('class'),'description'))
  90. $ret['desc'] = $x->textContent;
  91. if (attribute_contains($x->getAttribute('class'),'location'))
  92. $ret['location'] = $x->textContent;
  93. }
  94. }
  95. }
  96. // sanitise
  97. if ((x($ret,'desc')) && ((strpos($ret['desc'],'<') !== false) || (strpos($ret['desc'],'>') !== false))) {
  98. $config = HTMLPurifier_Config::createDefault();
  99. $config->set('Cache.DefinitionImpl', null);
  100. $purifier = new HTMLPurifier($config);
  101. $ret['desc'] = html2bbcode($purifier->purify($ret['desc']));
  102. }
  103. if ((x($ret,'location')) && ((strpos($ret['location'],'<') !== false) || (strpos($ret['location'],'>') !== false))) {
  104. $config = HTMLPurifier_Config::createDefault();
  105. $config->set('Cache.DefinitionImpl', null);
  106. $purifier = new HTMLPurifier($config);
  107. $ret['location'] = html2bbcode($purifier->purify($ret['location']));
  108. }
  109. if (x($ret,'start'))
  110. $ret['start'] = datetime_convert('UTC','UTC',$ret['start']);
  111. if (x($ret,'finish'))
  112. $ret['finish'] = datetime_convert('UTC','UTC',$ret['finish']);
  113. return $ret;
  114. }
  115. */
  116. function format_event_bbcode($ev) {
  117. $o = '';
  118. if ($ev['summary']) {
  119. $o .= '[event-summary]' . $ev['summary'] . '[/event-summary]';
  120. }
  121. if ($ev['desc']) {
  122. $o .= '[event-description]' . $ev['desc'] . '[/event-description]';
  123. }
  124. if ($ev['start']) {
  125. $o .= '[event-start]' . $ev['start'] . '[/event-start]';
  126. }
  127. if (($ev['finish']) && (! $ev['nofinish'])) {
  128. $o .= '[event-finish]' . $ev['finish'] . '[/event-finish]';
  129. }
  130. if ($ev['location']) {
  131. $o .= '[event-location]' . $ev['location'] . '[/event-location]';
  132. }
  133. if ($ev['adjust']) {
  134. $o .= '[event-adjust]' . $ev['adjust'] . '[/event-adjust]';
  135. }
  136. return $o;
  137. }
  138. function bbtovcal($s) {
  139. $o = '';
  140. $ev = bbtoevent($s);
  141. if ($ev['desc']) {
  142. $o = format_event_html($ev);
  143. }
  144. return $o;
  145. }
  146. function bbtoevent($s) {
  147. $ev = array();
  148. $match = '';
  149. if (preg_match("/\[event\-summary\](.*?)\[\/event\-summary\]/is", $s, $match)) {
  150. $ev['summary'] = $match[1];
  151. }
  152. $match = '';
  153. if (preg_match("/\[event\-description\](.*?)\[\/event\-description\]/is", $s, $match)) {
  154. $ev['desc'] = $match[1];
  155. }
  156. $match = '';
  157. if (preg_match("/\[event\-start\](.*?)\[\/event\-start\]/is", $s, $match)) {
  158. $ev['start'] = $match[1];
  159. }
  160. $match = '';
  161. if (preg_match("/\[event\-finish\](.*?)\[\/event\-finish\]/is", $s, $match)) {
  162. $ev['finish'] = $match[1];
  163. }
  164. $match = '';
  165. if (preg_match("/\[event\-location\](.*?)\[\/event\-location\]/is", $s, $match)) {
  166. $ev['location'] = $match[1];
  167. }
  168. $match = '';
  169. if (preg_match("/\[event\-adjust\](.*?)\[\/event\-adjust\]/is", $s, $match)) {
  170. $ev['adjust'] = $match[1];
  171. }
  172. $ev['nofinish'] = (((x($ev, 'start') && $ev['start']) && (!x($ev, 'finish') || !$ev['finish'])) ? 1 : 0);
  173. return $ev;
  174. }
  175. function sort_by_date($a) {
  176. usort($a,'ev_compare');
  177. return $a;
  178. }
  179. function ev_compare($a,$b) {
  180. $date_a = (($a['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $a['start']) : $a['start']);
  181. $date_b = (($b['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $b['start']) : $b['start']);
  182. if ($date_a === $date_b) {
  183. return strcasecmp($a['desc'], $b['desc']);
  184. }
  185. return strcmp($date_a, $date_b);
  186. }
  187. function event_delete($event_id) {
  188. if ($event_id == 0) {
  189. return;
  190. }
  191. q("DELETE FROM `event` WHERE `id` = %d", intval($event_id));
  192. logger("Deleted event ".$event_id, LOGGER_DEBUG);
  193. }
  194. function event_store($arr) {
  195. require_once 'include/datetime.php';
  196. require_once 'include/items.php';
  197. require_once 'include/bbcode.php';
  198. $a = get_app();
  199. $arr['created'] = (($arr['created']) ? $arr['created'] : datetime_convert());
  200. $arr['edited'] = (($arr['edited']) ? $arr['edited'] : datetime_convert());
  201. $arr['type'] = (($arr['type']) ? $arr['type'] : 'event' );
  202. $arr['cid'] = ((intval($arr['cid'])) ? intval($arr['cid']) : 0);
  203. $arr['uri'] = (x($arr, 'uri') ? $arr['uri'] : item_new_uri($a->get_hostname(), $arr['uid']));
  204. $arr['private'] = ((x($arr, 'private')) ? intval($arr['private']) : 0);
  205. $arr['guid'] = get_guid(32);
  206. if ($arr['cid']) {
  207. $c = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  208. intval($arr['cid']),
  209. intval($arr['uid'])
  210. );
  211. } else {
  212. $c = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
  213. intval($arr['uid'])
  214. );
  215. }
  216. if (dbm::is_result($c)) {
  217. $contact = $c[0];
  218. }
  219. // Existing event being modified
  220. if ($arr['id']) {
  221. // has the event actually changed?
  222. $r = q("SELECT * FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  223. intval($arr['id']),
  224. intval($arr['uid'])
  225. );
  226. if ((! dbm::is_result($r)) || ($r[0]['edited'] === $arr['edited'])) {
  227. // Nothing has changed. Grab the item id to return.
  228. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  229. intval($arr['id']),
  230. intval($arr['uid'])
  231. );
  232. return ((dbm::is_result($r)) ? $r[0]['id'] : 0);
  233. }
  234. // The event changed. Update it.
  235. $r = q("UPDATE `event` SET
  236. `edited` = '%s',
  237. `start` = '%s',
  238. `finish` = '%s',
  239. `summary` = '%s',
  240. `desc` = '%s',
  241. `location` = '%s',
  242. `type` = '%s',
  243. `adjust` = %d,
  244. `nofinish` = %d
  245. WHERE `id` = %d AND `uid` = %d",
  246. dbesc($arr['edited']),
  247. dbesc($arr['start']),
  248. dbesc($arr['finish']),
  249. dbesc($arr['summary']),
  250. dbesc($arr['desc']),
  251. dbesc($arr['location']),
  252. dbesc($arr['type']),
  253. intval($arr['adjust']),
  254. intval($arr['nofinish']),
  255. intval($arr['id']),
  256. intval($arr['uid'])
  257. );
  258. $r = q("SELECT * FROM `item` WHERE `event-id` = %d AND `uid` = %d LIMIT 1",
  259. intval($arr['id']),
  260. intval($arr['uid'])
  261. );
  262. if (dbm::is_result($r)) {
  263. $object = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  264. $object .= '<content>' . xmlify(format_event_bbcode($arr)) . '</content>';
  265. $object .= '</object>' . "\n";
  266. q("UPDATE `item` SET `body` = '%s', `object` = '%s', `edited` = '%s' WHERE `id` = %d AND `uid` = %d",
  267. dbesc(format_event_bbcode($arr)),
  268. dbesc($object),
  269. dbesc($arr['edited']),
  270. intval($r[0]['id']),
  271. intval($arr['uid'])
  272. );
  273. $item_id = $r[0]['id'];
  274. } else {
  275. $item_id = 0;
  276. }
  277. call_hooks("event_updated", $arr['id']);
  278. return $item_id;
  279. } else {
  280. // New event. Store it.
  281. $r = q("INSERT INTO `event` (`uid`,`cid`,`guid`,`uri`,`created`,`edited`,`start`,`finish`,`summary`, `desc`,`location`,`type`,
  282. `adjust`,`nofinish`,`allow_cid`,`allow_gid`,`deny_cid`,`deny_gid`)
  283. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s' ) ",
  284. intval($arr['uid']),
  285. intval($arr['cid']),
  286. dbesc($arr['guid']),
  287. dbesc($arr['uri']),
  288. dbesc($arr['created']),
  289. dbesc($arr['edited']),
  290. dbesc($arr['start']),
  291. dbesc($arr['finish']),
  292. dbesc($arr['summary']),
  293. dbesc($arr['desc']),
  294. dbesc($arr['location']),
  295. dbesc($arr['type']),
  296. intval($arr['adjust']),
  297. intval($arr['nofinish']),
  298. dbesc($arr['allow_cid']),
  299. dbesc($arr['allow_gid']),
  300. dbesc($arr['deny_cid']),
  301. dbesc($arr['deny_gid'])
  302. );
  303. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  304. dbesc($arr['uri']),
  305. intval($arr['uid'])
  306. );
  307. if (dbm::is_result($r)) {
  308. $event = $r[0];
  309. }
  310. $item_arr = array();
  311. $item_arr['uid'] = $arr['uid'];
  312. $item_arr['contact-id'] = $arr['cid'];
  313. $item_arr['uri'] = $arr['uri'];
  314. $item_arr['parent-uri'] = $arr['uri'];
  315. $item_arr['guid'] = $arr['guid'];
  316. $item_arr['type'] = 'activity';
  317. $item_arr['wall'] = (($arr['cid']) ? 0 : 1);
  318. $item_arr['contact-id'] = $contact['id'];
  319. $item_arr['owner-name'] = $contact['name'];
  320. $item_arr['owner-link'] = $contact['url'];
  321. $item_arr['owner-avatar'] = $contact['thumb'];
  322. $item_arr['author-name'] = $contact['name'];
  323. $item_arr['author-link'] = $contact['url'];
  324. $item_arr['author-avatar'] = $contact['thumb'];
  325. $item_arr['title'] = '';
  326. $item_arr['allow_cid'] = $arr['allow_cid'];
  327. $item_arr['allow_gid'] = $arr['allow_gid'];
  328. $item_arr['deny_cid'] = $arr['deny_cid'];
  329. $item_arr['deny_gid'] = $arr['deny_gid'];
  330. $item_arr['private'] = $arr['private'];
  331. $item_arr['last-child'] = 1;
  332. $item_arr['visible'] = 1;
  333. $item_arr['verb'] = ACTIVITY_POST;
  334. $item_arr['object-type'] = ACTIVITY_OBJ_EVENT;
  335. $item_arr['origin'] = ((intval($arr['cid']) == 0) ? 1 : 0);
  336. $item_arr['body'] = format_event_bbcode($event);
  337. $item_arr['object'] = '<object><type>' . xmlify(ACTIVITY_OBJ_EVENT) . '</type><title></title><id>' . xmlify($arr['uri']) . '</id>';
  338. $item_arr['object'] .= '<content>' . xmlify(format_event_bbcode($event)) . '</content>';
  339. $item_arr['object'] .= '</object>' . "\n";
  340. $item_id = item_store($item_arr);
  341. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  342. intval($arr['uid'])
  343. );
  344. //if (dbm::is_result($r))
  345. // $plink = App::get_baseurl() . '/display/' . $r[0]['nickname'] . '/' . $item_id;
  346. if ($item_id) {
  347. //q("UPDATE `item` SET `plink` = '%s', `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  348. // dbesc($plink),
  349. // intval($event['id']),
  350. // intval($arr['uid']),
  351. // intval($item_id)
  352. //);
  353. q("UPDATE `item` SET `event-id` = %d WHERE `uid` = %d AND `id` = %d",
  354. intval($event['id']),
  355. intval($arr['uid']),
  356. intval($item_id)
  357. );
  358. }
  359. call_hooks("event_created", $event['id']);
  360. return $item_id;
  361. }
  362. }
  363. function get_event_strings() {
  364. // First day of the week (0 = Sunday)
  365. $firstDay = get_pconfig(local_user(), 'system', 'first_day_of_week');
  366. if ($firstDay === false) {
  367. $firstDay = 0;
  368. }
  369. $i18n = array(
  370. "firstDay" => $firstDay,
  371. "allday" => t("all-day"),
  372. "Sun" => t("Sun"),
  373. "Mon" => t("Mon"),
  374. "Tue" => t("Tue"),
  375. "Wed" => t("Wed"),
  376. "Thu" => t("Thu"),
  377. "Fri" => t("Fri"),
  378. "Sat" => t("Sat"),
  379. "Sunday" => t("Sunday"),
  380. "Monday" => t("Monday"),
  381. "Tuesday" => t("Tuesday"),
  382. "Wednesday" => t("Wednesday"),
  383. "Thursday" => t("Thursday"),
  384. "Friday" => t("Friday"),
  385. "Saturday" => t("Saturday"),
  386. "Jan" => t("Jan"),
  387. "Feb" => t("Feb"),
  388. "Mar" => t("Mar"),
  389. "Apr" => t("Apr"),
  390. "May" => t("May"),
  391. "Jun" => t("Jun"),
  392. "Jul" => t("Jul"),
  393. "Aug" => t("Aug"),
  394. "Sep" => t("Sept"),
  395. "Oct" => t("Oct"),
  396. "Nov" => t("Nov"),
  397. "Dec" => t("Dec"),
  398. "January" => t("January"),
  399. "February" => t("February"),
  400. "March" => t("March"),
  401. "April" => t("April"),
  402. "May" => t("May"),
  403. "June" => t("June"),
  404. "July" => t("July"),
  405. "August" => t("August"),
  406. "September" => t("September"),
  407. "October" => t("October"),
  408. "November" => t("November"),
  409. "December" => t("December"),
  410. "today" => t("today"),
  411. "month" => t("month"),
  412. "week" => t("week"),
  413. "day" => t("day"),
  414. "noevent" => t("No events to display"),
  415. "dtstart_label" => t("Starts:"),
  416. "dtend_label" => t("Finishes:"),
  417. "location_label" => t("Location:")
  418. );
  419. return $i18n;
  420. }
  421. /**
  422. * @brief Removes duplicated birthday events
  423. *
  424. * @param array $dates Array of possibly duplicated events
  425. * @return array Cleaned events
  426. *
  427. * @todo We should replace this with a separate update function if there is some time left
  428. */
  429. function event_remove_duplicates($dates) {
  430. $dates2 = array();
  431. foreach ($dates AS $date) {
  432. if ($date['type'] == 'birthday') {
  433. $dates2[$date['uid'] . "-" . $date['cid'] . "-" . $date['start']] = $date;
  434. } else {
  435. $dates2[] = $date;
  436. }
  437. }
  438. return $dates2;
  439. }
  440. /**
  441. * @brief Get an event by its event ID
  442. *
  443. * @param type $owner_uid The User ID of the owner of the event
  444. * @param type $event_params An assoziative array with
  445. * int 'event_id' => The ID of the event in the event table
  446. * @param type $sql_extra
  447. * @return array Query result
  448. */
  449. function event_by_id($owner_uid = 0, $event_params, $sql_extra = '') {
  450. // ownly allow events if there is a valid owner_id
  451. if ($owner_uid == 0) {
  452. return;
  453. }
  454. // Query for the event by event id
  455. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  456. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  457. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  458. WHERE `event`.`uid` = %d AND `event`.`id` = %d $sql_extra",
  459. intval($owner_uid),
  460. intval($event_params["event_id"])
  461. );
  462. if (dbm::is_result($r)) {
  463. return event_remove_duplicates($r);
  464. }
  465. }
  466. /**
  467. * @brief Get all events in a specific timeframe
  468. *
  469. * @param int $owner_uid The User ID of the owner of the events
  470. * @param array $event_params An assoziative array with
  471. * int 'ignored' =>
  472. * string 'start' => Start time of the timeframe
  473. * string 'finish' => Finish time of the timeframe
  474. * string 'adjust_start' =>
  475. * string 'adjust_start' =>
  476. *
  477. * @param string $sql_extra Additional sql conditions (e.g. permission request)
  478. * @return array Query results
  479. */
  480. function events_by_date($owner_uid = 0, $event_params, $sql_extra = '') {
  481. // Only allow events if there is a valid owner_id
  482. if ($owner_uid == 0) {
  483. return;
  484. }
  485. // Query for the event by date
  486. $r = q("SELECT `event`.*, `item`.`id` AS `itemid`,`item`.`plink`,
  487. `item`.`author-name`, `item`.`author-avatar`, `item`.`author-link` FROM `event`
  488. LEFT JOIN `item` ON `item`.`event-id` = `event`.`id` AND `item`.`uid` = `event`.`uid`
  489. WHERE `event`.`uid` = %d AND event.ignore = %d
  490. AND ((`adjust` = 0 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s')
  491. OR (`adjust` = 1 AND (`finish` >= '%s' OR (nofinish AND start >= '%s')) AND `start` <= '%s'))
  492. $sql_extra ",
  493. intval($owner_uid),
  494. intval($event_params["ignored"]),
  495. dbesc($event_params["start"]),
  496. dbesc($event_params["start"]),
  497. dbesc($event_params["finish"]),
  498. dbesc($event_params["adjust_start"]),
  499. dbesc($event_params["adjust_start"]),
  500. dbesc($event_params["adjust_finish"])
  501. );
  502. if (dbm::is_result($r)) {
  503. return event_remove_duplicates($r);
  504. }
  505. }
  506. /**
  507. * @brief Convert an array query results in an arry which could be used by the events template
  508. *
  509. * @param array $arr Event query array
  510. * @return array Event array for the template
  511. */
  512. function process_events($arr) {
  513. $events=array();
  514. $last_date = '';
  515. $fmt = t('l, F j');
  516. if (count($arr)) {
  517. foreach ($arr as $rr) {
  518. $j = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'j') : datetime_convert('UTC', 'UTC', $rr['start'], 'j'));
  519. $d = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], $fmt) : datetime_convert('UTC', 'UTC', $rr['start'], $fmt));
  520. $d = day_translate($d);
  521. $start = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['start'], 'c') : datetime_convert('UTC', 'UTC', $rr['start'], 'c'));
  522. if ($rr['nofinish']) {
  523. $end = null;
  524. } else {
  525. $end = (($rr['adjust']) ? datetime_convert('UTC', date_default_timezone_get(), $rr['finish'], 'c') : datetime_convert('UTC', 'UTC', $rr['finish'], 'c'));
  526. }
  527. $is_first = ($d !== $last_date);
  528. $last_date = $d;
  529. // Show edit and drop actions only if the user is the owner of the event and the event
  530. // is a real event (no bithdays)
  531. if (local_user() && local_user() == $rr['uid'] && $rr['type'] == 'event') {
  532. $edit = ((! $rr['cid']) ? array(App::get_baseurl() . '/events/event/' . $rr['id'], t('Edit event'), '', '') : null);
  533. $drop = array(App::get_baseurl() . '/events/drop/' . $rr['id'], t('Delete event'), '', '');
  534. }
  535. $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
  536. if (! $title) {
  537. list($title, $_trash) = explode("<br", bbcode($rr['desc']), 2);
  538. $title = strip_tags(html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
  539. }
  540. $html = format_event_html($rr);
  541. $rr['desc'] = bbcode($rr['desc']);
  542. $rr['location'] = bbcode($rr['location']);
  543. $events[] = array(
  544. 'id' => $rr['id'],
  545. 'start' => $start,
  546. 'end' => $end,
  547. 'allDay' => false,
  548. 'title' => $title,
  549. 'j' => $j,
  550. 'd' => $d,
  551. 'edit' => $edit,
  552. 'drop' => $drop,
  553. 'is_first' => $is_first,
  554. 'item' => $rr,
  555. 'html' => $html,
  556. 'plink' => array($rr['plink'], t('link to source'), '', ''),
  557. );
  558. }
  559. }
  560. return $events;
  561. }
  562. /**
  563. * @brief Format event to export format (ical/csv)
  564. *
  565. * @param array $events Query result for events
  566. * @param string $format The output format (ical/csv)
  567. * @param string $timezone The timezone of the user (not implemented yet)
  568. *
  569. * @return string Content according to selected export format
  570. */
  571. function event_format_export ($events, $format = 'ical', $timezone) {
  572. if (! ((is_array($events)) && count($events))) {
  573. return;
  574. }
  575. switch ($format) {
  576. // Format the exported data as a CSV file
  577. case "csv":
  578. header("Content-type: text/csv");
  579. $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL;
  580. foreach ($events as $event) {
  581. /// @todo The time / date entries don't include any information about the
  582. /// timezone the event is scheduled in :-/
  583. $tmp1 = strtotime($event['start']);
  584. $tmp2 = strtotime($event['finish']);
  585. $time_format = "%H:%M:%S";
  586. $date_format = "%Y-%m-%d";
  587. $o .= '"' . $event['summary'] . '", "' . strftime($date_format, $tmp1) .
  588. '", "' . strftime($time_format, $tmp1) . '", "' . $event['desc'] .
  589. '", "' . strftime($date_format, $tmp2) .
  590. '", "' . strftime($time_format, $tmp2) .
  591. '", "' . $event['location'] . '"' . PHP_EOL;
  592. }
  593. break;
  594. // Format the exported data as a ics file
  595. case "ical":
  596. header("Content-type: text/ics");
  597. $o = 'BEGIN:VCALENDAR' . PHP_EOL
  598. . 'VERSION:2.0' . PHP_EOL
  599. . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL;
  600. /// @todo include timezone informations in cases were the time is not in UTC
  601. // see http://tools.ietf.org/html/rfc2445#section-4.8.3
  602. // . 'BEGIN:VTIMEZONE' . PHP_EOL
  603. // . 'TZID:' . $timezone . PHP_EOL
  604. // . 'END:VTIMEZONE' . PHP_EOL;
  605. // TODO instead of PHP_EOL CRLF should be used for long entries
  606. // but test your solution against http://icalvalid.cloudapp.net/
  607. // also long lines SHOULD be split at 75 characters length
  608. foreach ($events as $event) {
  609. if ($event['adjust'] == 1) {
  610. $UTC = 'Z';
  611. } else {
  612. $UTC = '';
  613. }
  614. $o .= 'BEGIN:VEVENT' . PHP_EOL;
  615. if ($event['start']) {
  616. $tmp = strtotime($event['start']);
  617. $dtformat = "%Y%m%dT%H%M%S" . $UTC;
  618. $o .= 'DTSTART:' . strftime($dtformat, $tmp) . PHP_EOL;
  619. }
  620. if (!$event['nofinish']) {
  621. $tmp = strtotime($event['finish']);
  622. $dtformat = "%Y%m%dT%H%M%S" . $UTC;
  623. $o .= 'DTEND:' . strftime($dtformat, $tmp) . PHP_EOL;
  624. }
  625. if ($event['summary']) {
  626. $tmp = $event['summary'];
  627. $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
  628. $tmp = addcslashes($tmp, ',;');
  629. $o .= 'SUMMARY:' . $tmp . PHP_EOL;
  630. }
  631. if ($event['desc']) {
  632. $tmp = $event['desc'];
  633. $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
  634. $tmp = addcslashes($tmp, ',;');
  635. $o .= 'DESCRIPTION:' . $tmp . PHP_EOL;
  636. }
  637. if ($event['location']) {
  638. $tmp = $event['location'];
  639. $tmp = str_replace(PHP_EOL, PHP_EOL . ' ', $tmp);
  640. $tmp = addcslashes($tmp, ',;');
  641. $o .= 'LOCATION:' . $tmp . PHP_EOL;
  642. }
  643. $o .= 'END:VEVENT' . PHP_EOL;
  644. $o .= PHP_EOL;
  645. }
  646. $o .= 'END:VCALENDAR' . PHP_EOL;
  647. break;
  648. }
  649. return $o;
  650. }
  651. /**
  652. * @brief Get all events for a user ID
  653. *
  654. * The query for events is done permission sensitive
  655. * If the user is the owner of the calendar he/she
  656. * will get all of his/her available events.
  657. * If the user is only a visitor only the public events will
  658. * be available
  659. *
  660. * @param int $uid The user ID
  661. * @param int $sql_extra Additional sql conditions for permission
  662. *
  663. * @return array Query results
  664. */
  665. function events_by_uid($uid = 0, $sql_extra = '') {
  666. if ($uid == 0) {
  667. return;
  668. }
  669. // The permission condition if no condition was transmitted
  670. if ($sql_extra == '') {
  671. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' ";
  672. }
  673. // Does the user who requests happen to be the owner of the events
  674. // requested? then show all of your events, otherwise only those that
  675. // don't have limitations set in allow_cid and allow_gid
  676. if (local_user() == $uid) {
  677. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  678. FROM `event` WHERE `uid`= %d AND `cid` = 0 ",
  679. intval($uid)
  680. );
  681. } else {
  682. $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location`, `nofinish`
  683. FROM `event` WHERE `uid`= %d AND `cid` = 0 $sql_extra ",
  684. intval($uid)
  685. );
  686. }
  687. if (dbm::is_result($r)) {
  688. return $r;
  689. }
  690. }
  691. /**
  692. *
  693. * @param int $uid The user ID
  694. * @param string $format Output format (ical/csv)
  695. * @return array With the results
  696. * bool 'success' => True if the processing was successful
  697. * string 'format' => The output format
  698. * string 'extension' => The file extension of the output format
  699. * string 'content' => The formatted output content
  700. *
  701. * @todo Respect authenticated users with events_by_uid()
  702. */
  703. function event_export($uid, $format = 'ical') {
  704. $process = false;
  705. // We are allowed to show events
  706. // get the timezone the user is in
  707. $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d LIMIT 1", intval($uid));
  708. if (dbm::is_result($r)) {
  709. $timezone = $r[0]['timezone'];
  710. }
  711. // Get all events which are owned by a uid (respects permissions);
  712. $events = events_by_uid($uid);
  713. // We have the events that are available for the requestor
  714. // now format the output according to the requested format
  715. if (count($events)) {
  716. $res = event_format_export($events, $format, $timezone);
  717. }
  718. // If there are results the precess was successfull
  719. if (x($res)) {
  720. $process = true;
  721. }
  722. // Get the file extension for the format
  723. switch ($format) {
  724. case "ical":
  725. $file_ext = "ics";
  726. break;
  727. case "csv":
  728. $file_ext = "csv";
  729. break;
  730. default:
  731. $file_ext = "";
  732. }
  733. $arr = array(
  734. 'success' => $process,
  735. 'format' => $format,
  736. 'extension' => $file_ext,
  737. 'content' => $res,
  738. );
  739. return $arr;
  740. }
  741. /**
  742. * @brief Get the events widget
  743. *
  744. * @return string Formated html of the evens widget
  745. */
  746. function widget_events() {
  747. $a = get_app();
  748. $owner_uid = $a->data['user']['uid'];
  749. // $a->data is only available if the profile page is visited. If the visited page is not part
  750. // of the profile page it should be the personal /events page. So we can use $a->user
  751. $user = ($a->data['user']['nickname'] ? $a->data['user']['nickname'] : $a->user['nickname']);
  752. // The permission testing is a little bit tricky because we have to respect many cases
  753. // It's not the private events page (we don't get the $owner_uid for /events)
  754. if (! local_user() && ! $owner_uid) {
  755. return;
  756. }
  757. // Cal logged in user (test permission at foreign profile page)
  758. // If the $owner uid is available we know it is part of one of the profile pages (like /cal)
  759. // So we have to test if if it's the own profile page of the logged in user
  760. // or a foreign one. For foreign profile pages we need to check if the feature
  761. // for exporting the cal is enabled (otherwise the widget would appear for logged in users
  762. // on foreigen profile pages even if the widget is disabled)
  763. if (intval($owner_uid) && local_user() !== $owner_uid && ! feature_enabled($owner_uid, "export_calendar")) {
  764. return;
  765. }
  766. // If it's a kind of profile page (intval($owner_uid)) return if the user not logged in and
  767. // export feature isn't enabled
  768. if (intval($owner_uid) && ! local_user() && ! feature_enabled($owner_uid, "export_calendar")) {
  769. return;
  770. }
  771. return replace_macros(get_markup_template("events_aside.tpl"), array(
  772. '$etitle' => t("Export"),
  773. '$export_ical' => t("Export calendar as ical"),
  774. '$export_csv' => t("Export calendar as csv"),
  775. '$user' => $user
  776. ));
  777. }