Subs-Calendar.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. <?php
  2. /**
  3. * This file contains several functions for retrieving and manipulating calendar events, birthdays and holidays.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2014 Simple Machines and individual contributors
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('No direct access...');
  16. /**
  17. * Get all birthdays within the given time range.
  18. * finds all the birthdays in the specified range of days.
  19. * works with birthdays set for no year, or any other year, and respects month and year boundaries.
  20. *
  21. * @param string $low_date inclusive, YYYY-MM-DD
  22. * @param string $high_date inclusive, YYYY-MM-DD
  23. * @return array days, each of which an array of birthday information for the context
  24. */
  25. function getBirthdayRange($low_date, $high_date)
  26. {
  27. global $smcFunc;
  28. // We need to search for any birthday in this range, and whatever year that birthday is on.
  29. $year_low = (int) substr($low_date, 0, 4);
  30. $year_high = (int) substr($high_date, 0, 4);
  31. // Collect all of the birthdays for this month. I know, it's a painful query.
  32. $result = $smcFunc['db_query']('birthday_array', '
  33. SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
  34. FROM {db_prefix}members
  35. WHERE YEAR(birthdate) != {string:year_one}
  36. AND MONTH(birthdate) != {int:no_month}
  37. AND DAYOFMONTH(birthdate) != {int:no_day}
  38. AND YEAR(birthdate) <= {int:max_year}
  39. AND (
  40. DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
  41. OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
  42. )
  43. AND is_activated = {int:is_activated}',
  44. array(
  45. 'is_activated' => 1,
  46. 'no_month' => 0,
  47. 'no_day' => 0,
  48. 'year_one' => '0001',
  49. 'year_low' => $year_low . '-%m-%d',
  50. 'year_high' => $year_high . '-%m-%d',
  51. 'low_date' => $low_date,
  52. 'high_date' => $high_date,
  53. 'max_year' => $year_high,
  54. )
  55. );
  56. $bday = array();
  57. while ($row = $smcFunc['db_fetch_assoc']($result))
  58. {
  59. if ($year_low != $year_high)
  60. $age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
  61. else
  62. $age_year = $year_low;
  63. $bday[$age_year . substr($row['birthdate'], 4)][] = array(
  64. 'id' => $row['id_member'],
  65. 'name' => $row['real_name'],
  66. 'age' => $row['birth_year'] > 4 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
  67. 'is_last' => false
  68. );
  69. }
  70. $smcFunc['db_free_result']($result);
  71. // Set is_last, so the themes know when to stop placing separators.
  72. foreach ($bday as $mday => $array)
  73. $bday[$mday][count($array) - 1]['is_last'] = true;
  74. return $bday;
  75. }
  76. /**
  77. * Get all calendar events within the given time range.
  78. *
  79. * - finds all the posted calendar events within a date range.
  80. * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
  81. * - censors the posted event titles.
  82. * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
  83. *
  84. * @param string $low_date
  85. * @param string $high_date
  86. * @param bool $use_permissions = true
  87. * @return array contextual information if use_permissions is true, and an array of the data needed to build that otherwise
  88. */
  89. function getEventRange($low_date, $high_date, $use_permissions = true)
  90. {
  91. global $scripturl, $modSettings, $user_info, $smcFunc, $context;
  92. $low_date_time = sscanf($low_date, '%04d-%02d-%02d');
  93. $low_date_time = mktime(0, 0, 0, $low_date_time[1], $low_date_time[2], $low_date_time[0]);
  94. $high_date_time = sscanf($high_date, '%04d-%02d-%02d');
  95. $high_date_time = mktime(0, 0, 0, $high_date_time[1], $high_date_time[2], $high_date_time[0]);
  96. // Find all the calendar info...
  97. $result = $smcFunc['db_query']('', '
  98. SELECT
  99. cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, cal.id_topic,
  100. cal.id_board, b.member_groups, t.id_first_msg, t.approved, b.id_board
  101. FROM {db_prefix}calendar AS cal
  102. LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
  103. LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
  104. WHERE cal.start_date <= {date:high_date}
  105. AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
  106. AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
  107. array(
  108. 'high_date' => $high_date,
  109. 'low_date' => $low_date,
  110. 'no_board_link' => 0,
  111. )
  112. );
  113. $events = array();
  114. while ($row = $smcFunc['db_fetch_assoc']($result))
  115. {
  116. // If the attached topic is not approved then for the moment pretend it doesn't exist
  117. if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
  118. continue;
  119. // Force a censor of the title - as often these are used by others.
  120. censorText($row['title'], $use_permissions ? false : true);
  121. $start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
  122. $start_date = max(mktime(0, 0, 0, $start_date[1], $start_date[2], $start_date[0]), $low_date_time);
  123. $end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
  124. $end_date = min(mktime(0, 0, 0, $end_date[1], $end_date[2], $end_date[0]), $high_date_time);
  125. $lastDate = '';
  126. for ($date = $start_date; $date <= $end_date; $date += 86400)
  127. {
  128. // Attempt to avoid DST problems.
  129. // @todo Resolve this properly at some point.
  130. if (strftime('%Y-%m-%d', $date) == $lastDate)
  131. $date += 3601;
  132. $lastDate = strftime('%Y-%m-%d', $date);
  133. // If we're using permissions (calendar pages?) then just ouput normal contextual style information.
  134. if ($use_permissions)
  135. $events[strftime('%Y-%m-%d', $date)][] = array(
  136. 'id' => $row['id_event'],
  137. 'title' => $row['title'],
  138. 'start_date' => $row['start_date'],
  139. 'end_date' => $row['end_date'],
  140. 'is_last' => false,
  141. 'id_board' => $row['id_board'],
  142. 'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
  143. 'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
  144. 'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
  145. 'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
  146. 'modify_href' => $scripturl . '?action=' . ($row['id_board'] == 0 ? 'calendar;sa=post;' : 'post;msg=' . $row['id_first_msg'] . ';topic=' . $row['id_topic'] . '.0;calendar;') . 'eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
  147. 'can_export' => !empty($modSettings['cal_export']) ? true : false,
  148. 'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
  149. );
  150. // Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
  151. else
  152. $events[strftime('%Y-%m-%d', $date)][] = array(
  153. 'id' => $row['id_event'],
  154. 'title' => $row['title'],
  155. 'start_date' => $row['start_date'],
  156. 'end_date' => $row['end_date'],
  157. 'is_last' => false,
  158. 'id_board' => $row['id_board'],
  159. 'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
  160. 'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
  161. 'link' => $row['id_topic'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
  162. 'can_edit' => false,
  163. 'can_export' => !empty($modSettings['cal_export']) ? true : false,
  164. 'topic' => $row['id_topic'],
  165. 'msg' => $row['id_first_msg'],
  166. 'poster' => $row['id_member'],
  167. 'allowed_groups' => explode(',', $row['member_groups']),
  168. );
  169. }
  170. }
  171. $smcFunc['db_free_result']($result);
  172. // If we're doing normal contextual data, go through and make things clear to the templates ;).
  173. if ($use_permissions)
  174. {
  175. foreach ($events as $mday => $array)
  176. $events[$mday][count($array) - 1]['is_last'] = true;
  177. }
  178. return $events;
  179. }
  180. /**
  181. * Get all holidays within the given time range.
  182. *
  183. * @param string $low_date YYYY-MM-DD
  184. * @param string $high_date YYYY-MM-DD
  185. * @return array an array of days, which are all arrays of holiday names.
  186. */
  187. function getHolidayRange($low_date, $high_date)
  188. {
  189. global $smcFunc;
  190. // Get the lowest and highest dates for "all years".
  191. if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
  192. $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
  193. OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
  194. else
  195. $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';
  196. // Find some holidays... ;).
  197. $result = $smcFunc['db_query']('', '
  198. SELECT event_date, YEAR(event_date) AS year, title
  199. FROM {db_prefix}calendar_holidays
  200. WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
  201. OR ' . $allyear_part,
  202. array(
  203. 'low_date' => $low_date,
  204. 'high_date' => $high_date,
  205. 'all_year_low' => '0004' . substr($low_date, 4),
  206. 'all_year_high' => '0004' . substr($high_date, 4),
  207. 'all_year_jan' => '0004-01-01',
  208. 'all_year_dec' => '0004-12-31',
  209. )
  210. );
  211. $holidays = array();
  212. while ($row = $smcFunc['db_fetch_assoc']($result))
  213. {
  214. if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
  215. $event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
  216. else
  217. $event_year = substr($low_date, 0, 4);
  218. $holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
  219. }
  220. $smcFunc['db_free_result']($result);
  221. return $holidays;
  222. }
  223. /**
  224. * Does permission checks to see if an event can be linked to a board/topic.
  225. * checks if the current user can link the current topic to the calendar, permissions et al.
  226. * this requires the calendar_post permission, a forum moderator, or a topic starter.
  227. * expects the $topic and $board variables to be set.
  228. * if the user doesn't have proper permissions, an error will be shown.
  229. */
  230. function canLinkEvent()
  231. {
  232. global $user_info, $topic, $board, $smcFunc;
  233. // If you can't post, you can't link.
  234. isAllowedTo('calendar_post');
  235. // No board? No topic?!?
  236. if (empty($board))
  237. fatal_lang_error('missing_board_id', false);
  238. if (empty($topic))
  239. fatal_lang_error('missing_topic_id', false);
  240. // Administrator, Moderator, or owner. Period.
  241. if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
  242. {
  243. // Not admin or a moderator of this board. You better be the owner - or else.
  244. $result = $smcFunc['db_query']('', '
  245. SELECT id_member_started
  246. FROM {db_prefix}topics
  247. WHERE id_topic = {int:current_topic}
  248. LIMIT 1',
  249. array(
  250. 'current_topic' => $topic,
  251. )
  252. );
  253. if ($row = $smcFunc['db_fetch_assoc']($result))
  254. {
  255. // Not the owner of the topic.
  256. if ($row['id_member_started'] != $user_info['id'])
  257. fatal_lang_error('not_your_topic', 'user');
  258. }
  259. // Topic/Board doesn't exist.....
  260. else
  261. fatal_lang_error('calendar_no_topic', 'general');
  262. $smcFunc['db_free_result']($result);
  263. }
  264. }
  265. /**
  266. * Returns date information about 'today' relative to the users time offset.
  267. * returns an array with the current date, day, month, and year.
  268. * takes the users time offset into account.
  269. */
  270. function getTodayInfo()
  271. {
  272. return array(
  273. 'day' => (int) strftime('%d', forum_time()),
  274. 'month' => (int) strftime('%m', forum_time()),
  275. 'year' => (int) strftime('%Y', forum_time()),
  276. 'date' => strftime('%Y-%m-%d', forum_time()),
  277. );
  278. }
  279. /**
  280. * Provides information (link, month, year) about the previous and next month.
  281. * @param int $month
  282. * @param int $year
  283. * @param array $calendarOptions
  284. * @param int $is_previous
  285. * @return array containing all the information needed to show a calendar grid for the given month
  286. */
  287. function getCalendarGrid($month, $year, $calendarOptions, $is_previous = false)
  288. {
  289. global $scripturl, $modSettings;
  290. // Eventually this is what we'll be returning.
  291. $calendarGrid = array(
  292. 'week_days' => array(),
  293. 'weeks' => array(),
  294. 'short_day_titles' => !empty($calendarOptions['short_day_titles']),
  295. 'short_month_titles' => !empty($calendarOptions['short_month_titles']),
  296. 'highlight' => array(
  297. 'events' => !empty($calendarOptions['highlight']['events']) && !empty($calendarOptions['show_events']) ? $calendarOptions['highlight']['events'] : 0,
  298. 'holidays' => !empty($calendarOptions['highlight']['holidays']) && !empty($calendarOptions['show_holidays']) ? $calendarOptions['highlight']['holidays'] : 0,
  299. 'birthdays' => !empty($calendarOptions['highlight']['birthdays']) && !empty($calendarOptions['show_birthdays']) ? $calendarOptions['highlight']['birthdays'] : 0,
  300. ),
  301. 'current_month' => $month,
  302. 'current_year' => $year,
  303. 'show_next_prev' => !empty($calendarOptions['show_next_prev']),
  304. 'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
  305. 'previous_calendar' => array(
  306. 'year' => $month == 1 ? $year - 1 : $year,
  307. 'month' => $month == 1 ? 12 : $month - 1,
  308. 'disabled' => $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
  309. ),
  310. 'next_calendar' => array(
  311. 'year' => $month == 12 ? $year + 1 : $year,
  312. 'month' => $month == 12 ? 1 : $month + 1,
  313. 'disabled' => $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
  314. ),
  315. 'size' => empty($modSettings['cal_display_type']) ? 'large' : 'small',
  316. );
  317. // Get today's date.
  318. $today = getTodayInfo();
  319. // Get information about this month.
  320. $month_info = array(
  321. 'first_day' => array(
  322. 'day_of_week' => (int) strftime('%w', mktime(0, 0, 0, $month, 1, $year)),
  323. 'week_num' => (int) strftime('%U', mktime(0, 0, 0, $month, 1, $year)),
  324. 'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month, 1, $year)),
  325. ),
  326. 'last_day' => array(
  327. 'day_of_month' => (int) strftime('%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
  328. 'date' => strftime('%Y-%m-%d', mktime(0, 0, 0, $month == 12 ? 1 : $month + 1, 0, $month == 12 ? $year + 1 : $year)),
  329. ),
  330. 'first_day_of_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year)),
  331. 'first_day_of_next_year' => (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1)),
  332. );
  333. // The number of days the first row is shifted to the right for the starting day.
  334. $nShift = $month_info['first_day']['day_of_week'];
  335. $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
  336. // Starting any day other than Sunday means a shift...
  337. if (!empty($calendarOptions['start_day']))
  338. {
  339. $nShift -= $calendarOptions['start_day'];
  340. if ($nShift < 0)
  341. $nShift = 7 + $nShift;
  342. }
  343. // Number of rows required to fit the month.
  344. $nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
  345. if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
  346. $nRows++;
  347. // Fetch the arrays for birthdays, posted events, and holidays.
  348. $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
  349. $events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
  350. $holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
  351. // Days of the week taking into consideration that they may want it to start on any day.
  352. $count = $calendarOptions['start_day'];
  353. for ($i = 0; $i < 7; $i++)
  354. {
  355. $calendarGrid['week_days'][] = $count;
  356. $count++;
  357. if ($count == 7)
  358. $count = 0;
  359. }
  360. // An adjustment value to apply to all calculated week numbers.
  361. if (!empty($calendarOptions['show_week_num']))
  362. {
  363. // If the first day of the year is a Sunday, then there is no
  364. // adjustment to be made. However, if the first day of the year is not
  365. // a Sunday, then there is a partial week at the start of the year
  366. // that needs to be accounted for.
  367. if ($calendarOptions['start_day'] === 0)
  368. $nWeekAdjust = $month_info['first_day_of_year'] === 0 ? 0 : 1;
  369. // If we are viewing the weeks, with a starting date other than Sunday,
  370. // then things get complicated! Basically, as PHP is calculating the
  371. // weeks with a Sunday starting date, we need to take this into account
  372. // and offset the whole year dependant on whether the first day in the
  373. // year is above or below our starting date. Note that we offset by
  374. // two, as some of this will get undone quite quickly by the statement
  375. // below.
  376. else
  377. $nWeekAdjust = $calendarOptions['start_day'] > $month_info['first_day_of_year'] && $month_info['first_day_of_year'] !== 0 ? 2 : 1;
  378. // If our week starts on a day greater than the day the month starts
  379. // on, then our week numbers will be one too high. So we need to
  380. // reduce it by one - all these thoughts of offsets makes my head
  381. // hurt...
  382. if ($month_info['first_day']['day_of_week'] < $calendarOptions['start_day'] || $month_info['first_day_of_year'] > 4)
  383. $nWeekAdjust--;
  384. }
  385. else
  386. $nWeekAdjust = 0;
  387. // Iterate through each week.
  388. $calendarGrid['weeks'] = array();
  389. for ($nRow = 0; $nRow < $nRows; $nRow++)
  390. {
  391. // Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
  392. $calendarGrid['weeks'][$nRow] = array(
  393. 'days' => array(),
  394. 'number' => $month_info['first_day']['week_num'] + $nRow + $nWeekAdjust
  395. );
  396. // Handle the dreaded "week 53", it can happen, but only once in a blue moon ;)
  397. if ($calendarGrid['weeks'][$nRow]['number'] == 53 && $nShift != 4 && $month_info['first_day_of_next_year'] < 4)
  398. $calendarGrid['weeks'][$nRow]['number'] = 1;
  399. // And figure out all the days.
  400. for ($nCol = 0; $nCol < 7; $nCol++)
  401. {
  402. $nDay = ($nRow * 7) + $nCol - $nShift + 1;
  403. if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
  404. $nDay = 0;
  405. $date = sprintf('%04d-%02d-%02d', $year, $month, $nDay);
  406. $calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
  407. 'day' => $nDay,
  408. 'date' => $date,
  409. 'is_today' => $date == $today['date'],
  410. 'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
  411. 'is_first_of_month' => $nDay === 1,
  412. 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
  413. 'events' => !empty($events[$date]) ? $events[$date] : array(),
  414. 'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
  415. );
  416. }
  417. }
  418. // What is the last day of the month?
  419. if ($is_previous === true)
  420. $calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];
  421. // We'll use the shift in the template.
  422. $calendarGrid['shift'] = $nShift;
  423. // Set the previous and the next month's links.
  424. $calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'];
  425. $calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'];
  426. return $calendarGrid;
  427. }
  428. /**
  429. * Returns the information needed to show a calendar for the given week.
  430. * @param int $month
  431. * @param int $year
  432. * @param int $day
  433. * @param array $calendarOptions
  434. * @return array
  435. */
  436. function getCalendarWeek($month, $year, $day, $calendarOptions)
  437. {
  438. global $scripturl, $modSettings;
  439. // Get today's date.
  440. $today = getTodayInfo();
  441. // What is the actual "start date" for the passed day.
  442. $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
  443. $day_of_week = (int) strftime('%w', mktime(0, 0, 0, $month, $day, $year));
  444. if ($day_of_week != $calendarOptions['start_day'])
  445. {
  446. // Here we offset accordingly to get things to the real start of a week.
  447. $date_diff = $day_of_week - $calendarOptions['start_day'];
  448. if ($date_diff < 0)
  449. $date_diff += 7;
  450. $new_timestamp = mktime(0, 0, 0, $month, $day, $year) - $date_diff * 86400;
  451. $day = (int) strftime('%d', $new_timestamp);
  452. $month = (int) strftime('%m', $new_timestamp);
  453. $year = (int) strftime('%Y', $new_timestamp);
  454. }
  455. // Now start filling in the calendar grid.
  456. $calendarGrid = array(
  457. 'show_next_prev' => !empty($calendarOptions['show_next_prev']),
  458. // Previous week is easy - just step back one day.
  459. 'previous_week' => array(
  460. 'year' => $day == 1 ? ($month == 1 ? $year - 1 : $year) : $year,
  461. 'month' => $day == 1 ? ($month == 1 ? 12 : $month - 1) : $month,
  462. 'day' => $day == 1 ? 28 : $day - 1,
  463. 'disabled' => $day < 7 && $modSettings['cal_minyear'] > ($month == 1 ? $year - 1 : $year),
  464. ),
  465. 'next_week' => array(
  466. 'disabled' => $day > 25 && $modSettings['cal_maxyear'] < ($month == 12 ? $year + 1 : $year),
  467. ),
  468. 'size' => empty($modSettings['cal_display_type']) ? 'large' : 'small',
  469. );
  470. // The next week calculation requires a bit more work.
  471. $curTimestamp = mktime(0, 0, 0, $month, $day, $year);
  472. $nextWeekTimestamp = $curTimestamp + 604800;
  473. $calendarGrid['next_week']['day'] = (int) strftime('%d', $nextWeekTimestamp);
  474. $calendarGrid['next_week']['month'] = (int) strftime('%m', $nextWeekTimestamp);
  475. $calendarGrid['next_week']['year'] = (int) strftime('%Y', $nextWeekTimestamp);
  476. // Fetch the arrays for birthdays, posted events, and holidays.
  477. $startDate = strftime('%Y-%m-%d', $curTimestamp);
  478. $endDate = strftime('%Y-%m-%d', $nextWeekTimestamp);
  479. $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($startDate, $endDate) : array();
  480. $events = $calendarOptions['show_events'] ? getEventRange($startDate, $endDate) : array();
  481. $holidays = $calendarOptions['show_holidays'] ? getHolidayRange($startDate, $endDate) : array();
  482. // An adjustment value to apply to all calculated week numbers.
  483. if (!empty($calendarOptions['show_week_num']))
  484. {
  485. $first_day_of_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year));
  486. $first_day_of_next_year = (int) strftime('%w', mktime(0, 0, 0, 1, 1, $year + 1));
  487. $last_day_of_last_year = (int) strftime('%w', mktime(0, 0, 0, 12, 31, $year - 1));
  488. // All this is as getCalendarGrid.
  489. if ($calendarOptions['start_day'] === 0)
  490. $nWeekAdjust = $first_day_of_year === 0 && $first_day_of_year > 3 ? 0 : 1;
  491. else
  492. $nWeekAdjust = $calendarOptions['start_day'] > $first_day_of_year && $first_day_of_year !== 0 ? 2 : 1;
  493. $calendarGrid['week_number'] = (int) strftime('%U', mktime(0, 0, 0, $month, $day, $year)) + $nWeekAdjust;
  494. // If this crosses a year boundry and includes january it should be week one.
  495. if ((int) strftime('%Y', $curTimestamp + 518400) != $year && $calendarGrid['week_number'] > 53 && $first_day_of_next_year < 5)
  496. $calendarGrid['week_number'] = 1;
  497. }
  498. // This holds all the main data - there is at least one month!
  499. $calendarGrid['months'] = array();
  500. $lastDay = 99;
  501. $curDay = $day;
  502. $curDayOfWeek = $calendarOptions['start_day'];
  503. for ($i = 0; $i < 7; $i++)
  504. {
  505. // Have we gone into a new month (Always happens first cycle too)
  506. if ($lastDay > $curDay)
  507. {
  508. $curMonth = $lastDay == 99 ? $month : ($month == 12 ? 1 : $month + 1);
  509. $curYear = $lastDay == 99 ? $year : ($curMonth == 1 && $month == 12 ? $year + 1 : $year);
  510. $calendarGrid['months'][$curMonth] = array(
  511. 'current_month' => $curMonth,
  512. 'current_year' => $curYear,
  513. 'days' => array(),
  514. );
  515. }
  516. // Add todays information to the pile!
  517. $date = sprintf('%04d-%02d-%02d', $curYear, $curMonth, $curDay);
  518. $calendarGrid['months'][$curMonth]['days'][$curDay] = array(
  519. 'day' => $curDay,
  520. 'day_of_week' => $curDayOfWeek,
  521. 'date' => $date,
  522. 'is_today' => $date == $today['date'],
  523. 'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
  524. 'events' => !empty($events[$date]) ? $events[$date] : array(),
  525. 'birthdays' => !empty($bday[$date]) ? $bday[$date] : array()
  526. );
  527. // Make the last day what the current day is and work out what the next day is.
  528. $lastDay = $curDay;
  529. $curTimestamp += 86400;
  530. $curDay = (int) strftime('%d', $curTimestamp);
  531. // Also increment the current day of the week.
  532. $curDayOfWeek = $curDayOfWeek >= 6 ? 0 : ++$curDayOfWeek;
  533. }
  534. // Set the previous and the next week's links.
  535. $calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
  536. $calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];
  537. return $calendarGrid;
  538. }
  539. /**
  540. * Retrieve all events for the given days, independently of the users offset.
  541. * cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
  542. * widens the search range by an extra 24 hours to support time offset shifts.
  543. * used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
  544. *
  545. * @param int $days_to_index
  546. * @return array
  547. */
  548. function cache_getOffsetIndependentEvents($days_to_index)
  549. {
  550. $low_date = strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
  551. $high_date = strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);
  552. return array(
  553. 'data' => array(
  554. 'holidays' => getHolidayRange($low_date, $high_date),
  555. 'birthdays' => getBirthdayRange($low_date, $high_date),
  556. 'events' => getEventRange($low_date, $high_date, false),
  557. ),
  558. 'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
  559. 'expires' => time() + 3600,
  560. );
  561. }
  562. /**
  563. * cache callback function used to retrieve the upcoming birthdays, holidays, and events within the given period, taking into account the users time offset.
  564. * Called from the BoardIndex to display the current day's events on the board index
  565. * used by the board index and SSI to show the upcoming events.
  566. * @param array $eventOptions
  567. * @return array
  568. */
  569. function cache_getRecentEvents($eventOptions)
  570. {
  571. // With the 'static' cached data we can calculate the user-specific data.
  572. $cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions['num_days_shown']));
  573. // Get the information about today (from user perspective).
  574. $today = getTodayInfo();
  575. $return_data = array(
  576. 'calendar_holidays' => array(),
  577. 'calendar_birthdays' => array(),
  578. 'calendar_events' => array(),
  579. );
  580. // Set the event span to be shown in seconds.
  581. $days_for_index = $eventOptions['num_days_shown'] * 86400;
  582. // Get the current member time/date.
  583. $now = forum_time();
  584. // Holidays between now and now + days.
  585. for ($i = $now; $i < $now + $days_for_index; $i += 86400)
  586. {
  587. if (isset($cached_data['holidays'][strftime('%Y-%m-%d', $i)]))
  588. $return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][strftime('%Y-%m-%d', $i)]);
  589. }
  590. // Happy Birthday, guys and gals!
  591. for ($i = $now; $i < $now + $days_for_index; $i += 86400)
  592. {
  593. $loop_date = strftime('%Y-%m-%d', $i);
  594. if (isset($cached_data['birthdays'][$loop_date]))
  595. {
  596. foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
  597. $cached_data['birthdays'][strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
  598. $return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
  599. }
  600. }
  601. $duplicates = array();
  602. for ($i = $now; $i < $now + $days_for_index; $i += 86400)
  603. {
  604. // Determine the date of the current loop step.
  605. $loop_date = strftime('%Y-%m-%d', $i);
  606. // No events today? Check the next day.
  607. if (empty($cached_data['events'][$loop_date]))
  608. continue;
  609. // Loop through all events to add a few last-minute values.
  610. foreach ($cached_data['events'][$loop_date] as $ev => $event)
  611. {
  612. // Create a shortcut variable for easier access.
  613. $this_event = &$cached_data['events'][$loop_date][$ev];
  614. // Skip duplicates.
  615. if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
  616. {
  617. unset($cached_data['events'][$loop_date][$ev]);
  618. continue;
  619. }
  620. else
  621. $duplicates[$this_event['topic'] . $this_event['title']] = true;
  622. // Might be set to true afterwards, depending on the permissions.
  623. $this_event['can_edit'] = false;
  624. $this_event['is_today'] = $loop_date === $today['date'];
  625. $this_event['date'] = $loop_date;
  626. }
  627. if (!empty($cached_data['events'][$loop_date]))
  628. $return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
  629. }
  630. // Mark the last item so that a list separator can be used in the template.
  631. for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
  632. $return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
  633. for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
  634. $return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);
  635. return array(
  636. 'data' => $return_data,
  637. 'expires' => time() + 3600,
  638. 'refresh_eval' => 'return \'' . strftime('%Y%m%d', forum_time(false)) . '\' != strftime(\'%Y%m%d\', forum_time(false)) || (!empty($modSettings[\'calendar_updated\']) && ' . time() . ' < $modSettings[\'calendar_updated\']);',
  639. 'post_retri_eval' => '
  640. global $context, $scripturl, $user_info;
  641. foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
  642. {
  643. // Remove events that the user may not see or wants to ignore.
  644. if ((count(array_intersect($user_info[\'groups\'], $event[\'allowed_groups\'])) === 0 && !allowedTo(\'admin_forum\') && !empty($event[\'id_board\'])) || in_array($event[\'id_board\'], $user_info[\'ignoreboards\']))
  645. unset($cache_block[\'data\'][\'calendar_events\'][$k]);
  646. else
  647. {
  648. // Whether the event can be edited depends on the permissions.
  649. $cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));
  650. // The added session code makes this URL not cachable.
  651. $cache_block[\'data\'][\'calendar_events\'][$k][\'modify_href\'] = $scripturl . \'?action=\' . ($event[\'topic\'] == 0 ? \'calendar;sa=post;\' : \'post;msg=\' . $event[\'msg\'] . \';topic=\' . $event[\'topic\'] . \'.0;calendar;\') . \'eventid=\' . $event[\'id\'] . \';\' . $context[\'session_var\'] . \'=\' . $context[\'session_id\'];
  652. }
  653. }
  654. if (empty($params[0][\'include_holidays\']))
  655. $cache_block[\'data\'][\'calendar_holidays\'] = array();
  656. if (empty($params[0][\'include_birthdays\']))
  657. $cache_block[\'data\'][\'calendar_birthdays\'] = array();
  658. if (empty($params[0][\'include_events\']))
  659. $cache_block[\'data\'][\'calendar_events\'] = array();
  660. $cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
  661. );
  662. }
  663. /**
  664. * Makes sure the calendar post is valid.
  665. */
  666. function validateEventPost()
  667. {
  668. global $modSettings, $smcFunc;
  669. if (!isset($_POST['deleteevent']))
  670. {
  671. // No month? No year?
  672. if (!isset($_POST['month']))
  673. fatal_lang_error('event_month_missing', false);
  674. if (!isset($_POST['year']))
  675. fatal_lang_error('event_year_missing', false);
  676. // Check the month and year...
  677. if ($_POST['month'] < 1 || $_POST['month'] > 12)
  678. fatal_lang_error('invalid_month', false);
  679. if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
  680. fatal_lang_error('invalid_year', false);
  681. }
  682. // Make sure they're allowed to post...
  683. isAllowedTo('calendar_post');
  684. if (isset($_POST['span']))
  685. {
  686. // Make sure it's turned on and not some fool trying to trick it.
  687. if (empty($modSettings['cal_allowspan']))
  688. fatal_lang_error('no_span', false);
  689. if ($_POST['span'] < 1 || $_POST['span'] > $modSettings['cal_maxspan'])
  690. fatal_lang_error('invalid_days_numb', false);
  691. }
  692. // There is no need to validate the following values if we are just deleting the event.
  693. if (!isset($_POST['deleteevent']))
  694. {
  695. // No day?
  696. if (!isset($_POST['day']))
  697. fatal_lang_error('event_day_missing', false);
  698. if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
  699. fatal_lang_error('event_title_missing', false);
  700. elseif (!isset($_POST['evtitle']))
  701. $_POST['evtitle'] = $_POST['subject'];
  702. // Bad day?
  703. if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
  704. fatal_lang_error('invalid_date', false);
  705. // No title?
  706. if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
  707. fatal_lang_error('no_event_title', false);
  708. if ($smcFunc['strlen']($_POST['evtitle']) > 100)
  709. $_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 100);
  710. $_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
  711. }
  712. }
  713. /**
  714. * Get the event's poster.
  715. *
  716. * @param int $event_id
  717. * @return int|bool the id of the poster or false if the event was not found
  718. */
  719. function getEventPoster($event_id)
  720. {
  721. global $smcFunc;
  722. // A simple database query, how hard can that be?
  723. $request = $smcFunc['db_query']('', '
  724. SELECT id_member
  725. FROM {db_prefix}calendar
  726. WHERE id_event = {int:id_event}
  727. LIMIT 1',
  728. array(
  729. 'id_event' => $event_id,
  730. )
  731. );
  732. // No results, return false.
  733. if ($smcFunc['db_num_rows'] === 0)
  734. return false;
  735. // Grab the results and return.
  736. list ($poster) = $smcFunc['db_fetch_row']($request);
  737. $smcFunc['db_free_result']($request);
  738. return (int) $poster;
  739. }
  740. /**
  741. * Consolidating the various INSERT statements into this function.
  742. * inserts the passed event information into the calendar table.
  743. * allows to either set a time span (in days) or an end_date.
  744. * does not check any permissions of any sort.
  745. *
  746. * @param array $eventOptions
  747. */
  748. function insertEvent(&$eventOptions)
  749. {
  750. global $smcFunc;
  751. // Add special chars to the title.
  752. $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
  753. // Add some sanity checking to the span.
  754. $eventOptions['span'] = isset($eventOptions['span']) && $eventOptions['span'] > 0 ? (int) $eventOptions['span'] : 0;
  755. // Make sure the start date is in ISO order.
  756. // @todo $year, $month, and $day are not set
  757. if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
  758. trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);
  759. // Set the end date (if not yet given)
  760. // @todo $year, $month, and $day are not set
  761. if (!isset($eventOptions['end_date']))
  762. $eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
  763. // If no topic and board are given, they are not linked to a topic.
  764. $eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
  765. $eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;
  766. $event_columns = array(
  767. 'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
  768. 'start_date' => 'date', 'end_date' => 'date',
  769. );
  770. $event_parameters = array(
  771. $eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
  772. $eventOptions['start_date'], $eventOptions['end_date'],
  773. );
  774. call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));
  775. // Insert the event!
  776. $smcFunc['db_insert']('',
  777. '{db_prefix}calendar',
  778. $event_columns,
  779. $event_parameters,
  780. array('id_event')
  781. );
  782. // Store the just inserted id_event for future reference.
  783. $eventOptions['id'] = $smcFunc['db_insert_id']('{db_prefix}calendar', 'id_event');
  784. // If this isn't tied to a topic, we need to notify people about it.
  785. if (empty($eventOptions['topic']))
  786. {
  787. $smcFunc['db_insert']('insert',
  788. '{db_prefix}background_tasks',
  789. array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
  790. array('$sourcedir/tasks/EventNew-Notify.php', 'EventNew_Notify_Background', serialize(array(
  791. 'event_title' => $eventOptions['title'],
  792. 'event_id' => $eventOptions['id'],
  793. 'sender_id' => $eventOptions['member'],
  794. 'sender_name' => $eventOptions['member'] == $context['user']['id'] ? $context['user']['name'] : '',
  795. 'time' => time(),
  796. )), 0),
  797. array('id_task')
  798. );
  799. }
  800. // Update the settings to show something calendar-ish was updated.
  801. updateSettings(array(
  802. 'calendar_updated' => time(),
  803. ));
  804. }
  805. /**
  806. * modifies an event.
  807. * allows to either set a time span (in days) or an end_date.
  808. * does not check any permissions of any sort.
  809. *
  810. * @param int $event_id
  811. * @param array $eventOptions
  812. */
  813. function modifyEvent($event_id, &$eventOptions)
  814. {
  815. global $smcFunc;
  816. // Properly sanitize the title.
  817. $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
  818. // Scan the start date for validity and get its components.
  819. if (($num_results = sscanf($eventOptions['start_date'], '%d-%d-%d', $year, $month, $day)) !== 3)
  820. trigger_error('modifyEvent(): invalid start date format given', E_USER_ERROR);
  821. // Default span to 0 days.
  822. $eventOptions['span'] = isset($eventOptions['span']) ? (int) $eventOptions['span'] : 0;
  823. // Set the end date to the start date + span (if the end date wasn't already given).
  824. if (!isset($eventOptions['end_date']))
  825. $eventOptions['end_date'] = strftime('%Y-%m-%d', mktime(0, 0, 0, $month, $day, $year) + $eventOptions['span'] * 86400);
  826. $event_columns = array(
  827. 'start_date' => '{date:start_date}',
  828. 'end_date' => '{date:end_date}',
  829. 'title' => 'SUBSTRING({string:title}, 1, 60)',
  830. 'id_board' => '{int:id_board}',
  831. 'id_topic' => '{int:id_topic}'
  832. );
  833. $event_parameters = array(
  834. 'start_date' => $eventOptions['start_date'],
  835. 'end_date' => $eventOptions['end_date'],
  836. 'title' => $eventOptions['title'],
  837. 'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
  838. 'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
  839. );
  840. // This is to prevent hooks to modify the id of the event
  841. $real_event_id = $event_id;
  842. call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns, &$event_parameters));
  843. $column_clauses = array();
  844. foreach ($event_columns as $col => $crit)
  845. $column_clauses[] = $col . ' = ' . $crit;
  846. $smcFunc['db_query']('', '
  847. UPDATE {db_prefix}calendar
  848. SET
  849. ' . implode(', ', $column_clauses) . '
  850. WHERE id_event = {int:id_event}',
  851. array_merge(
  852. $event_parameters,
  853. array(
  854. 'id_event' => $real_event_id
  855. )
  856. )
  857. );
  858. updateSettings(array(
  859. 'calendar_updated' => time(),
  860. ));
  861. }
  862. /**
  863. * Remove an event
  864. * removes an event.
  865. * does no permission checks.
  866. *
  867. * @param int $event_id
  868. */
  869. function removeEvent($event_id)
  870. {
  871. global $smcFunc;
  872. $smcFunc['db_query']('', '
  873. DELETE FROM {db_prefix}calendar
  874. WHERE id_event = {int:id_event}',
  875. array(
  876. 'id_event' => $event_id,
  877. )
  878. );
  879. call_integration_hook('integrate_remove_event', array($event_id));
  880. updateSettings(array(
  881. 'calendar_updated' => time(),
  882. ));
  883. }
  884. /**
  885. * Gets all the events properties
  886. *
  887. * @param int $event_id
  888. * @return array
  889. */
  890. function getEventProperties($event_id)
  891. {
  892. global $smcFunc;
  893. $request = $smcFunc['db_query']('', '
  894. SELECT
  895. c.id_event, c.id_board, c.id_topic, MONTH(c.start_date) AS month,
  896. DAYOFMONTH(c.start_date) AS day, YEAR(c.start_date) AS year,
  897. (TO_DAYS(c.end_date) - TO_DAYS(c.start_date)) AS span, c.id_member, c.title,
  898. t.id_first_msg, t.id_member_started,
  899. mb.real_name, m.modified_time
  900. FROM {db_prefix}calendar AS c
  901. LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
  902. LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
  903. LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
  904. WHERE c.id_event = {int:id_event}',
  905. array(
  906. 'id_event' => $event_id,
  907. )
  908. );
  909. // If nothing returned, we are in poo, poo.
  910. if ($smcFunc['db_num_rows']($request) === 0)
  911. return false;
  912. $row = $smcFunc['db_fetch_assoc']($request);
  913. $smcFunc['db_free_result']($request);
  914. $return_value = array(
  915. 'boards' => array(),
  916. 'board' => $row['id_board'],
  917. 'new' => 0,
  918. 'eventid' => $event_id,
  919. 'year' => $row['year'],
  920. 'month' => $row['month'],
  921. 'day' => $row['day'],
  922. 'title' => $row['title'],
  923. 'span' => 1 + $row['span'],
  924. 'member' => $row['id_member'],
  925. 'realname' => $row['real_name'],
  926. 'sequence' => $row['modified_time'],
  927. 'topic' => array(
  928. 'id' => $row['id_topic'],
  929. 'member_started' => $row['id_member_started'],
  930. 'first_msg' => $row['id_first_msg'],
  931. ),
  932. );
  933. $return_value['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $return_value['month'] == 12 ? 1 : $return_value['month'] + 1, 0, $return_value['month'] == 12 ? $return_value['year'] + 1 : $return_value['year']));
  934. return $return_value;
  935. }
  936. /**
  937. * Gets all of the holidays for the listing
  938. *
  939. * @param int $start
  940. * @param int $items_per_page
  941. * @param string $sort
  942. * @return array
  943. */
  944. function list_getHolidays($start, $items_per_page, $sort)
  945. {
  946. global $smcFunc;
  947. $request = $smcFunc['db_query']('', '
  948. SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
  949. FROM {db_prefix}calendar_holidays
  950. ORDER BY {raw:sort}
  951. LIMIT ' . $start . ', ' . $items_per_page,
  952. array(
  953. 'sort' => $sort,
  954. )
  955. );
  956. $holidays = array();
  957. while ($row = $smcFunc['db_fetch_assoc']($request))
  958. $holidays[] = $row;
  959. $smcFunc['db_free_result']($request);
  960. return $holidays;
  961. }
  962. /**
  963. * Helper function to get the total number of holidays
  964. *
  965. * @return int
  966. */
  967. function list_getNumHolidays()
  968. {
  969. global $smcFunc;
  970. $request = $smcFunc['db_query']('', '
  971. SELECT COUNT(*)
  972. FROM {db_prefix}calendar_holidays',
  973. array(
  974. )
  975. );
  976. list($num_items) = $smcFunc['db_fetch_row']($request);
  977. $smcFunc['db_free_result']($request);
  978. return (int) $num_items;
  979. }
  980. /**
  981. * Remove a holdiay from the calendar
  982. *
  983. * @param array $holiday_ids An array of
  984. */
  985. function removeHolidays($holiday_ids)
  986. {
  987. global $smcFunc;
  988. $smcFunc['db_query']('', '
  989. DELETE FROM {db_prefix}calendar_holidays
  990. WHERE id_holiday IN ({array_int:id_holiday})',
  991. array(
  992. 'id_holiday' => $holiday_ids,
  993. )
  994. );
  995. updateSettings(array(
  996. 'calendar_updated' => time(),
  997. ));
  998. }
  999. ?>