Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

945 lines
27 KiB

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