Overview

Namespaces

  • MatthiasMullie
    • Minify
      • Exceptions
    • PathConverter
  • None
  • ReCaptcha
    • RequestMethod
  • TOTP

Classes

  • apc_cache
  • apcu_cache
  • ApprovePost_Notify_Background
  • ApproveReply_Notify_Background
  • Attachments
  • Birthday_Notify_Background
  • browser_detector
  • Buddy_Notify_Background
  • cache_api
  • CreateAttachment_Notify_Background
  • CreatePost_Notify_Background
  • curl_fetch_web_data
  • custom_search
  • EventNew_Notify_Background
  • ftp_connection
  • fulltext_search
  • gif_color_table
  • gif_file
  • gif_file_header
  • gif_image
  • gif_image_header
  • gif_lzw_compression
  • GroupAct_Notify_Background
  • GroupReq_Notify_Background
  • Likes
  • Likes_Notify_Background
  • MatthiasMullie\Minify\CSS
  • MatthiasMullie\Minify\JS
  • MatthiasMullie\Minify\Minify
  • MatthiasMullie\PathConverter\Converter
  • MemberReport_Notify_Background
  • MemberReportReply_Notify_Background
  • memcache_cache
  • memcached_cache
  • Mentions
  • MsgReport_Notify_Background
  • MsgReportReply_Notify_Background
  • paypal_display
  • paypal_payment
  • postgres_cache
  • ProxyServer
  • Punycode
  • ReCaptcha\ReCaptcha
  • ReCaptcha\RequestMethod\Curl
  • ReCaptcha\RequestMethod\CurlPost
  • ReCaptcha\RequestMethod\Post
  • ReCaptcha\RequestMethod\Socket
  • ReCaptcha\RequestMethod\SocketPost
  • ReCaptcha\RequestParameters
  • ReCaptcha\Response
  • Register_Notify_Background
  • search_api
  • SMF_BackgroundTask
  • smf_cache
  • sqlite_cache
  • standard_search
  • TOTP\Auth
  • TypeError
  • Update_TLD_Regex
  • xcache_cache
  • xmlArray
  • zend_cache

Interfaces

  • cache_api_interface
  • ReCaptcha\RequestMethod
  • search_api_interface

Exceptions

  • Error
  • MatthiasMullie\Minify\Exception
  • MatthiasMullie\Minify\Exceptions\BasicException
  • MatthiasMullie\Minify\Exceptions\FileImportException
  • MatthiasMullie\Minify\Exceptions\IOException

Functions

  • _safe_serialize
  • _safe_unserialize
  • account
  • Activate
  • activateAccount
  • add_integration_function
  • addData
  • addInlineCss
  • addInlineJavaScript
  • addJavaScriptVar
  • AddLanguage
  • AddMailQueue
  • AddMembergroup
  • addMembersToGroup
  • addSeparator
  • AddSmiley
  • addSubscription
  • addTriggers
  • AdminAccount
  • AdminApprove
  • AdminBoardRecount
  • AdminEndSession
  • AdminHome
  • adminLogin
  • adminLogin_outputPostVars
  • AdminLogs
  • AdminMain
  • adminNotify
  • AdminRegister
  • AdminSearch
  • AdminSearchInternal
  • AdminSearchMember
  • AdminSearchOM
  • alert_configuration
  • alert_count
  • alert_delete
  • alert_mark
  • alert_markread
  • alert_notifications_boards
  • alert_notifications_topics
  • alert_purge
  • alerts_popup
  • AlignURLsWithSSLSetting
  • allowedTo
  • AnnouncementSelectMembergroup
  • AnnouncementSend
  • AnnounceTopic
  • ApplyRules
  • approveAllData
  • ApproveAttach
  • ApproveAttachments
  • ApproveMessage
  • approveMessages
  • approvePosts
  • approveTopics
  • array_column
  • array_length
  • assignAttachments
  • attachDirStatus
  • attachmentChecks
  • attachments_init_dir
  • automanage_attachments_by_space
  • automanage_attachments_check_directory
  • automanage_attachments_create_directory
  • AutoSuggest_Search_Member
  • AutoSuggest_Search_MemberGroups
  • AutoSuggest_Search_SMFVersions
  • AutoSuggestHandler
  • AutoTask
  • BackupDatabase
  • backupTable
  • Ban
  • BanBrowseTriggers
  • BanEdit
  • banEdit2
  • BanEditTrigger
  • BanList
  • banLoadAdditionalIPs
  • banLoadAdditionalIPsError
  • banLoadAdditionalIPsMember
  • BanLog
  • banPermissions
  • bbc_to_html
  • BoardIndex
  • BoardNotify
  • BoardPermissionsReport
  • BoardReport
  • boardsAllowedTo
  • BoardurlMatch
  • BookOfUnknown
  • BrowseFiles
  • BrowseMailQueue
  • BuddyListToggle
  • build_query_board
  • build_regex
  • buildEventDatetimes
  • cache_get_data
  • cache_getLastPosts
  • cache_getMembergroupList
  • cache_getOffsetIndependentEvents
  • cache_getRecentEvents
  • cache_put_data
  • cache_quick_get
  • CalculateNextTrigger
  • CalendarMain
  • CalendarPost
  • call_helper
  • call_integration_hook
  • canLinkEvent
  • canPickTheme
  • cdata_parse
  • censorText
  • check_cron
  • checkActivation
  • checkChange
  • checkConfirm
  • checkExistingTriggerIP
  • CheckFilesWritable
  • checkGD
  • checkImageContents
  • checkImagick
  • checkLogin
  • checkMagickWand
  • checkSession
  • checkSubmitOnce
  • clean_cache
  • cleanLangString
  • cleanRequest
  • cleanRequest_cron
  • cleanTokens
  • cleanXml
  • ClearMailQueue
  • cli_scheduled_fetchSMfiles
  • clock
  • cmdStep0
  • comma_format
  • compareVersions
  • ComposeMailing
  • consolidateSpiderStats
  • construct_query_string
  • constructPageIndex
  • ConvertEntities
  • ConvertMsgBody
  • convertSettingstoOptions
  • convertSettingsToTheme
  • ConvertUtf8
  • CoppaForm
  • CopyTemplate
  • copytree
  • countReports
  • create_button
  • create_chmod_control
  • create_control_richedit
  • create_control_verification
  • createAttachment
  • createBoard
  • createCategory
  • createList
  • createMenu
  • CreateMessageIndex
  • createPost
  • createSalvageArea
  • createThumbnail
  • createToken
  • createWaveFile
  • Credits
  • custFieldsMaxOrder
  • custMinify
  • DatabaseChanges
  • DatabasePopulation
  • DatabaseSettings
  • db_extend
  • db_extra_init
  • db_fix_prefix
  • db_packages_init
  • db_search_init
  • db_version_check
  • debugPrint
  • deleteAccount
  • deleteAccount2
  • deleteAllMinified
  • deleteBoards
  • deleteCategories
  • DeleteDraft
  • deleteErrors
  • DeleteInstall
  • DeleteMembergroup
  • deleteMembergroups
  • deleteMembers
  • DeleteMessage
  • deleteMessages
  • deleteModComment
  • deleteNotifyPrefs
  • DeleteUpgrade
  • deltree
  • Destroy
  • destroyMenu
  • detectBrowser
  • detectFulltextIndex
  • determineActions
  • Display
  • display_db_error
  • display_loadavg_error
  • display_maintenance_message
  • DisplayAdminFile
  • displayDebug
  • DisplayStats
  • DoLogin
  • Download
  • downloadAvatar
  • DownloadLanguage
  • dumpTags
  • EditAgreement
  • EditBoard
  • EditBoard2
  • EditBoardSettings
  • editBuddies
  • editBuddyIgnoreLists
  • EditCategory
  • EditCategory2
  • EditComment
  • EditCustomProfiles
  • EditHoliday
  • editIgnoreList
  • EditMembergroup
  • EditMessageIcons
  • editModComment
  • EditNews
  • EditPermissionProfiles
  • EditPoll
  • EditPoll2
  • EditSearchMethod
  • EditSearchSettings
  • EditSmileyOrder
  • EditSmileys
  • EditSmileySets
  • EditSmileySettings
  • EditSpider
  • EditTask
  • EditTheme
  • EditWeights
  • emailAdmins
  • EnableTheme
  • entity_fix__callback
  • escapestring__recursive
  • ExamineFile
  • expandIPv6
  • fatal_error
  • fatal_lang_error
  • fetch_alerts
  • fetch_task
  • fetch_web_data
  • fetchPerms__recursive
  • fetchTagAttributes
  • find_gpg
  • find_signed_off
  • find_signed_off_parents
  • findForumErrors
  • findMembers
  • findSearchAPI
  • finishTables
  • fix_possible_url
  • fix_serialized_data
  • fixchar__callback
  • fixchardb__callback
  • fixChildren
  • fixModSecurity
  • fixRelativePath
  • fixTag
  • fixTags
  • forum_time
  • forumProfile
  • ForumSettings
  • frameOptionsHeader
  • GeneralPermissionSettings
  • generateSubscriptionError
  • generateValidationCode
  • get_all_themes
  • get_current_settings
  • get_date_or_time_format
  • get_directory_tree_elements
  • get_file_listing
  • get_files_recursive
  • get_gravatar_url
  • get_hook_info_from_raw
  • get_installed_themes
  • get_integration_hooks
  • get_integration_hooks_count
  • get_integration_hooks_data
  • get_proxied_url
  • get_single_theme
  • get_theme_info
  • getAttachmentFilename
  • getAttachMsgInfo
  • getAvatars
  • getBirthdayRange
  • getBoardIndex
  • getBoardList
  • getBoardModeratorGroups
  • getBoardModerators
  • getBoardParents
  • getBoardTree
  • getCalendarGrid
  • getCalendarList
  • getCalendarWeek
  • getCommentModDetails
  • getCustFieldsMList
  • getDailyStats
  • getEventPoster
  • getEventProperties
  • getEventRange
  • getFileVersions
  • getHolidayRange
  • GetJumpTo
  • getLanguages
  • getLastPost
  • getLastPosts
  • GetMemberActivationCounts
  • getMemberData
  • getMemberGroups
  • getMembersOnlineStats
  • getMessageIcons
  • getMsgMemberID
  • getNewEventDatetimes
  • getNotifyPrefs
  • getPackageInfo
  • getRawAttachInfo
  • getReportComments
  • getReportDetails
  • getReports
  • getServerVersions
  • getTodayInfo
  • getTopic
  • getTreeOrder
  • getUserTimezone
  • getXmlMembers
  • getXmlNews
  • getXmlProfile
  • getXmlRecent
  • gif_outputAsPng
  • GroupList
  • groupMembership
  • groupMembership2
  • GroupPermissionsReport
  • GroupRequests
  • Groups
  • groupsAllowedTo
  • HandleComment
  • HandleReport
  • hash_benchmark
  • hash_length
  • hash_password
  • hash_salt
  • hash_verify_password
  • HelpIndex
  • HelpRules
  • highlight
  • highlight_php_code
  • host_from_ip
  • html_to_bbc
  • htmlspecialchars__recursive
  • htmltrim__recursive
  • https_redirect_active
  • httpsOn
  • iCalDownload
  • ignoreboards
  • imagecopyresamplebicubic
  • imagecreatefrombmp
  • imageMemoryCheck
  • ImportSmileys
  • inet_dtop
  • inet_ptod
  • initialize_inputs
  • InMaintenance
  • insertBanGroup
  • insertEvent
  • InstallCopy
  • InstallDir
  • installer_updateSettingsFile
  • installExit
  • InstallFile
  • InstallSmileySet
  • ip2range
  • iri_to_url
  • is_not_banned
  • is_not_guest
  • isAccessiblePM
  • isAllowedTo
  • isBannedEmail
  • isBrowser
  • isChildOf
  • isReservedName
  • issueWarning
  • isValidIP
  • isValidIPv6
  • JavaScriptEscape
  • JavaScriptModify
  • jeffsdatediff
  • JSMembers
  • KickGuest
  • legalise_bbc
  • list_getAttachDirs
  • list_getAttachments
  • list_getBanItems
  • list_getBanLogEntries
  • list_getBans
  • list_getBanTriggers
  • list_getBaseDirs
  • list_getBoardNotifications
  • list_getFiles
  • list_getGroupRequestCount
  • list_getGroupRequests
  • list_getGroupRequestsCount
  • list_getHolidays
  • list_getIPMessageCount
  • list_getIPMessages
  • list_getLanguages
  • list_getLanguagesList
  • list_getLoginCount
  • list_getLogins
  • list_getMailQueue
  • list_getMailQueueSize
  • list_getMembergroups
  • list_getMembers
  • list_getMessageIcons
  • list_getModLogEntries
  • list_getModLogEntryCount
  • list_getNews
  • list_getNumAttachments
  • list_getNumBanItems
  • list_getNumBanLogEntries
  • list_getNumBans
  • list_getNumBanTriggers
  • list_getNumFiles
  • list_getNumHolidays
  • list_getNumLanguages
  • list_getNumMembers
  • list_getNumSmileys
  • list_getNumSmileySets
  • list_getNumSpiderLogs
  • list_getNumSpiders
  • list_getNumSpiderStats
  • list_getNumTaskLogEntries
  • list_getNumUnapprovedAttachments
  • list_getNumUnwatched
  • list_getPackages
  • list_getProfileEditCount
  • list_getProfileEdits
  • list_getProfileFields
  • list_getProfileFieldSize
  • list_getScheduledTasks
  • list_getSmileys
  • list_getSmileySets
  • list_getSpiderLogs
  • list_getSpiders
  • list_getSpiderStats
  • list_getSubscribedUserCount
  • list_getSubscribedUsers
  • list_getTaskLogEntries
  • list_getTopicNotificationCount
  • list_getTopicNotifications
  • list_getUnapprovedAttachments
  • list_getUnwatched
  • list_getUserErrorCount
  • list_getUserErrors
  • list_getUserWarningCount
  • list_getUserWarnings
  • list_getWarningCount
  • list_getWarnings
  • list_getWarningTemplateCount
  • list_getWarningTemplates
  • list_getWatchedUserCount
  • list_getWatchedUserPosts
  • list_getWatchedUserPostsCount
  • list_getWatchedUsers
  • list_integration_hooks
  • listMembergroupMembers_Href
  • ListMessageIcons
  • listtree
  • load_database
  • load_file
  • load_lang_file
  • loadAttachmentContext
  • loadBoard
  • loadCacheAccelerator
  • loadCacheAPIs
  • loadCSSFile
  • loadCustomFields
  • loadDatabase
  • loadDatePair
  • loadDatePicker
  • loadEmailTemplate
  • loadEssentialData
  • loadEssentialThemeData
  • loadForumTests
  • loadGeneralSettingParameters
  • loadIllegalBBCHtmlGroups
  • loadIllegalGuestPermissions
  • loadIllegalPermissions
  • loadInstalledPackages
  • loadJavaScriptFile
  • loadLanguage
  • loadLocale
  • loadMemberContext
  • loadMemberCustomFields
  • loadMemberData
  • loadPaymentGateways
  • loadPermissionProfiles
  • loadPermissions
  • loadProfileFields
  • LoadRules
  • loadSearchAPIs
  • loadSession
  • loadSubscriptions
  • loadSubTemplate
  • loadTemplate
  • loadTheme
  • loadThemeOptions
  • loadTimePicker
  • loadUserSettings
  • LockTopic
  • LockVoting
  • log_ban
  • log_error
  • log_error_online
  • logAction
  • logActions
  • Login
  • Login2
  • LoginTFA
  • logLastDatabaseError
  • Logout
  • logSpider
  • logTriggersUpdates
  • MaintainCleanCache
  • MaintainDatabase
  • MaintainEmptyUnimportantLogs
  • MaintainFiles
  • MaintainFindFixErrors
  • MaintainMassMoveTopics
  • MaintainMembers
  • MaintainPurgeInactiveMembers
  • MaintainReattributePosts
  • MaintainRecountPosts
  • MaintainRemoveOldDrafts
  • MaintainRemoveOldPosts
  • MaintainRoutine
  • MaintainTopics
  • makeCustomFieldChanges
  • makeFilesWritable
  • makeNotificationChanges
  • makeThemeChanges
  • ManageAttachmentPaths
  • ManageAttachments
  • ManageAttachmentSettings
  • ManageAvatarSettings
  • ManageBoards
  • ManageBoardsMain
  • ManageCalendar
  • ManageLabels
  • ManageLanguages
  • ManageMail
  • ManageMaintenance
  • ManageNews
  • ManagePaidSubscriptions
  • ManagePostSettings
  • ManageRules
  • ManageScheduledTasks
  • ManageSearch
  • ManageSearchEngineSettings
  • ManageSmileys
  • markBoardsRead
  • markMessages
  • MarkRead
  • matchHighestPackageVersion
  • matchIPtoCIDR
  • matchPackageVersion
  • md5_hmac
  • MembergroupIndex
  • MembergroupMembers
  • MemberGroupsReport
  • Memberlist
  • membersAllowedTo
  • MembersAwaitingActivation
  • memoryReturnBytes
  • MergeDone
  • MergeExecute
  • MergeIndex
  • mergePosts
  • MergeTopics
  • MessageActionsApply
  • MessageDrafts
  • MessageFolder
  • MessageIndex
  • messageIndexBar
  • MessageKillAll
  • MessageMain
  • MessagePopup
  • MessagePost
  • MessagePost2
  • messagePostError
  • MessagePrune
  • MessageSearch
  • MessageSearch2
  • MessageSettings
  • mimespecialchars
  • mktree
  • MLAll
  • MLSearch
  • ModBlockGroupRequests
  • ModBlockNotes
  • ModBlockReportedMembers
  • ModBlockReportedPosts
  • ModBlockWatchedUsers
  • ModEndSession
  • ModerateGroups
  • ModerationHome
  • ModerationMain
  • ModerationSettings
  • ModifyAlertsSettings
  • ModifyAntispamSettings
  • ModifyBasicSettings
  • ModifyBBCSettings
  • modifyBoard
  • ModifyCacheSettings
  • ModifyCalendarSettings
  • ModifyCat
  • modifyCategory
  • ModifyCookieSettings
  • ModifyDatabaseSettings
  • ModifyDraftSettings
  • modifyEvent
  • ModifyFeatureSettings
  • ModifyGeneralModSettings
  • ModifyGeneralSecuritySettings
  • ModifyGeneralSettings
  • ModifyHolidays
  • ModifyLanguage
  • ModifyLanguages
  • ModifyLanguageSettings
  • ModifyLayoutSettings
  • ModifyLikesSettings
  • ModifyLoadBalancingSettings
  • ModifyLogSettings
  • ModifyMailSettings
  • ModifyMembergroup
  • ModifyMembergroup2
  • ModifyMembergroups
  • ModifyMembergroupsettings
  • ModifyMentionsSettings
  • ModifyModSettings
  • ModifyNewsSettings
  • ModifyPermissions
  • modifyPost
  • ModifyPostModeration
  • ModifyPostSettings
  • ModifyProfile
  • ModifyRegistrationSettings
  • ModifySettings
  • ModifySignatureSettings
  • ModifySubscription
  • ModifySubscriptionSettings
  • ModifyTopicSettings
  • ModifyUserSubscription
  • ModifyWarningSettings
  • ModifyWarningTemplate
  • MoveTopic
  • MoveTopic2
  • moveTopicConcurrence
  • moveTopics
  • MySQLConvertOldIp
  • newsletterpreview
  • newspreview
  • newTable
  • next_time
  • nextSubstep
  • notification
  • ob_sessrewrite
  • obExit
  • obExit_cron
  • OptimizeTables
  • package_chmod
  • package_create_backup
  • package_crypt
  • package_flush_cache
  • package_get_contents
  • package_put_contents
  • PackageBrowse
  • PackageDownload
  • PackageFTPTest
  • PackageGBrowse
  • PackageGet
  • PackageInstall
  • PackageInstallTest
  • PackageList
  • PackageOptions
  • PackagePermissions
  • PackagePermissionsAction
  • PackageRemove
  • packageRequireFTP
  • Packages
  • PackageServerAdd
  • PackageServerRemove
  • PackageServers
  • PackageUpload
  • parse_bbc
  • parse_path
  • parse_sql
  • parseAttachBBC
  • parseBoardMod
  • parseModification
  • parsePackageInfo
  • parsesmileys
  • password_get_info
  • password_hash
  • password_needs_rehash
  • password_verify
  • pauseAttachmentMaintenance
  • pauseMailQueueClear
  • pauseRepairProcess
  • pauseSignatureApplySettings
  • perform_task
  • PermissionByBoard
  • PermissionIndex
  • permute
  • php_version_check
  • phpBB3_password_check
  • PickTheme
  • PlushSearch1
  • PlushSearch2
  • populateDuplicateMembers
  • Post
  • Post2
  • PostModerationMain
  • prepareAttachsByMsg
  • prepareCLIhandler
  • prepareDBSettingContext
  • prepareDisplayContext
  • prepareLikesContext
  • prepareMailingForPreview
  • prepareMessageContext
  • prepareSearchContext
  • prepareServerSettingsContext
  • preparsecode
  • print_error
  • printMemberListRows
  • PrintTopic
  • processAttachments
  • profile_popup
  • profileLoadAvatarData
  • profileLoadGroups
  • profileLoadLanguages
  • profileLoadSignatureData
  • profileReloadUser
  • profileSaveAvatarData
  • profileSaveGroups
  • profileSendActivation
  • profileValidateEmail
  • profileValidateSignature
  • protected_alter
  • quickFileWritable
  • QuickInTopicModeration
  • QuickModeration
  • QuoteFast
  • random_bytes
  • random_int
  • RandomCompat_intval
  • RandomCompat_strlen
  • RandomCompat_substr
  • range2ip
  • read_tgz_data
  • read_tgz_file
  • read_zip_data
  • read_zip_file
  • ReadDraft
  • reapplySubscriptions
  • reattributePosts
  • rebuildModCache
  • recacheSpiderNames
  • RecentPosts
  • recountOpenReports
  • recursiveBoards
  • redirectexit
  • redirectLocation
  • ReduceMailQueue
  • reencodeImage
  • RegCenter
  • Register
  • Register2
  • RegisterCheckUsername
  • registerMember
  • registerSMStats
  • reloadSettings
  • RemindMe
  • RemindPick
  • remove_dir
  • remove_integration_function
  • remove_theme
  • RemoveAllAttachments
  • RemoveAttachment
  • RemoveAttachmentByAge
  • RemoveAttachmentBySize
  • removeBanGroups
  • removeBanLogs
  • removeBanTriggers
  • removeDeleteConcurrence
  • removeEvent
  • removeHolidays
  • removeIllegalBBCHtmlPermission
  • removeMembersFromGroups
  • removeMessage
  • removeMessages
  • RemoveOldTopics2
  • RemovePoll
  • removeSubscription
  • RemoveTheme
  • RemoveTopic2
  • removeTopics
  • reorderBoards
  • RepairAttachments
  • RepairBoards
  • replaceEntities__callback
  • ReportDetails
  • ReportedContent
  • ReportedMembers
  • ReportMessage
  • reportPost
  • ReportsMain
  • ReportToModerator
  • ReportToModerator2
  • reportUser
  • RequestMembers
  • resetPassword
  • resizeImage
  • resizeImageFile
  • RestoreTopic
  • RetrievePreview
  • safe_file_write
  • safe_serialize
  • safe_unserialize
  • sanitize_iri
  • sanitizeMSCutPaste
  • saveDBSettings
  • SaveDraft
  • saveModComment
  • SavePMDraft
  • saveProfileChanges
  • saveProfileFields
  • saveSettings
  • saveTriggers
  • scheduled_birthdayemails
  • scheduled_daily_digest
  • scheduled_daily_maintenance
  • scheduled_fetchSMfiles
  • scheduled_paid_subscriptions
  • scheduled_remove_old_drafts
  • scheduled_remove_temp_attachments
  • scheduled_remove_topic_redirect
  • scheduled_weekly_digest
  • scheduled_weekly_maintenance
  • ScheduledTasks
  • SearchEngines
  • SearchMembers
  • searchSort
  • SecretAnswer2
  • SecretAnswerInput
  • secureDirectory
  • SelectMailingMembers
  • send_http_status
  • SendActivation
  • sendmail
  • SendMailing
  • sendNotifications
  • sendpm
  • sentence_list
  • serialize_to_json
  • sessionClose
  • sessionDestroy
  • sessionGC
  • sessionOpen
  • sessionRead
  • sessionWrite
  • set_alert_icon
  • set_avatar_data
  • set_fatal_error_headers
  • set_tld_regex
  • SetCensor
  • setEventStartEnd
  • SetJavaScript
  • setKeys
  • setLoginCookie
  • setMemoryLimit
  • setNotifyPrefs
  • setPassword
  • setPassword2
  • SetQuickGroups
  • SetReserved
  • setSqlMode
  • setTFACookie
  • SetThemeOptions
  • SetThemeSettings
  • setup_fatal_error_context
  • setupMenuContext
  • setupProfileContext
  • setupThemeContext
  • sha1_core
  • sha1_ft
  • sha1_kt
  • sha1_raw
  • sha1_rol
  • sha1_smf
  • shorten_subject
  • ShowAdminHelp
  • showAlerts
  • showAttachment
  • showAttachments
  • ShowClosedReports
  • showCodeImage
  • ShowCustomProfiles
  • ShowDrafts
  • ShowHelp
  • showLetterImage
  • ShowNotice
  • showPermissions
  • ShowPHPinfoSettings
  • showPMDrafts
  • showPosts
  • showProfileDrafts
  • ShowReports
  • showUnwatched
  • ShowXmlFeed
  • sig_preview
  • smf_chmod
  • smf_crc32
  • smf_db_add_column
  • smf_db_add_index
  • smf_db_affected_rows
  • smf_db_allow_persistent
  • smf_db_backup_table
  • smf_db_calculate_type
  • smf_db_change_column
  • smf_db_create_query_column
  • smf_db_create_table
  • smf_db_create_word_search
  • smf_db_cte_support
  • smf_db_custom_order
  • smf_db_drop_table
  • smf_db_error
  • smf_db_error_backtrace
  • smf_db_error_insert
  • smf_db_escape_string
  • smf_db_escape_wildcard_string
  • smf_db_fetch_all
  • smf_db_get_server_info
  • smf_db_get_vendor
  • smf_db_get_version
  • smf_db_initiate
  • smf_db_insert
  • smf_db_insert_id
  • smf_db_list_columns
  • smf_db_list_indexes
  • smf_db_list_tables
  • smf_db_native_replace
  • smf_db_optimize_table
  • smf_db_query
  • smf_db_quote
  • smf_db_remove_column
  • smf_db_remove_index
  • smf_db_replacement__callback
  • smf_db_search_language
  • smf_db_search_query
  • smf_db_search_support
  • smf_db_select
  • smf_db_select_db
  • smf_db_table_sql
  • smf_db_table_structure
  • smf_db_transaction
  • smf_db_version
  • smf_error_handler
  • smf_error_handler_cron
  • smf_is_resource
  • smf_json_decode
  • smf_list_timezones
  • smf_main
  • smf_mysql_fetch_assoc
  • smf_mysql_fetch_row
  • smf_mysql_free_result
  • smf_mysql_insert_id
  • smf_mysql_num_rows
  • smf_mysql_real_escape_string
  • smf_seed_generator
  • smf_serverResponse
  • smf_setcookie
  • smf_strtolower
  • smf_var_export
  • SMStats
  • sortBoards
  • sortCategories
  • spamProtection
  • spell_check
  • spell_init
  • spell_suggest
  • SpellCheck
  • SpiderCheck
  • SpiderLogs
  • SpiderStats
  • SplitExecute
  • SplitIndex
  • SplitSelectionExecute
  • SplitSelectTopics
  • splitTopic
  • SplitTopics
  • ssi_boardNews
  • ssi_boardStats
  • ssi_checkPassword
  • ssi_copyright
  • ssi_fetchGroupMembers
  • ssi_fetchMember
  • ssi_fetchPosts
  • ssi_full_version
  • ssi_latestMember
  • ssi_login
  • ssi_logOnline
  • ssi_logout
  • ssi_menubar
  • ssi_news
  • ssi_pollVote
  • ssi_queryMembers
  • ssi_queryPosts
  • ssi_quickSearch
  • ssi_randomMember
  • ssi_recentAttachments
  • ssi_recentEvents
  • ssi_recentPoll
  • ssi_recentPosts
  • ssi_recentTopics
  • ssi_showPoll
  • ssi_shutdown
  • ssi_software_year
  • ssi_todaysBirthdays
  • ssi_todaysCalendar
  • ssi_todaysEvents
  • ssi_todaysHolidays
  • ssi_topBoards
  • ssi_topPoll
  • ssi_topPoster
  • ssi_topTopics
  • ssi_topTopicsReplies
  • ssi_topTopicsViews
  • ssi_version
  • ssi_welcome
  • ssi_whosOnline
  • ssl_cert_found
  • StaffReport
  • statPanel
  • Sticky
  • strip_php_comments
  • stripslashes__recursive
  • subscriptions
  • summary
  • TaskLog
  • TaskSettings
  • template_action_permissions
  • template_add_edit_group_boards_list
  • template_add_language
  • template_add_rule
  • template_additional_rows
  • template_addsmiley
  • template_admin
  • template_admin_account
  • template_admin_browse
  • template_admin_login
  • template_admin_quick_search
  • template_admin_register
  • template_admin_search_results
  • template_after
  • template_alert_configuration
  • template_alert_notifications_boards
  • template_alert_notifications_topics
  • template_alerts_all_read
  • template_alerts_popup
  • template_announce
  • template_announcement_send
  • template_ask
  • template_ask_delete
  • template_attachment_errors
  • template_attachment_paths
  • template_attachment_repair
  • template_avatar_settings_above
  • template_avatar_settings_below
  • template_backup_database
  • template_backup_xml
  • template_ban_edit
  • template_ban_edit_trigger
  • template_bcd
  • template_bi_board_children
  • template_bi_board_icon
  • template_bi_board_info
  • template_bi_board_lastpost
  • template_bi_board_stats
  • template_bi_redirect_icon
  • template_bi_redirect_stats
  • template_boardindex_outer_above
  • template_boardindex_outer_below
  • template_body_above
  • template_body_below
  • template_browse
  • template_button_strip
  • template_by_board
  • template_calendar_top
  • template_callback_question_answer_list
  • template_check_username
  • template_chmod
  • template_chmod_files
  • template_choose_payment
  • template_clean_cache_button_above
  • template_clean_cache_button_below
  • template_confirm_board_delete
  • template_confirm_category_delete
  • template_control_chmod
  • template_control_richedit
  • template_control_richedit_buttons
  • template_control_verification
  • template_convert_entities
  • template_convert_msgbody
  • template_convert_utf8
  • template_convert_xml
  • template_coppa
  • template_coppa_form
  • template_copy_template
  • template_create_index
  • template_create_index_done
  • template_create_index_progress
  • template_create_list_menu
  • template_credits
  • template_css
  • template_database_changes
  • template_database_settings
  • template_database_xml
  • template_delete_install
  • template_delete_subscription
  • template_deleteAccount
  • template_download_language
  • template_downloaded
  • template_edit_agreement
  • template_edit_browse
  • template_edit_censored
  • template_edit_comment
  • template_edit_file
  • template_edit_group
  • template_edit_holiday
  • template_edit_list
  • template_edit_options
  • template_edit_profile_field
  • template_edit_profiles
  • template_edit_reserved_words
  • template_edit_scheduled_tasks
  • template_edit_style
  • template_edit_template
  • template_editBuddies
  • template_editicon
  • template_editicons
  • template_editIgnoreList
  • template_editsets
  • template_email_members
  • template_email_members_compose
  • template_email_members_send
  • template_error_log
  • template_error_message
  • template_event_post
  • template_examine
  • template_extract_package
  • template_fatal_error
  • template_file_permissions
  • template_find_members
  • template_folder
  • template_footer
  • template_forum_settings
  • template_ftp_required
  • template_generic
  • template_generic_menu
  • template_generic_menu_dropdown_above
  • template_generic_menu_dropdown_below
  • template_generic_menu_tabs
  • template_generic_xml
  • template_generic_xml_recursive
  • template_group_members
  • template_group_request_reason
  • template_group_requests_block
  • template_groupMembership
  • template_header
  • template_hms
  • template_homepage_sample1
  • template_homepage_sample1_html
  • template_homepage_sample1_php
  • template_html_above
  • template_html_below
  • template_ic_block_calendar
  • template_ic_block_online
  • template_ic_block_recent
  • template_ic_block_stats
  • template_ignoreboards
  • template_include
  • template_info_center
  • template_init
  • template_inline_permissions
  • template_install_above
  • template_install_below
  • template_install_options
  • template_installed
  • template_issueWarning
  • template_javascript
  • template_jump_to
  • template_kick_guest
  • template_labels
  • template_like
  • template_list
  • template_list_themes
  • template_load_warning_variables
  • template_login
  • template_login_tfa
  • template_mailtest
  • template_main
  • template_maint_warning_above
  • template_maint_warning_below
  • template_maintain_database
  • template_maintain_members
  • template_maintain_routine
  • template_maintain_topics
  • template_maintenance
  • template_manual
  • template_max_size
  • template_menu
  • template_merge
  • template_merge_done
  • template_merge_extra_options
  • template_message_icons
  • template_moderation_center
  • template_moderation_settings
  • template_modify_board
  • template_modify_category
  • template_modify_group
  • template_modify_group_display
  • template_modify_language_entries
  • template_modify_subscription
  • template_modify_user_subscription
  • template_modify_weights
  • template_modifydone
  • template_modifyfast
  • template_modifyset
  • template_modifysmiley
  • template_modifytopicdone
  • template_move
  • template_new_group
  • template_news_lists
  • template_newsfader
  • template_not_done
  • template_notes
  • template_notify_board
  • template_omfg
  • template_optimize
  • template_options
  • template_package_confirm
  • template_package_list
  • template_paid_done
  • template_permission_index
  • template_permission_show_contents
  • template_php_info
  • template_pick
  • template_pm
  • template_pm_above
  • template_pm_below
  • template_pm_popup
  • template_populate_database
  • template_popup
  • template_post
  • template_post_header
  • template_postmod_permissions
  • template_print
  • template_print_above
  • template_print_below
  • template_print_options
  • template_profile_above
  • template_profile_avatar_select
  • template_profile_below
  • template_profile_birthdate
  • template_profile_group_manage
  • template_profile_pm_settings
  • template_profile_popup
  • template_profile_save
  • template_profile_signature_modify
  • template_profile_smiley_pick
  • template_profile_tfa
  • template_profile_theme_pick
  • template_profile_theme_settings
  • template_profile_timeformat_modify
  • template_prune
  • template_quickbuttons
  • template_quickreply
  • template_quotefast
  • template_recent
  • template_redirect_options
  • template_registration_agreement
  • template_registration_form
  • template_reminder_pick
  • template_repair_boards
  • template_replies
  • template_report_message
  • template_report_message_complete
  • template_report_type
  • template_reported_members
  • template_reported_members_block
  • template_reported_posts
  • template_reported_posts_block
  • template_reported_users_block
  • template_resend
  • template_reset_list
  • template_results
  • template_retry_activate
  • template_rules
  • template_search
  • template_search_members
  • template_search_results
  • template_select
  • template_select_search_method
  • template_send
  • template_sendbody
  • template_sent
  • template_serialize_json
  • template_serialize_json_xml
  • template_servers
  • template_set_options
  • template_set_password
  • template_set_settings
  • template_setorder
  • template_settings
  • template_show_backtrace
  • template_show_custom_profile
  • template_show_file
  • template_show_list
  • template_show_month_grid
  • template_show_notice
  • template_show_settings
  • template_show_spider_logs
  • template_show_spider_stats
  • template_show_upcoming_list
  • template_show_week_grid
  • template_showAlerts
  • template_showDrafts
  • template_showPermissions
  • template_showPMDrafts
  • template_showPosts
  • template_single_pm
  • template_single_post
  • template_spellcheck
  • template_spider_edit
  • template_split
  • template_ssi_above
  • template_ssi_below
  • template_statPanel
  • template_stats
  • template_subject_list
  • template_summary
  • template_terms
  • template_tfadisable
  • template_tfasetup
  • template_tfasetup_backup
  • template_thetime
  • template_topic_legend
  • template_trackActivity
  • template_trackIP
  • template_unapproved_posts
  • template_unread
  • template_upgrade_above
  • template_upgrade_below
  • template_upgrade_complete
  • template_upgrade_options
  • template_user_subscription
  • template_user_watch_post_callback
  • template_verification_sound
  • template_view_operations
  • template_view_package
  • template_view_scheduled_tasks
  • template_view_versions
  • template_viewmemberreport
  • template_viewmodreport
  • template_viewWarning
  • template_warn_template
  • template_warning
  • template_warning_divs
  • template_watched_users
  • template_welcome_message
  • template_xml_above
  • template_xml_below
  • TestMailSend
  • text2words
  • textfield_alter
  • tfadisable
  • tfasetup
  • theme
  • theme_copyright
  • theme_inline_permissions
  • theme_install
  • theme_linktree
  • ThemeAdmin
  • ThemeInstall
  • ThemeList
  • ThemesMain
  • throw_error
  • time_since
  • timeformat
  • TopicNotify
  • trackActivity
  • trackEdits
  • trackGroupReq
  • tracking
  • TrackIP
  • TrackLogins
  • trackStats
  • trackStatsUsersOnline
  • TransferAttachments
  • truncate_array
  • un_htmlspecialchars
  • un_preparsecode
  • UnapprovedAttachments
  • UnapprovedPosts
  • unescapestring__recursive
  • UnreadTopics
  • updateAdminPreferences
  • updateBanGroup
  • updateBanMembers
  • updateBoardManagers
  • updateChildPermissions
  • updateDbLastError
  • updateLastMessages
  • updateMemberData
  • updateReport
  • updateSettings
  • updateSettingsFile
  • updateStats
  • updateTriggers
  • upgrade_clean_cache
  • upgrade_query
  • upgradeExit
  • upgradeGetColumnInfo
  • UpgradeOptions
  • url_exists
  • url_image_size
  • url_parts
  • url_to_iri
  • urldecode__recursive
  • user_info_callback
  • utf8_strtolower
  • utf8_strtoupper
  • validate_iri
  • validateEventPost
  • validatePassword
  • validatePasswordFlood
  • validateSession
  • validateToken
  • validateTriggers
  • validateUsername
  • VerificationCode
  • VersionDetail
  • ViewBacktrace
  • ViewErrorLog
  • ViewFile
  • ViewMemberlist
  • ViewMembers
  • ViewModlog
  • ViewOperations
  • ViewQuery
  • ViewSpiders
  • ViewSubscribedUsers
  • ViewSubscriptions
  • viewWarning
  • ViewWarningLog
  • ViewWarnings
  • ViewWarningTemplates
  • ViewWatchedUsers
  • Vote
  • warning_preview
  • Welcome
  • WelcomeLogin
  • Who
  • WrapAction
  • writeLog
  • XmlDraft
  • XMLhttpMain
  • Overview
  • Namespace
  • Class
   1:    2:    3:    4:    5:    6:    7:    8:    9:   10:   11:   12:   13:   14:   15:   16:   17:   18:   19:   20:   21:   22:   23:   24:   25:   26:   27:   28:   29:   30:   31:   32:   33:   34:   35:   36:   37:   38:   39:   40:   41:   42:   43:   44:   45:   46:   47:   48:   49:   50:   51:   52:   53:   54:   55:   56:   57:   58:   59:   60:   61:   62:   63:   64:   65:   66:   67:   68:   69:   70:   71:   72:   73:   74:   75:   76:   77:   78:   79:   80:   81:   82:   83:   84:   85:   86:   87:   88:   89:   90:   91:   92:   93:   94:   95:   96:   97:   98:   99:  100:  101:  102:  103:  104:  105:  106:  107:  108:  109:  110:  111:  112:  113:  114:  115:  116:  117:  118:  119:  120:  121:  122:  123:  124:  125:  126:  127:  128:  129:  130:  131:  132:  133:  134:  135:  136:  137:  138:  139:  140:  141:  142:  143:  144:  145:  146:  147:  148:  149:  150:  151:  152:  153:  154:  155:  156:  157:  158:  159:  160:  161:  162:  163:  164:  165:  166:  167:  168:  169:  170:  171:  172:  173:  174:  175:  176:  177:  178:  179:  180:  181:  182:  183:  184:  185:  186:  187:  188:  189:  190:  191:  192:  193:  194:  195:  196:  197:  198:  199:  200:  201:  202:  203:  204:  205:  206:  207:  208:  209:  210:  211:  212:  213:  214:  215:  216:  217:  218:  219:  220:  221:  222:  223:  224:  225:  226:  227:  228:  229:  230:  231:  232:  233:  234:  235:  236:  237:  238:  239:  240:  241:  242:  243:  244:  245:  246:  247:  248:  249:  250:  251:  252:  253:  254:  255:  256:  257:  258:  259:  260:  261:  262:  263:  264:  265:  266:  267:  268:  269:  270:  271:  272:  273:  274:  275:  276:  277:  278:  279:  280:  281:  282:  283:  284:  285:  286:  287:  288:  289:  290:  291:  292:  293:  294:  295:  296:  297:  298:  299:  300:  301:  302:  303:  304:  305:  306:  307:  308:  309:  310:  311:  312:  313:  314:  315:  316:  317:  318:  319:  320:  321:  322:  323:  324:  325:  326:  327:  328:  329:  330:  331:  332:  333:  334:  335:  336:  337:  338:  339:  340:  341:  342:  343:  344:  345:  346:  347:  348:  349:  350:  351:  352:  353:  354:  355:  356:  357:  358:  359:  360:  361:  362:  363:  364:  365:  366:  367:  368:  369:  370:  371:  372:  373:  374:  375:  376:  377:  378:  379:  380:  381:  382:  383:  384:  385:  386:  387:  388:  389:  390:  391:  392:  393:  394:  395:  396:  397:  398:  399:  400:  401:  402:  403:  404:  405:  406:  407:  408:  409:  410:  411:  412:  413:  414:  415:  416:  417:  418:  419:  420:  421:  422:  423:  424:  425:  426:  427:  428:  429:  430:  431:  432:  433:  434:  435:  436:  437:  438:  439:  440:  441:  442:  443:  444:  445:  446:  447:  448:  449:  450:  451:  452:  453:  454:  455:  456:  457:  458:  459:  460:  461:  462:  463:  464:  465:  466:  467:  468:  469:  470:  471:  472:  473:  474:  475:  476:  477:  478:  479:  480:  481:  482:  483:  484:  485:  486:  487:  488:  489:  490:  491:  492:  493:  494:  495:  496:  497:  498:  499:  500:  501:  502:  503:  504:  505:  506:  507:  508:  509:  510:  511:  512:  513:  514:  515:  516:  517:  518:  519:  520:  521:  522:  523:  524:  525:  526:  527:  528:  529:  530:  531:  532:  533:  534:  535:  536:  537:  538:  539:  540:  541:  542:  543:  544:  545:  546:  547:  548:  549:  550:  551:  552:  553:  554:  555:  556:  557:  558:  559:  560:  561:  562:  563:  564:  565:  566:  567:  568:  569:  570:  571:  572:  573:  574:  575:  576:  577:  578:  579:  580:  581:  582:  583:  584:  585:  586:  587:  588:  589:  590:  591:  592:  593:  594:  595:  596:  597:  598:  599:  600:  601:  602:  603:  604:  605:  606:  607:  608:  609:  610:  611:  612:  613:  614:  615:  616:  617:  618:  619:  620:  621:  622:  623:  624:  625:  626:  627:  628:  629:  630:  631:  632:  633:  634:  635:  636:  637:  638:  639:  640:  641:  642:  643:  644:  645:  646:  647:  648:  649:  650:  651:  652:  653:  654:  655:  656:  657:  658:  659:  660:  661:  662:  663:  664:  665:  666:  667:  668:  669:  670:  671:  672:  673:  674:  675:  676:  677:  678:  679:  680:  681:  682:  683:  684:  685:  686:  687:  688:  689:  690:  691:  692:  693:  694:  695:  696:  697:  698:  699:  700:  701:  702:  703:  704:  705:  706:  707:  708:  709:  710:  711:  712:  713:  714:  715:  716:  717:  718:  719:  720:  721:  722:  723:  724:  725:  726:  727:  728:  729:  730:  731:  732:  733:  734:  735:  736:  737:  738:  739:  740:  741:  742:  743:  744:  745:  746:  747:  748:  749:  750:  751:  752:  753:  754:  755:  756:  757:  758:  759:  760:  761:  762:  763:  764:  765:  766:  767:  768:  769:  770:  771:  772:  773:  774:  775:  776:  777:  778:  779:  780:  781:  782:  783:  784:  785:  786:  787:  788:  789:  790:  791:  792:  793:  794:  795:  796:  797:  798:  799:  800:  801:  802:  803:  804:  805:  806:  807:  808:  809:  810:  811:  812:  813:  814:  815:  816:  817:  818:  819:  820:  821:  822:  823:  824:  825:  826:  827:  828:  829:  830:  831:  832:  833:  834:  835:  836:  837:  838:  839:  840:  841:  842:  843:  844:  845:  846:  847:  848:  849:  850:  851:  852:  853:  854:  855:  856:  857:  858:  859:  860:  861:  862:  863:  864:  865:  866:  867:  868:  869:  870:  871:  872:  873:  874:  875:  876:  877:  878:  879:  880:  881:  882:  883:  884:  885:  886:  887:  888:  889:  890:  891:  892:  893:  894:  895:  896:  897:  898:  899:  900:  901:  902:  903:  904:  905:  906:  907:  908:  909:  910:  911:  912:  913:  914:  915:  916:  917:  918:  919:  920:  921:  922:  923:  924:  925:  926:  927:  928:  929:  930:  931:  932:  933:  934:  935:  936:  937:  938:  939:  940:  941:  942:  943:  944:  945:  946:  947:  948:  949:  950:  951:  952:  953:  954:  955:  956:  957:  958:  959:  960:  961:  962:  963:  964:  965:  966:  967:  968:  969:  970:  971:  972:  973:  974:  975:  976:  977:  978:  979:  980:  981:  982:  983:  984:  985:  986:  987:  988:  989:  990:  991:  992:  993:  994:  995:  996:  997:  998:  999: 1000: 1001: 1002: 1003: 1004: 1005: 1006: 1007: 1008: 1009: 1010: 1011: 1012: 1013: 1014: 1015: 1016: 1017: 1018: 1019: 1020: 1021: 1022: 1023: 1024: 1025: 1026: 1027: 1028: 1029: 1030: 1031: 1032: 1033: 1034: 1035: 1036: 1037: 1038: 1039: 1040: 1041: 1042: 1043: 1044: 1045: 1046: 1047: 1048: 1049: 1050: 1051: 1052: 1053: 1054: 1055: 1056: 1057: 1058: 1059: 1060: 1061: 1062: 1063: 1064: 1065: 1066: 1067: 1068: 1069: 1070: 1071: 1072: 1073: 1074: 1075: 1076: 1077: 1078: 1079: 1080: 1081: 1082: 1083: 1084: 1085: 1086: 1087: 1088: 1089: 1090: 1091: 1092: 1093: 1094: 1095: 1096: 1097: 1098: 1099: 1100: 1101: 1102: 1103: 1104: 1105: 1106: 1107: 1108: 1109: 1110: 1111: 1112: 1113: 1114: 1115: 1116: 1117: 1118: 1119: 1120: 1121: 1122: 1123: 1124: 1125: 1126: 1127: 1128: 1129: 1130: 1131: 1132: 1133: 1134: 1135: 1136: 1137: 1138: 1139: 1140: 1141: 1142: 1143: 1144: 1145: 1146: 1147: 1148: 1149: 1150: 1151: 1152: 1153: 1154: 1155: 1156: 1157: 1158: 1159: 1160: 1161: 1162: 1163: 1164: 1165: 1166: 1167: 1168: 1169: 1170: 1171: 1172: 1173: 1174: 1175: 1176: 1177: 1178: 1179: 1180: 1181: 1182: 1183: 1184: 1185: 1186: 1187: 1188: 1189: 1190: 1191: 1192: 1193: 1194: 1195: 1196: 1197: 1198: 1199: 1200: 1201: 1202: 1203: 1204: 1205: 1206: 1207: 1208: 1209: 1210: 1211: 1212: 1213: 1214: 1215: 1216: 1217: 1218: 1219: 1220: 1221: 1222: 1223: 1224: 1225: 1226: 1227: 1228: 1229: 1230: 1231: 1232: 1233: 1234: 1235: 1236: 1237: 1238: 1239: 1240: 1241: 1242: 1243: 1244: 1245: 1246: 1247: 1248: 1249: 1250: 1251: 1252: 1253: 1254: 1255: 1256: 1257: 1258: 1259: 1260: 1261: 1262: 1263: 1264: 1265: 1266: 1267: 1268: 1269: 1270: 1271: 1272: 1273: 1274: 1275: 1276: 1277: 1278: 1279: 1280: 1281: 1282: 1283: 1284: 1285: 1286: 1287: 1288: 1289: 1290: 1291: 1292: 1293: 1294: 1295: 1296: 1297: 1298: 1299: 1300: 1301: 1302: 1303: 1304: 1305: 1306: 1307: 1308: 1309: 1310: 1311: 1312: 1313: 1314: 1315: 1316: 1317: 1318: 1319: 1320: 1321: 1322: 1323: 1324: 1325: 1326: 1327: 1328: 1329: 1330: 1331: 1332: 1333: 1334: 1335: 1336: 1337: 1338: 1339: 1340: 1341: 1342: 1343: 1344: 1345: 1346: 1347: 1348: 1349: 1350: 1351: 1352: 1353: 1354: 1355: 1356: 1357: 1358: 1359: 1360: 1361: 1362: 1363: 1364: 1365: 1366: 1367: 1368: 1369: 1370: 1371: 1372: 1373: 1374: 1375: 1376: 1377: 1378: 1379: 1380: 1381: 1382: 1383: 1384: 1385: 1386: 1387: 1388: 1389: 1390: 1391: 1392: 1393: 1394: 1395: 1396: 1397: 1398: 1399: 1400: 1401: 1402: 1403: 1404: 1405: 1406: 1407: 1408: 1409: 1410: 1411: 1412: 1413: 1414: 1415: 1416: 1417: 1418: 1419: 1420: 1421: 1422: 1423: 1424: 1425: 1426: 1427: 1428: 1429: 1430: 1431: 1432: 1433: 1434: 1435: 1436: 1437: 1438: 1439: 1440: 1441: 1442: 1443: 1444: 1445: 1446: 1447: 1448: 1449: 1450: 1451: 1452: 1453: 1454: 1455: 1456: 1457: 1458: 1459: 1460: 1461: 1462: 1463: 1464: 1465: 1466: 1467: 1468: 1469: 1470: 1471: 1472: 1473: 1474: 1475: 1476: 1477: 1478: 1479: 1480: 1481: 1482: 1483: 1484: 1485: 1486: 1487: 1488: 1489: 1490: 1491: 1492: 1493: 1494: 1495: 1496: 1497: 1498: 1499: 1500: 1501: 1502: 1503: 1504: 1505: 1506: 1507: 1508: 1509: 1510: 1511: 1512: 1513: 1514: 1515: 1516: 1517: 1518: 1519: 1520: 1521: 1522: 1523: 1524: 1525: 1526: 1527: 1528: 1529: 1530: 1531: 1532: 1533: 1534: 1535: 1536: 1537: 1538: 1539: 1540: 1541: 1542: 1543: 1544: 1545: 1546: 1547: 1548: 1549: 1550: 1551: 1552: 1553: 1554: 1555: 1556: 1557: 1558: 1559: 1560: 1561: 1562: 1563: 1564: 1565: 1566: 1567: 1568: 1569: 1570: 1571: 1572: 1573: 1574: 1575: 1576: 1577: 1578: 1579: 1580: 1581: 1582: 1583: 1584: 1585: 1586: 1587: 1588: 1589: 1590: 1591: 1592: 1593: 1594: 1595: 1596: 1597: 1598: 1599: 1600: 1601: 1602: 1603: 1604: 1605: 1606: 1607: 1608: 1609: 1610: 1611: 1612: 1613: 1614: 1615: 1616: 1617: 1618: 1619: 1620: 1621: 1622: 1623: 1624: 1625: 1626: 1627: 1628: 1629: 1630: 1631: 1632: 1633: 1634: 1635: 1636: 1637: 1638: 1639: 1640: 1641: 1642: 1643: 1644: 1645: 1646: 1647: 1648: 1649: 1650: 1651: 1652: 1653: 1654: 1655: 1656: 1657: 1658: 1659: 1660: 1661: 1662: 1663: 1664: 1665: 1666: 1667: 1668: 1669: 1670: 1671: 1672: 1673: 1674: 1675: 1676: 1677: 1678: 1679: 1680: 1681: 1682: 1683: 1684: 1685: 1686: 1687: 1688: 1689: 1690: 1691: 1692: 1693: 1694: 1695: 1696: 1697: 1698: 1699: 1700: 1701: 1702: 1703: 1704: 1705: 1706: 1707: 1708: 1709: 1710: 1711: 1712: 1713: 1714: 1715: 1716: 1717: 1718: 1719: 1720: 1721: 1722: 1723: 1724: 1725: 1726: 1727: 1728: 1729: 1730: 1731: 1732: 1733: 1734: 1735: 1736: 1737: 1738: 1739: 1740: 1741: 1742: 1743: 1744: 1745: 1746: 1747: 1748: 1749: 1750: 1751: 1752: 1753: 1754: 1755: 1756: 1757: 1758: 1759: 1760: 1761: 1762: 1763: 1764: 1765: 1766: 1767: 1768: 1769: 1770: 1771: 1772: 1773: 1774: 1775: 1776: 1777: 1778: 1779: 1780: 1781: 1782: 1783: 1784: 1785: 1786: 1787: 1788: 1789: 1790: 1791: 1792: 1793: 1794: 1795: 1796: 1797: 1798: 1799: 1800: 1801: 1802: 1803: 1804: 1805: 1806: 1807: 1808: 1809: 1810: 1811: 1812: 1813: 1814: 1815: 1816: 1817: 1818: 1819: 1820: 1821: 1822: 1823: 1824: 1825: 1826: 1827: 1828: 1829: 1830: 1831: 1832: 1833: 1834: 1835: 1836: 1837: 1838: 1839: 1840: 1841: 1842: 1843: 1844: 1845: 1846: 1847: 1848: 1849: 1850: 1851: 1852: 1853: 1854: 1855: 1856: 1857: 1858: 1859: 1860: 1861: 1862: 1863: 1864: 1865: 1866: 1867: 1868: 1869: 1870: 1871: 1872: 1873: 1874: 1875: 1876: 1877: 1878: 1879: 1880: 1881: 1882: 1883: 1884: 1885: 1886: 1887: 1888: 1889: 1890: 1891: 1892: 1893: 1894: 1895: 1896: 1897: 1898: 1899: 1900: 
<?php

/**
 * This file contains several functions for retrieving and manipulating calendar events, birthdays and holidays.
 *
 * Simple Machines Forum (SMF)
 *
 * @package SMF
 * @author Simple Machines https://www.simplemachines.org
 * @copyright 2020 Simple Machines and individual contributors
 * @license https://www.simplemachines.org/about/smf/license.php BSD
 *
 * @version 2.1 RC2
 */

if (!defined('SMF'))
    die('No direct access...');

/**
 * Get all birthdays within the given time range.
 * finds all the birthdays in the specified range of days.
 * works with birthdays set for no year, or any other year, and respects month and year boundaries.
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @return array An array of days, each of which is an array of birthday information for the context
 */
function getBirthdayRange($low_date, $high_date)
{
    global $smcFunc;

    // We need to search for any birthday in this range, and whatever year that birthday is on.
    $year_low = (int) substr($low_date, 0, 4);
    $year_high = (int) substr($high_date, 0, 4);

    if ($smcFunc['db_title'] !== POSTGRE_TITLE)
    {
        // Collect all of the birthdays for this month.  I know, it's a painful query.
        $result = $smcFunc['db_query']('birthday_array', '
            SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
            FROM {db_prefix}members
            WHERE YEAR(birthdate) != {string:year_one}
                AND MONTH(birthdate) != {int:no_month}
                AND DAYOFMONTH(birthdate) != {int:no_day}
                AND YEAR(birthdate) <= {int:max_year}
                AND (
                    DATE_FORMAT(birthdate, {string:year_low}) BETWEEN {date:low_date} AND {date:high_date}' . ($year_low == $year_high ? '' : '
                    OR DATE_FORMAT(birthdate, {string:year_high}) BETWEEN {date:low_date} AND {date:high_date}') . '
                )
                AND is_activated = {int:is_activated}',
            array(
                'is_activated' => 1,
                'no_month' => 0,
                'no_day' => 0,
                'year_one' => '1004',
                'year_low' => $year_low . '-%m-%d',
                'year_high' => $year_high . '-%m-%d',
                'low_date' => $low_date,
                'high_date' => $high_date,
                'max_year' => $year_high,
            )
        );
    }
    else
    {
        $result = $smcFunc['db_query']('birthday_array', '
            SELECT id_member, real_name, YEAR(birthdate) AS birth_year, birthdate
            FROM {db_prefix}members
            WHERE YEAR(birthdate) != {string:year_one}
                AND MONTH(birthdate) != {int:no_month}
                AND DAYOFMONTH(birthdate) != {int:no_day}
                AND (
                    indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_low_low_date}) AND indexable_month_day({date:year_low_high_date})' . ($year_low == $year_high ? '' : '
                    OR  indexable_month_day(birthdate) BETWEEN indexable_month_day({date:year_high_low_date}) AND indexable_month_day({date:year_high_high_date})') . '
                )
                AND is_activated = {int:is_activated}',
            array(
                'is_activated' => 1,
                'no_month' => 0,
                'no_day' => 0,
                'year_one' => '1004',
                'year_low' => $year_low . '-%m-%d',
                'year_high' => $year_high . '-%m-%d',
                'year_low_low_date' => $low_date,
                'year_low_high_date' => ($year_low == $year_high ? $high_date : $year_low . '-12-31'),
                'year_high_low_date' => ($year_low == $year_high ? $low_date : $year_high . '-01-01'),
                'year_high_high_date' => $high_date,
            )
        );
    }
    $bday = array();
    while ($row = $smcFunc['db_fetch_assoc']($result))
    {
        if ($year_low != $year_high)
            $age_year = substr($row['birthdate'], 5) < substr($high_date, 5) ? $year_high : $year_low;
        else
            $age_year = $year_low;

        $bday[$age_year . substr($row['birthdate'], 4)][] = array(
            'id' => $row['id_member'],
            'name' => $row['real_name'],
            'age' => $row['birth_year'] > 1004 && $row['birth_year'] <= $age_year ? $age_year - $row['birth_year'] : null,
            'is_last' => false
        );
    }
    $smcFunc['db_free_result']($result);

    ksort($bday);

    // Set is_last, so the themes know when to stop placing separators.
    foreach ($bday as $mday => $array)
        $bday[$mday][count($array) - 1]['is_last'] = true;

    return $bday;
}

/**
 * Get all calendar events within the given time range.
 *
 * - finds all the posted calendar events within a date range.
 * - both the earliest_date and latest_date should be in the standard YYYY-MM-DD format.
 * - censors the posted event titles.
 * - uses the current user's permissions if use_permissions is true, otherwise it does nothing "permission specific"
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @param bool $use_permissions Whether to use permissions
 * @return array Contextual information if use_permissions is true, and an array of the data needed to build that otherwise
 */
function getEventRange($low_date, $high_date, $use_permissions = true)
{
    global $scripturl, $modSettings, $user_info, $smcFunc, $context, $sourcedir;
    static $timezone_array = array();
    require_once($sourcedir . '/Subs.php');

    if (empty($timezone_array['default']))
        $timezone_array['default'] = timezone_open(date_default_timezone_get());

    $low_object = date_create($low_date);
    $high_object = date_create($high_date);

    // Find all the calendar info...
    $result = $smcFunc['db_query']('calendar_get_events', '
        SELECT
            cal.id_event, cal.title, cal.id_member, cal.id_topic, cal.id_board,
            cal.start_date, cal.end_date, cal.start_time, cal.end_time, cal.timezone, cal.location,
            b.member_groups, t.id_first_msg, t.approved, b.id_board
        FROM {db_prefix}calendar AS cal
            LEFT JOIN {db_prefix}boards AS b ON (b.id_board = cal.id_board)
            LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = cal.id_topic)
        WHERE cal.start_date <= {date:high_date}
            AND cal.end_date >= {date:low_date}' . ($use_permissions ? '
            AND (cal.id_board = {int:no_board_link} OR {query_wanna_see_board})' : ''),
        array(
            'high_date' => $high_date,
            'low_date' => $low_date,
            'no_board_link' => 0,
        )
    );
    $events = array();
    while ($row = $smcFunc['db_fetch_assoc']($result))
    {
        // If the attached topic is not approved then for the moment pretend it doesn't exist
        if (!empty($row['id_first_msg']) && $modSettings['postmod_active'] && !$row['approved'])
            continue;

        // Force a censor of the title - as often these are used by others.
        censorText($row['title'], $use_permissions ? false : true);

        // Get the various time and date properties for this event
        list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);

        if (empty($timezone_array[$tz]))
            $timezone_array[$tz] = timezone_open($tz);

        // Sanity check
        if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
            continue;

        // Get set up for the loop
        $start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$tz]);
        $end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$tz]);
        date_timezone_set($start_object, $timezone_array['default']);
        date_timezone_set($end_object, $timezone_array['default']);
        date_time_set($start_object, 0, 0, 0);
        date_time_set($end_object, 0, 0, 0);
        $start_date_string = date_format($start_object, 'Y-m-d');
        $end_date_string = date_format($end_object, 'Y-m-d');

        $cal_date = ($start_object >= $low_object) ? $start_object : $low_object;
        while ($cal_date <= $end_object && $cal_date <= $high_object)
        {
            $starts_today = (date_format($cal_date, 'Y-m-d') == $start_date_string);
            $ends_today = (date_format($cal_date, 'Y-m-d') == $end_date_string);

            $eventProperties = array(
                'id' => $row['id_event'],
                'title' => $row['title'],
                'year' => $start['year'],
                'month' => $start['month'],
                'day' => $start['day'],
                'hour' => !$allday ? $start['hour'] : null,
                'minute' => !$allday ? $start['minute'] : null,
                'second' => !$allday ? $start['second'] : null,
                'start_date' => $row['start_date'],
                'start_date_local' => $start['date_local'],
                'start_date_orig' => $start['date_orig'],
                'start_time' => !$allday ? $row['start_time'] : null,
                'start_time_local' => !$allday ? $start['time_local'] : null,
                'start_time_orig' => !$allday ? $start['time_orig'] : null,
                'start_timestamp' => $start['timestamp'],
                'start_datetime' => $start['datetime'],
                'start_iso_gmdate' => $start['iso_gmdate'],
                'end_year' => $end['year'],
                'end_month' => $end['month'],
                'end_day' => $end['day'],
                'end_hour' => !$allday ? $end['hour'] : null,
                'end_minute' => !$allday ? $end['minute'] : null,
                'end_second' => !$allday ? $end['second'] : null,
                'end_date' => $row['end_date'],
                'end_date_local' => $end['date_local'],
                'end_date_orig' => $end['date_orig'],
                'end_time' => !$allday ? $row['end_time'] : null,
                'end_time_local' => !$allday ? $end['time_local'] : null,
                'end_time_orig' => !$allday ? $end['time_orig'] : null,
                'end_timestamp' => $end['timestamp'],
                'end_datetime' => $end['datetime'],
                'end_iso_gmdate' => $end['iso_gmdate'],
                'allday' => $allday,
                'tz' => !$allday ? $tz : null,
                'tz_abbrev' => !$allday ? $tz_abbrev : null,
                'span' => $span,
                'is_last' => false,
                'id_board' => $row['id_board'],
                'is_selected' => !empty($context['selected_event']) && $context['selected_event'] == $row['id_event'],
                'starts_today' => $starts_today,
                'ends_today' => $ends_today,
                'location' => $row['location'],
            );

            // If we're using permissions (calendar pages?) then just ouput normal contextual style information.
            if ($use_permissions)
                $events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
                    'href' => $row['id_board'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
                    'link' => $row['id_board'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
                    'can_edit' => allowedTo('calendar_edit_any') || ($row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own')),
                    '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'],
                    'can_export' => !empty($modSettings['cal_export']) ? true : false,
                    'export_href' => $scripturl . '?action=calendar;sa=ical;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'],
                ));
            // Otherwise, this is going to be cached and the VIEWER'S permissions should apply... just put together some info.
            else
                $events[date_format($cal_date, 'Y-m-d')][] = array_merge($eventProperties, array(
                    'href' => $row['id_topic'] == 0 ? '' : $scripturl . '?topic=' . $row['id_topic'] . '.0',
                    'link' => $row['id_topic'] == 0 ? $row['title'] : '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['title'] . '</a>',
                    'can_edit' => false,
                    'can_export' => !empty($modSettings['cal_export']) ? true : false,
                    'topic' => $row['id_topic'],
                    'msg' => $row['id_first_msg'],
                    'poster' => $row['id_member'],
                    'allowed_groups' => explode(',', $row['member_groups']),
                ));

            date_add($cal_date, date_interval_create_from_date_string('1 day'));
        }
    }
    $smcFunc['db_free_result']($result);

    // If we're doing normal contextual data, go through and make things clear to the templates ;).
    if ($use_permissions)
    {
        foreach ($events as $mday => $array)
            $events[$mday][count($array) - 1]['is_last'] = true;
    }

    ksort($events);

    return $events;
}

/**
 * Get all holidays within the given time range.
 *
 * @param string $low_date The low end of the range, inclusive, in YYYY-MM-DD format
 * @param string $high_date The high end of the range, inclusive, in YYYY-MM-DD format
 * @return array An array of days, which are all arrays of holiday names.
 */
function getHolidayRange($low_date, $high_date)
{
    global $smcFunc;

    // Get the lowest and highest dates for "all years".
    if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
        $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_dec}
            OR event_date BETWEEN {date:all_year_jan} AND {date:all_year_high}';
    else
        $allyear_part = 'event_date BETWEEN {date:all_year_low} AND {date:all_year_high}';

    // Find some holidays... ;).
    $result = $smcFunc['db_query']('', '
        SELECT event_date, YEAR(event_date) AS year, title
        FROM {db_prefix}calendar_holidays
        WHERE event_date BETWEEN {date:low_date} AND {date:high_date}
            OR ' . $allyear_part,
        array(
            'low_date' => $low_date,
            'high_date' => $high_date,
            'all_year_low' => '1004' . substr($low_date, 4),
            'all_year_high' => '1004' . substr($high_date, 4),
            'all_year_jan' => '1004-01-01',
            'all_year_dec' => '1004-12-31',
        )
    );
    $holidays = array();
    while ($row = $smcFunc['db_fetch_assoc']($result))
    {
        if (substr($low_date, 0, 4) != substr($high_date, 0, 4))
            $event_year = substr($row['event_date'], 5) < substr($high_date, 5) ? substr($high_date, 0, 4) : substr($low_date, 0, 4);
        else
            $event_year = substr($low_date, 0, 4);

        $holidays[$event_year . substr($row['event_date'], 4)][] = $row['title'];
    }
    $smcFunc['db_free_result']($result);

    ksort($holidays);

    return $holidays;
}

/**
 * Does permission checks to see if an event can be linked to a board/topic.
 * checks if the current user can link the current topic to the calendar, permissions et al.
 * this requires the calendar_post permission, a forum moderator, or a topic starter.
 * expects the $topic and $board variables to be set.
 * if the user doesn't have proper permissions, an error will be shown.
 */
function canLinkEvent()
{
    global $user_info, $topic, $board, $smcFunc;

    // If you can't post, you can't link.
    isAllowedTo('calendar_post');

    // No board?  No topic?!?
    if (empty($board))
        fatal_lang_error('missing_board_id', false);
    if (empty($topic))
        fatal_lang_error('missing_topic_id', false);

    // Administrator, Moderator, or owner.  Period.
    if (!allowedTo('admin_forum') && !allowedTo('moderate_board'))
    {
        // Not admin or a moderator of this board. You better be the owner - or else.
        $result = $smcFunc['db_query']('', '
            SELECT id_member_started
            FROM {db_prefix}topics
            WHERE id_topic = {int:current_topic}
            LIMIT 1',
            array(
                'current_topic' => $topic,
            )
        );
        if ($row = $smcFunc['db_fetch_assoc']($result))
        {
            // Not the owner of the topic.
            if ($row['id_member_started'] != $user_info['id'])
                fatal_lang_error('not_your_topic', 'user');
        }
        // Topic/Board doesn't exist.....
        else
            fatal_lang_error('calendar_no_topic', 'general');
        $smcFunc['db_free_result']($result);
    }
}

/**
 * Returns date information about 'today' relative to the users time offset.
 * returns an array with the current date, day, month, and year.
 * takes the users time offset into account.
 *
 * @return array An array of info about today, based on forum time. Has 'day', 'month', 'year' and 'date' (in YYYY-MM-DD format)
 */
function getTodayInfo()
{
    return array(
        'day' => (int) strftime('%d', forum_time()),
        'month' => (int) strftime('%m', forum_time()),
        'year' => (int) strftime('%Y', forum_time()),
        'date' => strftime('%Y-%m-%d', forum_time()),
    );
}

/**
 * Provides information (link, month, year) about the previous and next month.
 *
 * @param string $selected_date A date in YYYY-MM-DD format
 * @param array $calendarOptions An array of calendar options
 * @param bool $is_previous Whether this is the previous month
 * @return array A large array containing all the information needed to show a calendar grid for the given month
 */
function getCalendarGrid($selected_date, $calendarOptions, $is_previous = false)
{
    global $scripturl, $modSettings;

    $selected_object = date_create($selected_date);

    $next_object = date_create($selected_date);
    date_add($next_object, date_interval_create_from_date_string('1 month'));

    $prev_object = date_create($selected_date);
    date_sub($prev_object, date_interval_create_from_date_string('1 month'));

    // Eventually this is what we'll be returning.
    $calendarGrid = array(
        'week_days' => array(),
        'weeks' => array(),
        'short_day_titles' => !empty($calendarOptions['short_day_titles']),
        'short_month_titles' => !empty($calendarOptions['short_month_titles']),
        'current_month' => date_format($selected_object, 'n'),
        'current_year' => date_format($selected_object, 'Y'),
        'current_day' => date_format($selected_object, 'd'),
        'show_next_prev' => !empty($calendarOptions['show_next_prev']),
        'show_week_links' => isset($calendarOptions['show_week_links']) ? $calendarOptions['show_week_links'] : 0,
        'previous_calendar' => array(
            'year' => date_format($prev_object, 'Y'),
            'month' => date_format($prev_object, 'n'),
            'day' => date_format($prev_object, 'd'),
            'start_date' => date_format($prev_object, 'Y-m-d'),
            'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
        ),
        'next_calendar' => array(
            'year' => date_format($next_object, 'Y'),
            'month' => date_format($next_object, 'n'),
            'day' => date_format($next_object, 'd'),
            'start_date' => date_format($next_object, 'Y-m-d'),
            'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
        ),
        'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
    );

    // Get today's date.
    $today = getTodayInfo();

    $first_day_object = date_create(date_format($selected_object, 'Y-m-01'));
    $last_day_object = date_create(date_format($selected_object, 'Y-m-t'));

    // Get information about this month.
    $month_info = array(
        'first_day' => array(
            'day_of_week' => date_format($first_day_object, 'w'),
            'week_num' => date_format($first_day_object, 'W'),
            'date' => date_format($first_day_object, 'Y-m-d'),
        ),
        'last_day' => array(
            'day_of_month' => date_format($last_day_object, 't'),
            'date' => date_format($last_day_object, 'Y-m-d'),
        ),
        'first_day_of_year' => date_format(date_create(date_format($selected_object, 'Y-01-01')), 'w'),
        'first_day_of_next_year' => date_format(date_create((date_format($selected_object, 'Y') + 1) . '-01-01'), 'w'),
    );

    // The number of days the first row is shifted to the right for the starting day.
    $nShift = $month_info['first_day']['day_of_week'];

    $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];

    // Starting any day other than Sunday means a shift...
    if (!empty($calendarOptions['start_day']))
    {
        $nShift -= $calendarOptions['start_day'];
        if ($nShift < 0)
            $nShift = 7 + $nShift;
    }

    // Number of rows required to fit the month.
    $nRows = floor(($month_info['last_day']['day_of_month'] + $nShift) / 7);
    if (($month_info['last_day']['day_of_month'] + $nShift) % 7)
        $nRows++;

    // Fetch the arrays for birthdays, posted events, and holidays.
    $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
    $events = $calendarOptions['show_events'] ? getEventRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();
    $holidays = $calendarOptions['show_holidays'] ? getHolidayRange($month_info['first_day']['date'], $month_info['last_day']['date']) : array();

    // Days of the week taking into consideration that they may want it to start on any day.
    $count = $calendarOptions['start_day'];
    for ($i = 0; $i < 7; $i++)
    {
        $calendarGrid['week_days'][] = $count;
        $count++;
        if ($count == 7)
            $count = 0;
    }

    // Iterate through each week.
    $calendarGrid['weeks'] = array();
    for ($nRow = 0; $nRow < $nRows; $nRow++)
    {
        // Start off the week - and don't let it go above 52, since that's the number of weeks in a year.
        $calendarGrid['weeks'][$nRow] = array(
            'days' => array(),
        );

        // And figure out all the days.
        for ($nCol = 0; $nCol < 7; $nCol++)
        {
            $nDay = ($nRow * 7) + $nCol - $nShift + 1;

            if ($nDay < 1 || $nDay > $month_info['last_day']['day_of_month'])
                $nDay = 0;

            $date = date_format($selected_object, 'Y-m-') . sprintf('%02d', $nDay);

            $calendarGrid['weeks'][$nRow]['days'][$nCol] = array(
                'day' => $nDay,
                'date' => $date,
                'is_today' => $date == $today['date'],
                'is_first_day' => !empty($calendarOptions['show_week_num']) && (($month_info['first_day']['day_of_week'] + $nDay - 1) % 7 == $calendarOptions['start_day']),
                'is_first_of_month' => $nDay === 1,
                'holidays' => !empty($holidays[$date]) ? $holidays[$date] : array(),
                'events' => !empty($events[$date]) ? $events[$date] : array(),
                'birthdays' => !empty($bday[$date]) ? $bday[$date] : array(),
            );
        }
    }

    // What is the last day of the month?
    if ($is_previous === true)
        $calendarGrid['last_of_month'] = $month_info['last_day']['day_of_month'];

    // We'll use the shift in the template.
    $calendarGrid['shift'] = $nShift;

    // Set the previous and the next month's links.
    $calendarGrid['previous_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['previous_calendar']['year'] . ';month=' . $calendarGrid['previous_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];
    $calendarGrid['next_calendar']['href'] = $scripturl . '?action=calendar;viewmonth;year=' . $calendarGrid['next_calendar']['year'] . ';month=' . $calendarGrid['next_calendar']['month'] . ';day=' . $calendarGrid['previous_calendar']['day'];

    loadDatePicker('#calendar_navigation .date_input');
    loadDatePair('#calendar_navigation', 'date_input');

    return $calendarGrid;
}

/**
 * Returns the information needed to show a calendar for the given week.
 *
 * @param string $selected_date A date in YYYY-MM-DD format
 * @param array $calendarOptions An array of calendar options
 * @return array An array of information needed to display the grid for a single week on the calendar
 */
function getCalendarWeek($selected_date, $calendarOptions)
{
    global $scripturl, $modSettings, $txt;

    $selected_object = date_create($selected_date);

    // Get today's date.
    $today = getTodayInfo();

    // What is the actual "start date" for the passed day.
    $calendarOptions['start_day'] = empty($calendarOptions['start_day']) ? 0 : (int) $calendarOptions['start_day'];
    $day_of_week = date_format($selected_object, 'w');
    $first_day_object = date_create($selected_date);
    if ($day_of_week != $calendarOptions['start_day'])
    {
        // Here we offset accordingly to get things to the real start of a week.
        $date_diff = $day_of_week - $calendarOptions['start_day'];
        if ($date_diff < 0)
            $date_diff += 7;

        date_sub($first_day_object, date_interval_create_from_date_string($date_diff . ' days'));
    }

    $last_day_object = date_create(date_format($first_day_object, 'Y-m-d'));
    date_add($last_day_object, date_interval_create_from_date_string('1 week'));

    $month = date_format($first_day_object, 'n');
    $year = date_format($first_day_object, 'Y');
    $day = date_format($first_day_object, 'd');

    $next_object = date_create($selected_date);
    date_add($next_object, date_interval_create_from_date_string('1 week'));

    $prev_object = date_create($selected_date);
    date_sub($prev_object, date_interval_create_from_date_string('1 week'));

    // Now start filling in the calendar grid.
    $calendarGrid = array(
        'show_next_prev' => !empty($calendarOptions['show_next_prev']),
        'previous_week' => array(
            'year' => date_format($prev_object, 'Y'),
            'month' => date_format($prev_object, 'n'),
            'day' => date_format($prev_object, 'd'),
            'start_date' => date_format($prev_object, 'Y-m-d'),
            'disabled' => $modSettings['cal_minyear'] > date_format($prev_object, 'Y'),
        ),
        'next_week' => array(
            'year' => date_format($next_object, 'Y'),
            'month' => date_format($next_object, 'n'),
            'day' => date_format($next_object, 'd'),
            'start_date' => date_format($next_object, 'Y-m-d'),
            'disabled' => $modSettings['cal_maxyear'] < date_format($next_object, 'Y'),
        ),
        'start_date' => timeformat(date_format($selected_object, 'U'), get_date_or_time_format('date')),
    );

    // Fetch the arrays for birthdays, posted events, and holidays.
    $bday = $calendarOptions['show_birthdays'] ? getBirthdayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
    $events = $calendarOptions['show_events'] ? getEventRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();
    $holidays = $calendarOptions['show_holidays'] ? getHolidayRange(date_format($first_day_object, 'Y-m-d'), date_format($last_day_object, 'Y-m-d')) : array();

    $calendarGrid['week_title'] = sprintf($txt['calendar_week_beginning'], $txt['months_titles'][date_format($first_day_object, 'n')], date_format($first_day_object, 'j'), date_format($first_day_object, 'Y'));

    // This holds all the main data - there is at least one month!
    $calendarGrid['months'] = array();
    $current_day_object = date_create(date_format($first_day_object, 'Y-m-d'));
    for ($i = 0; $i < 7; $i++)
    {
        $current_month = date_format($current_day_object, 'n');
        $current_day = date_format($current_day_object, 'j');
        $current_date = date_format($current_day_object, 'Y-m-d');

        if (!isset($calendarGrid['months'][$current_month]))
            $calendarGrid['months'][$current_month] = array(
                'current_month' => $current_month,
                'current_year' => date_format($current_day_object, 'Y'),
                'days' => array(),
            );

        $calendarGrid['months'][$current_month]['days'][$current_day] = array(
            'day' => $current_day,
            'day_of_week' => (date_format($current_day_object, 'w') + 7 - $calendarOptions['start_day']) % 7,
            'date' => $current_date,
            'is_today' => $current_date == $today['date'],
            'holidays' => !empty($holidays[$current_date]) ? $holidays[$current_date] : array(),
            'events' => !empty($events[$current_date]) ? $events[$current_date] : array(),
            'birthdays' => !empty($bday[$current_date]) ? $bday[$current_date] : array()
        );

        date_add($current_day_object, date_interval_create_from_date_string('1 day'));
    }

    // Set the previous and the next week's links.
    $calendarGrid['previous_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['previous_week']['year'] . ';month=' . $calendarGrid['previous_week']['month'] . ';day=' . $calendarGrid['previous_week']['day'];
    $calendarGrid['next_week']['href'] = $scripturl . '?action=calendar;viewweek;year=' . $calendarGrid['next_week']['year'] . ';month=' . $calendarGrid['next_week']['month'] . ';day=' . $calendarGrid['next_week']['day'];

    loadDatePicker('#calendar_navigation .date_input');
    loadDatePair('#calendar_navigation', 'date_input', '');

    return $calendarGrid;
}

/**
 * Returns the information needed to show a list of upcoming events, birthdays, and holidays on the calendar.
 *
 * @param string $start_date The start of a date range in YYYY-MM-DD format
 * @param string $end_date The end of a date range in YYYY-MM-DD format
 * @param array $calendarOptions An array of calendar options
 * @return array An array of information needed to display a list of upcoming events, etc., on the calendar
 */
function getCalendarList($start_date, $end_date, $calendarOptions)
{
    global $modSettings, $user_info, $txt, $context, $sourcedir;
    require_once($sourcedir . '/Subs.php');

    // DateTime objects make life easier
    $start_object = date_create($start_date);
    $end_object = date_create($end_date);

    $calendarGrid = array(
        'start_date' => timeformat(date_format($start_object, 'U'), get_date_or_time_format('date')),
        'start_year' => date_format($start_object, 'Y'),
        'start_month' => date_format($start_object, 'm'),
        'start_day' => date_format($start_object, 'd'),
        'end_date' => timeformat(date_format($end_object, 'U'), get_date_or_time_format('date')),
        'end_year' => date_format($end_object, 'Y'),
        'end_month' => date_format($end_object, 'm'),
        'end_day' => date_format($end_object, 'd'),
    );

    $calendarGrid['birthdays'] = $calendarOptions['show_birthdays'] ? getBirthdayRange($start_date, $end_date) : array();
    $calendarGrid['holidays'] = $calendarOptions['show_holidays'] ? getHolidayRange($start_date, $end_date) : array();
    $calendarGrid['events'] = $calendarOptions['show_events'] ? getEventRange($start_date, $end_date) : array();

    // Get rid of duplicate events
    $temp = array();
    foreach ($calendarGrid['events'] as $date => $date_events)
    {
        foreach ($date_events as $event_key => $event_val)
        {
            if (in_array($event_val['id'], $temp))
                unset($calendarGrid['events'][$date][$event_key]);
            else
                $temp[] = $event_val['id'];
        }
    }

    // Give birthdays and holidays a friendly format, without the year
    $date_format = str_replace(array('%Y', '%y', '%G', '%g', '%C', '%c', '%D'), array('', '', '', '', '', '%b %d', '%m/%d'), get_date_or_time_format('date'));

    foreach (array('birthdays', 'holidays') as $type)
    {
        foreach ($calendarGrid[$type] as $date => $date_content)
        {
            $date_local = preg_replace('~(?<=\s)0+(\d)~', '$1', trim(timeformat(strtotime($date), $date_format), " \t\n\r\0\x0B,./;:<>()[]{}\\|-_=+"));

            $calendarGrid[$type][$date]['date_local'] = $date_local;
        }
    }

    loadDatePicker('#calendar_range .date_input');
    loadDatePair('#calendar_range', 'date_input', '');

    return $calendarGrid;
}

/**
 * Loads the necessary JavaScript and CSS to create a datepicker.
 *
 * @param string $selector A CSS selector for the input field(s) that the datepicker should be attached to.
 * @param string $date_format The date format to use, in strftime() format.
 */
function loadDatePicker($selector = 'input.date_input', $date_format = '')
{
    global $modSettings, $txt, $context, $user_info;

    if (empty($date_format))
        $date_format = get_date_or_time_format('date');

    // Convert to format used by datepicker
    $date_format = strtr($date_format, array(
        // Day
        '%a' => 'D', '%A' => 'DD', '%e' => 'd', '%d' => 'dd', '%j' => 'oo', '%u' => '', '%w' => '',
        // Week
        '%U' => '', '%V' => '', '%W' => '',
        // Month
        '%b' => 'M', '%B' => 'MM', '%h' => 'M', '%m' => 'mm',
        // Year
        '%C' => '', '%g' => 'y', '%G' => 'yy', '%y' => 'y', '%Y' => 'yy',
        // Time (we remove all of these)
        '%H' => '', '%k' => '', '%I' => '', '%l' => '', '%M' => '', '%p' => '', '%P' => '',
        '%r' => '', '%R' => '', '%S' => '', '%T' => '', '%X' => '', '%z' => '', '%Z' => '',
        // Time and Date Stamps
        '%c' => 'D, d M yy', '%D' => 'mm/dd/y', '%F' => 'yy-mm-dd', '%s' => '@', '%x' => 'D, d M yy',
        // Miscellaneous
        '%n' => ' ', '%t' => ' ', '%%' => '%',
    ));

    loadCSSFile('jquery-ui.datepicker.css', array(), 'smf_datepicker');
    loadJavaScriptFile('jquery-ui.datepicker.min.js', array('defer' => true), 'smf_datepicker');
    addInlineJavaScript('
    $("' . $selector . '").datepicker({
        dateFormat: "' . $date_format . '",
        autoSize: true,
        isRTL: ' . ($context['right_to_left'] ? 'true' : 'false') . ',
        constrainInput: true,
        showAnim: "",
        showButtonPanel: false,
        yearRange: "' . $modSettings['cal_minyear'] . ':' . $modSettings['cal_maxyear'] . '",
        hideIfNoPrevNext: true,
        monthNames: ["' . implode('", "', $txt['months_titles']) . '"],
        monthNamesShort: ["' . implode('", "', $txt['months_short']) . '"],
        dayNames: ["' . implode('", "', $txt['days']) . '"],
        dayNamesShort: ["' . implode('", "', $txt['days_short']) . '"],
        dayNamesMin: ["' . implode('", "', $txt['days_short']) . '"],
        prevText: "' . $txt['prev_month'] . '",
        nextText: "' . $txt['next_month'] . '",
    });', true);
}

/**
 * Loads the necessary JavaScript and CSS to create a timepicker.
 *
 * @param string $selector A CSS selector for the input field(s) that the timepicker should be attached to.
 * @param string $time_format A time format in strftime format
 */
function loadTimePicker($selector = 'input.time_input', $time_format = '')
{
    global $modSettings, $txt, $context;

    if (empty($time_format))
        $time_format = get_date_or_time_format('time');

    // Format used for timepicker
    $time_format = strtr($time_format, array(
        '%H' => 'H',
        '%k' => 'G',
        '%I' => 'h',
        '%l' => 'g',
        '%M' => 'i',
        '%p' => 'A',
        '%P' => 'a',
        '%r' => 'h:i:s A',
        '%R' => 'H:i',
        '%S' => 's',
        '%T' => 'H:i:s',
        '%X' => 'H:i:s',
    ));

    loadCSSFile('jquery.timepicker.css', array(), 'smf_timepicker');
    loadJavaScriptFile('jquery.timepicker.min.js', array('defer' => true), 'smf_timepicker');
    addInlineJavaScript('
    $("' . $selector . '").timepicker({
        timeFormat: "' . $time_format . '",
        showDuration: true,
        maxTime: "23:59:59",
    });', true);
}

/**
 * Loads the necessary JavaScript for Datepair.js.
 *
 * Datepair.js helps to keep date ranges sane in the UI.
 *
 * @param string $container CSS selector for the containing element of the date/time inputs to be paired.
 * @param string $date_class The CSS class of the date inputs to be paired.
 * @param string $time_class The CSS class of the time inputs to be paired.
 */
function loadDatePair($container, $date_class = '', $time_class = '')
{
    global $modSettings, $txt, $context;

    $container = (string) $container;
    $date_class = (string) $date_class;
    $time_class = (string) $time_class;

    if ($container == '')
        return;

    loadJavaScriptFile('jquery.datepair.min.js', array('defer' => true), 'smf_datepair');

    $datepair_options = '';

    // If we're not using a date input, we might as well disable these.
    if ($date_class == '')
    {
        $datepair_options .= '
        parseDate: function (el) {},
        updateDate: function (el, v) {},';
    }
    else
    {
        $datepair_options .= '
        dateClass: "' . $date_class . '",';

        // Customize Datepair to work with jQuery UI's datepicker.
        $datepair_options .= '
        parseDate: function (el) {
            var val = $(el).datepicker("getDate");
            if (!val) {
                return null;
            }
            var utc = new Date(val);
            return utc && new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
        },
        updateDate: function (el, v) {
            $(el).datepicker("setDate", new Date(v.getTime() - (v.getTimezoneOffset() * 60000)));
        },';
    }

    // If not using a time input, disable time functions.
    if ($time_class == '')
    {
        $datepair_options .= '
        parseTime: function(input){},
        updateTime: function(input, dateObj){},
        setMinTime: function(input, dateObj){},';
    }
    else
    {
        $datepair_options .= '
        timeClass: "' . $time_class . '",';
    }

    addInlineJavaScript('
    $("' . $container . '").datepair({' . $datepair_options . "\n\t});", true);

}

/**
 * Retrieve all events for the given days, independently of the users offset.
 * cache callback function used to retrieve the birthdays, holidays, and events between now and now + days_to_index.
 * widens the search range by an extra 24 hours to support time offset shifts.
 * used by the cache_getRecentEvents function to get the information needed to calculate the events taking the users time offset into account.
 *
 * @param array $eventOptions With the keys 'num_days_shown', 'include_holidays', 'include_birthdays' and 'include_events'
 * @return array An array containing the data that was cached as well as an expression to calculate whether the data should be refreshed and when it expires
 */
function cache_getOffsetIndependentEvents($eventOptions)
{
    $days_to_index = $eventOptions['num_days_shown'];

    $low_date = strftime('%Y-%m-%d', forum_time(false) - 24 * 3600);
    $high_date = strftime('%Y-%m-%d', forum_time(false) + $days_to_index * 24 * 3600);

    return array(
        'data' => array(
            'holidays' => (!empty($eventOptions['include_holidays']) ? getHolidayRange($low_date, $high_date) : array()),
            'birthdays' => (!empty($eventOptions['include_birthdays']) ? getBirthdayRange($low_date, $high_date) : array()),
            'events' => (!empty($eventOptions['include_events']) ? getEventRange($low_date, $high_date, false) : array()),
        ),
        '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\']);',
        'expires' => time() + 3600,
    );
}

/**
 * cache callback function used to retrieve the upcoming birthdays, holidays, and events within the given period, taking into account the users time offset.
 * Called from the BoardIndex to display the current day's events on the board index
 * used by the board index and SSI to show the upcoming events.
 *
 * @param array $eventOptions An array of event options.
 * @return array An array containing the info that was cached as well as a few other relevant things
 */
function cache_getRecentEvents($eventOptions)
{
    // With the 'static' cached data we can calculate the user-specific data.
    $cached_data = cache_quick_get('calendar_index', 'Subs-Calendar.php', 'cache_getOffsetIndependentEvents', array($eventOptions));

    // Get the information about today (from user perspective).
    $today = getTodayInfo();

    $return_data = array(
        'calendar_holidays' => array(),
        'calendar_birthdays' => array(),
        'calendar_events' => array(),
    );

    // Set the event span to be shown in seconds.
    $days_for_index = $eventOptions['num_days_shown'] * 86400;

    // Get the current member time/date.
    $now = forum_time();

    if (!empty($eventOptions['include_holidays']))
    {
        // Holidays between now and now + days.
        for ($i = $now; $i < $now + $days_for_index; $i += 86400)
        {
            if (isset($cached_data['holidays'][strftime('%Y-%m-%d', $i)]))
                $return_data['calendar_holidays'] = array_merge($return_data['calendar_holidays'], $cached_data['holidays'][strftime('%Y-%m-%d', $i)]);
        }
    }

    if (!empty($eventOptions['include_birthdays']))
    {
        // Happy Birthday, guys and gals!
        for ($i = $now; $i < $now + $days_for_index; $i += 86400)
        {
            $loop_date = strftime('%Y-%m-%d', $i);
            if (isset($cached_data['birthdays'][$loop_date]))
            {
                foreach ($cached_data['birthdays'][$loop_date] as $index => $dummy)
                    $cached_data['birthdays'][strftime('%Y-%m-%d', $i)][$index]['is_today'] = $loop_date === $today['date'];
                $return_data['calendar_birthdays'] = array_merge($return_data['calendar_birthdays'], $cached_data['birthdays'][$loop_date]);
            }
        }
    }

    if (!empty($eventOptions['include_events']))
    {
        $duplicates = array();
        for ($i = $now; $i < $now + $days_for_index; $i += 86400)
        {
            // Determine the date of the current loop step.
            $loop_date = strftime('%Y-%m-%d', $i);

            // No events today? Check the next day.
            if (empty($cached_data['events'][$loop_date]))
                continue;

            // Loop through all events to add a few last-minute values.
            foreach ($cached_data['events'][$loop_date] as $ev => $event)
            {
                // Create a shortcut variable for easier access.
                $this_event = &$cached_data['events'][$loop_date][$ev];

                // Skip duplicates.
                if (isset($duplicates[$this_event['topic'] . $this_event['title']]))
                {
                    unset($cached_data['events'][$loop_date][$ev]);
                    continue;
                }
                else
                    $duplicates[$this_event['topic'] . $this_event['title']] = true;

                // Might be set to true afterwards, depending on the permissions.
                $this_event['can_edit'] = false;
                $this_event['is_today'] = $loop_date === $today['date'];
                $this_event['date'] = $loop_date;
            }

            if (!empty($cached_data['events'][$loop_date]))
                $return_data['calendar_events'] = array_merge($return_data['calendar_events'], $cached_data['events'][$loop_date]);
        }
    }

    // Mark the last item so that a list separator can be used in the template.
    for ($i = 0, $n = count($return_data['calendar_birthdays']); $i < $n; $i++)
        $return_data['calendar_birthdays'][$i]['is_last'] = !isset($return_data['calendar_birthdays'][$i + 1]);
    for ($i = 0, $n = count($return_data['calendar_events']); $i < $n; $i++)
        $return_data['calendar_events'][$i]['is_last'] = !isset($return_data['calendar_events'][$i + 1]);

    return array(
        'data' => $return_data,
        'expires' => time() + 3600,
        '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\']);',
        'post_retri_eval' => '
            global $context, $scripturl, $user_info;

            foreach ($cache_block[\'data\'][\'calendar_events\'] as $k => $event)
            {
                // Remove events that the user may not see or wants to ignore.
                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\']))
                    unset($cache_block[\'data\'][\'calendar_events\'][$k]);
                else
                {
                    // Whether the event can be edited depends on the permissions.
                    $cache_block[\'data\'][\'calendar_events\'][$k][\'can_edit\'] = allowedTo(\'calendar_edit_any\') || ($event[\'poster\'] == $user_info[\'id\'] && allowedTo(\'calendar_edit_own\'));

                    // The added session code makes this URL not cachable.
                    $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\'];
                }
            }

            if (empty($params[0][\'include_holidays\']))
                $cache_block[\'data\'][\'calendar_holidays\'] = array();
            if (empty($params[0][\'include_birthdays\']))
                $cache_block[\'data\'][\'calendar_birthdays\'] = array();
            if (empty($params[0][\'include_events\']))
                $cache_block[\'data\'][\'calendar_events\'] = array();

            $cache_block[\'data\'][\'show_calendar\'] = !empty($cache_block[\'data\'][\'calendar_holidays\']) || !empty($cache_block[\'data\'][\'calendar_birthdays\']) || !empty($cache_block[\'data\'][\'calendar_events\']);',
    );
}

/**
 * Makes sure the calendar post is valid.
 */
function validateEventPost()
{
    global $modSettings, $smcFunc;

    if (!isset($_POST['deleteevent']))
    {
        // The 2.1 way
        if (isset($_POST['start_date']))
        {
            $d = date_parse($_POST['start_date']);
            if (!empty($d['error_count']) || !empty($d['warning_count']))
                fatal_lang_error('invalid_date', false);
            if (empty($d['year']))
                fatal_lang_error('event_year_missing', false);
            if (empty($d['month']))
                fatal_lang_error('event_month_missing', false);
        }
        elseif (isset($_POST['start_datetime']))
        {
            $d = date_parse($_POST['start_datetime']);
            if (!empty($d['error_count']) || !empty($d['warning_count']))
                fatal_lang_error('invalid_date', false);
            if (empty($d['year']))
                fatal_lang_error('event_year_missing', false);
            if (empty($d['month']))
                fatal_lang_error('event_month_missing', false);
        }
        // The 2.0 way
        else
        {
            // No month?  No year?
            if (!isset($_POST['month']))
                fatal_lang_error('event_month_missing', false);
            if (!isset($_POST['year']))
                fatal_lang_error('event_year_missing', false);

            // Check the month and year...
            if ($_POST['month'] < 1 || $_POST['month'] > 12)
                fatal_lang_error('invalid_month', false);
            if ($_POST['year'] < $modSettings['cal_minyear'] || $_POST['year'] > $modSettings['cal_maxyear'])
                fatal_lang_error('invalid_year', false);
        }
    }

    // Make sure they're allowed to post...
    isAllowedTo('calendar_post');

    // If they want to us to calculate an end date, make sure it will fit in an acceptable range.
    if (isset($_POST['span']))
    {
        if (($_POST['span'] < 1) || (!empty($modSettings['cal_maxspan']) && $_POST['span'] > $modSettings['cal_maxspan']))
            fatal_lang_error('invalid_days_numb', false);
    }

    // There is no need to validate the following values if we are just deleting the event.
    if (!isset($_POST['deleteevent']))
    {
        // If we're doing things the 2.0 way, check the day
        if (empty($_POST['start_date']) && empty($_POST['start_datetime']))
        {
            // No day?
            if (!isset($_POST['day']))
                fatal_lang_error('event_day_missing', false);

            // Bad day?
            if (!checkdate($_POST['month'], $_POST['day'], $_POST['year']))
                fatal_lang_error('invalid_date', false);
        }

        if (!isset($_POST['evtitle']) && !isset($_POST['subject']))
            fatal_lang_error('event_title_missing', false);
        elseif (!isset($_POST['evtitle']))
            $_POST['evtitle'] = $_POST['subject'];

        // No title?
        if ($smcFunc['htmltrim']($_POST['evtitle']) === '')
            fatal_lang_error('no_event_title', false);
        if ($smcFunc['strlen']($_POST['evtitle']) > 100)
            $_POST['evtitle'] = $smcFunc['substr']($_POST['evtitle'], 0, 100);
        $_POST['evtitle'] = str_replace(';', '', $_POST['evtitle']);
    }
}

/**
 * Get the event's poster.
 *
 * @param int $event_id The ID of the event
 * @return int|bool The ID of the poster or false if the event was not found
 */
function getEventPoster($event_id)
{
    global $smcFunc;

    // A simple database query, how hard can that be?
    $request = $smcFunc['db_query']('', '
        SELECT id_member
        FROM {db_prefix}calendar
        WHERE id_event = {int:id_event}
        LIMIT 1',
        array(
            'id_event' => $event_id,
        )
    );

    // No results, return false.
    if ($smcFunc['db_num_rows'] === 0)
        return false;

    // Grab the results and return.
    list ($poster) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    return (int) $poster;
}

/**
 * Consolidating the various INSERT statements into this function.
 * Inserts the passed event information into the calendar table.
 * Allows to either set a time span (in days) or an end_date.
 * Does not check any permissions of any sort.
 *
 * @param array $eventOptions An array of event options ('title', 'span', 'start_date', 'end_date', etc.)
 */
function insertEvent(&$eventOptions)
{
    global $smcFunc, $context;

    // Add special chars to the title.
    $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);

    $eventOptions['location'] = isset($eventOptions['location']) ? $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES) : '';

    // Set the start and end dates and times
    list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);

    // If no topic and board are given, they are not linked to a topic.
    $eventOptions['board'] = isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0;
    $eventOptions['topic'] = isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0;

    $event_columns = array(
        'id_board' => 'int', 'id_topic' => 'int', 'title' => 'string-60', 'id_member' => 'int',
        'start_date' => 'date', 'end_date' => 'date', 'location' => 'string-255',
    );
    $event_parameters = array(
        $eventOptions['board'], $eventOptions['topic'], $eventOptions['title'], $eventOptions['member'],
        $start_date, $end_date, $eventOptions['location'],
    );
    if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
    {
        $event_columns['start_time'] = 'time';
        $event_parameters[] = $start_time;
        $event_columns['end_time'] = 'time';
        $event_parameters[] = $end_time;
        $event_columns['timezone'] = 'string';
        $event_parameters[] = $tz;
    }

    call_integration_hook('integrate_create_event', array(&$eventOptions, &$event_columns, &$event_parameters));

    // Insert the event!
    $eventOptions['id'] = $smcFunc['db_insert']('',
        '{db_prefix}calendar',
        $event_columns,
        $event_parameters,
        array('id_event'),
        1
    );

    // If this isn't tied to a topic, we need to notify people about it.
    if (empty($eventOptions['topic']))
    {
        $smcFunc['db_insert']('insert',
            '{db_prefix}background_tasks',
            array('task_file' => 'string', 'task_class' => 'string', 'task_data' => 'string', 'claimed_time' => 'int'),
            array('$sourcedir/tasks/EventNew-Notify.php', 'EventNew_Notify_Background', $smcFunc['json_encode'](array(
                'event_title' => $eventOptions['title'],
                'event_id' => $eventOptions['id'],
                'sender_id' => $eventOptions['member'],
                'sender_name' => $eventOptions['member'] == $context['user']['id'] ? $context['user']['name'] : '',
                'time' => time(),
            )), 0),
            array('id_task')
        );
    }

    // Update the settings to show something calendar-ish was updated.
    updateSettings(array(
        'calendar_updated' => time(),
    ));
}

/**
 * modifies an event.
 * allows to either set a time span (in days) or an end_date.
 * does not check any permissions of any sort.
 *
 * @param int $event_id The ID of the event
 * @param array $eventOptions An array of event information
 */
function modifyEvent($event_id, &$eventOptions)
{
    global $smcFunc;

    // Properly sanitize the title and location
    $eventOptions['title'] = $smcFunc['htmlspecialchars']($eventOptions['title'], ENT_QUOTES);
    $eventOptions['location'] = $smcFunc['htmlspecialchars']($eventOptions['location'], ENT_QUOTES);

    // Set the new start and end dates and times
    list($start_date, $end_date, $start_time, $end_time, $tz) = setEventStartEnd($eventOptions);

    $event_columns = array(
        'start_date' => '{date:start_date}',
        'end_date' => '{date:end_date}',
        'title' => 'SUBSTRING({string:title}, 1, 60)',
        'id_board' => '{int:id_board}',
        'id_topic' => '{int:id_topic}',
        'location' => 'SUBSTRING({string:location}, 1, 255)',
    );
    $event_parameters = array(
        'start_date' => $start_date,
        'end_date' => $end_date,
        'title' => $eventOptions['title'],
        'location' => $eventOptions['location'],
        'id_board' => isset($eventOptions['board']) ? (int) $eventOptions['board'] : 0,
        'id_topic' => isset($eventOptions['topic']) ? (int) $eventOptions['topic'] : 0,
    );
    if (!empty($start_time) && !empty($end_time) && !empty($tz) && in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
    {
        $event_columns['start_time'] = '{time:start_time}';
        $event_parameters['start_time'] = $start_time;
        $event_columns['end_time'] = '{time:end_time}';
        $event_parameters['end_time'] = $end_time;
        $event_columns['timezone'] = '{string:timezone}';
        $event_parameters['timezone'] = $tz;
    }

    // This is to prevent hooks to modify the id of the event
    $real_event_id = $event_id;
    call_integration_hook('integrate_modify_event', array($event_id, &$eventOptions, &$event_columns, &$event_parameters));

    $column_clauses = array();
    foreach ($event_columns as $col => $crit)
        $column_clauses[] = $col . ' = ' . $crit;

    $smcFunc['db_query']('', '
        UPDATE {db_prefix}calendar
        SET
            ' . implode(', ', $column_clauses) . '
        WHERE id_event = {int:id_event}',
        array_merge(
            $event_parameters,
            array(
                'id_event' => $real_event_id
            )
        )
    );

    if (empty($start_time) || empty($end_time) || empty($tz) || !in_array($tz, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
    {
        $smcFunc['db_query']('', '
            UPDATE {db_prefix}calendar
            SET start_time = NULL, end_time = NULL, timezone = NULL
            WHERE id_event = {int:id_event}',
            array(
                'id_event' => $real_event_id
            )
        );
    }

    updateSettings(array(
        'calendar_updated' => time(),
    ));
}

/**
 * Remove an event
 * removes an event.
 * does no permission checks.
 *
 * @param int $event_id The ID of the event to remove
 */
function removeEvent($event_id)
{
    global $smcFunc;

    $smcFunc['db_query']('', '
        DELETE FROM {db_prefix}calendar
        WHERE id_event = {int:id_event}',
        array(
            'id_event' => $event_id,
        )
    );

    call_integration_hook('integrate_remove_event', array($event_id));

    updateSettings(array(
        'calendar_updated' => time(),
    ));
}

/**
 * Gets all the events properties
 *
 * @param int $event_id The ID of the event
 * @return array An array of event information
 */
function getEventProperties($event_id)
{
    global $smcFunc;

    $request = $smcFunc['db_query']('', '
        SELECT
            c.id_event, c.id_board, c.id_topic, c.id_member, c.title,
            c.start_date, c.end_date, c.start_time, c.end_time, c.timezone, c.location,
            t.id_first_msg, t.id_member_started,
            mb.real_name, m.modified_time
        FROM {db_prefix}calendar AS c
            LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = c.id_topic)
            LEFT JOIN {db_prefix}members AS mb ON (mb.id_member = t.id_member_started)
            LEFT JOIN {db_prefix}messages AS m ON (m.id_msg  = t.id_first_msg)
        WHERE c.id_event = {int:id_event}',
        array(
            'id_event' => $event_id,
        )
    );

    // If nothing returned, we are in poo, poo.
    if ($smcFunc['db_num_rows']($request) === 0)
        return false;

    $row = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);

    list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);

    // Sanity check
    if (!empty($start['error_count']) || !empty($start['warning_count']) || !empty($end['error_count']) || !empty($end['warning_count']))
        return false;

    $return_value = array(
        'boards' => array(),
        'board' => $row['id_board'],
        'new' => 0,
        'eventid' => $event_id,
        'year' => $start['year'],
        'month' => $start['month'],
        'day' => $start['day'],
        'hour' => !$allday ? $start['hour'] : null,
        'minute' => !$allday ? $start['minute'] : null,
        'second' => !$allday ? $start['second'] : null,
        'start_date' => $row['start_date'],
        'start_date_local' => $start['date_local'],
        'start_date_orig' => $start['date_orig'],
        'start_time' => !$allday ? $row['start_time'] : null,
        'start_time_local' => !$allday ? $start['time_local'] : null,
        'start_time_orig' => !$allday ? $start['time_orig'] : null,
        'start_timestamp' => $start['timestamp'],
        'start_datetime' => $start['datetime'],
        'start_iso_gmdate' => $start['iso_gmdate'],
        'end_year' => $end['year'],
        'end_month' => $end['month'],
        'end_day' => $end['day'],
        'end_hour' => !$allday ? $end['hour'] : null,
        'end_minute' => !$allday ? $end['minute'] : null,
        'end_second' => !$allday ? $end['second'] : null,
        'end_date' => $row['end_date'],
        'end_date_local' => $end['date_local'],
        'end_date_orig' => $end['date_orig'],
        'end_time' => !$allday ? $row['end_time'] : null,
        'end_time_local' => !$allday ? $end['time_local'] : null,
        'end_time_orig' => !$allday ? $end['time_orig'] : null,
        'end_timestamp' => $end['timestamp'],
        'end_datetime' => $end['datetime'],
        'end_iso_gmdate' => $end['iso_gmdate'],
        'allday' => $allday,
        'tz' => !$allday ? $tz : null,
        'tz_abbrev' => !$allday ? $tz_abbrev : null,
        'span' => $span,
        'title' => $row['title'],
        'location' => $row['location'],
        'member' => $row['id_member'],
        'realname' => $row['real_name'],
        'sequence' => $row['modified_time'],
        'topic' => array(
            'id' => $row['id_topic'],
            'member_started' => $row['id_member_started'],
            'first_msg' => $row['id_first_msg'],
        ),
    );

    $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']));

    return $return_value;
}

/**
 * Gets an initial set of date and time values for creating a new event.
 *
 * @return array An array containing an initial set of date and time values for an event.
 */
function getNewEventDatetimes()
{
    // Ensure setEventStartEnd() has something to work with
    $now = date_create();
    $_POST['year'] = !empty($_POST['year']) ? $_POST['year'] : date_format($now, 'Y');
    $_POST['month'] = !empty($_POST['month']) ? $_POST['month'] : date_format($now, 'm');
    $_POST['day'] = !empty($_POST['day']) ? $_POST['day'] : date_format($now, 'd');
    $_POST['hour'] = !empty($_POST['hour']) ? $_POST['hour'] : date_format($now, 'H');
    $_POST['minute'] = !empty($_POST['minute']) ? $_POST['minute'] : date_format($now, 'i');
    $_POST['second'] = !empty($_POST['second']) ? $_POST['second'] : date_format($now, 's');

    // Set the basic values for the new event
    $row_keys = array('start_date', 'end_date', 'start_time', 'end_time', 'timezone');
    $row = array_combine($row_keys, setEventStartEnd());

    // And now set the full suite of values
    list($start, $end, $allday, $span, $tz, $tz_abbrev) = buildEventDatetimes($row);

    // Default theme only uses some of this info, but others might want it all
    $eventProperties = array(
        'year' => $start['year'],
        'month' => $start['month'],
        'day' => $start['day'],
        'hour' => !$allday ? $start['hour'] : null,
        'minute' => !$allday ? $start['minute'] : null,
        'second' => !$allday ? $start['second'] : null,
        'start_date' => $row['start_date'],
        'start_date_local' => $start['date_local'],
        'start_date_orig' => $start['date_orig'],
        'start_time' => !$allday ? $row['start_time'] : null,
        'start_time_local' => !$allday ? $start['time_local'] : null,
        'start_time_orig' => !$allday ? $start['time_orig'] : null,
        'start_timestamp' => $start['timestamp'],
        'start_datetime' => $start['datetime'],
        'start_iso_gmdate' => $start['iso_gmdate'],
        'end_year' => $end['year'],
        'end_month' => $end['month'],
        'end_day' => $end['day'],
        'end_hour' => !$allday ? $end['hour'] : null,
        'end_minute' => !$allday ? $end['minute'] : null,
        'end_second' => !$allday ? $end['second'] : null,
        'end_date' => $row['end_date'],
        'end_date_local' => $end['date_local'],
        'end_date_orig' => $end['date_orig'],
        'end_time' => !$allday ? $row['end_time'] : null,
        'end_time_local' => !$allday ? $end['time_local'] : null,
        'end_time_orig' => !$allday ? $end['time_orig'] : null,
        'end_timestamp' => $end['timestamp'],
        'end_datetime' => $end['datetime'],
        'end_iso_gmdate' => $end['iso_gmdate'],
        'allday' => $allday,
        'tz' => !$allday ? $tz : null,
        'tz_abbrev' => !$allday ? $tz_abbrev : null,
        'span' => $span,
    );

    return $eventProperties;
}

/**
 * Set the start and end dates and times for a posted event for insertion into the database.
 * Validates all date and times given to it.
 * Makes sure events do not exceed the maximum allowed duration (if any).
 * If passed an array that defines any time or date parameters, they will be used. Otherwise, gets the values from $_POST.
 *
 * @param array $eventOptions An array of optional time and date parameters (span, start_year, end_month, etc., etc.)
 * @return array An array containing $start_date, $end_date, $start_time, $end_time
 */
function setEventStartEnd($eventOptions = array())
{
    global $modSettings;

    // Set $span, in case we need it
    $span = isset($eventOptions['span']) ? $eventOptions['span'] : (isset($_POST['span']) ? $_POST['span'] : 0);
    if ($span > 0)
        $span = !empty($modSettings['cal_maxspan']) ? min($modSettings['cal_maxspan'], $span - 1) : $span - 1;

    // Define the timezone for this event, falling back to the default if not provided
    if (!empty($eventOptions['tz']) && in_array($eventOptions['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
        $tz = $eventOptions['tz'];
    elseif (!empty($_POST['tz']) && in_array($_POST['tz'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
        $tz = $_POST['tz'];
    else
        $tz = getUserTimezone();

    // Is this supposed to be an all day event, or should it have specific start and end times?
    if (isset($eventOptions['allday']))
        $allday = $eventOptions['allday'];
    elseif (empty($_POST['allday']))
        $allday = false;
    else
        $allday = true;

    // Input might come as individual parameters...
    $start_year = isset($eventOptions['year']) ? $eventOptions['year'] : (isset($_POST['year']) ? $_POST['year'] : null);
    $start_month = isset($eventOptions['month']) ? $eventOptions['month'] : (isset($_POST['month']) ? $_POST['month'] : null);
    $start_day = isset($eventOptions['day']) ? $eventOptions['day'] : (isset($_POST['day']) ? $_POST['day'] : null);
    $start_hour = isset($eventOptions['hour']) ? $eventOptions['hour'] : (isset($_POST['hour']) ? $_POST['hour'] : null);
    $start_minute = isset($eventOptions['minute']) ? $eventOptions['minute'] : (isset($_POST['minute']) ? $_POST['minute'] : null);
    $start_second = isset($eventOptions['second']) ? $eventOptions['second'] : (isset($_POST['second']) ? $_POST['second'] : null);
    $end_year = isset($eventOptions['end_year']) ? $eventOptions['end_year'] : (isset($_POST['end_year']) ? $_POST['end_year'] : null);
    $end_month = isset($eventOptions['end_month']) ? $eventOptions['end_month'] : (isset($_POST['end_month']) ? $_POST['end_month'] : null);
    $end_day = isset($eventOptions['end_day']) ? $eventOptions['end_day'] : (isset($_POST['end_day']) ? $_POST['end_day'] : null);
    $end_hour = isset($eventOptions['end_hour']) ? $eventOptions['end_hour'] : (isset($_POST['end_hour']) ? $_POST['end_hour'] : null);
    $end_minute = isset($eventOptions['end_minute']) ? $eventOptions['end_minute'] : (isset($_POST['end_minute']) ? $_POST['end_minute'] : null);
    $end_second = isset($eventOptions['end_second']) ? $eventOptions['end_second'] : (isset($_POST['end_second']) ? $_POST['end_second'] : null);

    // ... or as datetime strings ...
    $start_string = isset($eventOptions['start_datetime']) ? $eventOptions['start_datetime'] : (isset($_POST['start_datetime']) ? $_POST['start_datetime'] : null);
    $end_string = isset($eventOptions['end_datetime']) ? $eventOptions['end_datetime'] : (isset($_POST['end_datetime']) ? $_POST['end_datetime'] : null);

    // ... or as date strings and time strings.
    $start_date_string = isset($eventOptions['start_date']) ? $eventOptions['start_date'] : (isset($_POST['start_date']) ? $_POST['start_date'] : null);
    $start_time_string = isset($eventOptions['start_time']) ? $eventOptions['start_time'] : (isset($_POST['start_time']) ? $_POST['start_time'] : null);
    $end_date_string = isset($eventOptions['end_date']) ? $eventOptions['end_date'] : (isset($_POST['end_date']) ? $_POST['end_date'] : null);
    $end_time_string = isset($eventOptions['end_time']) ? $eventOptions['end_time'] : (isset($_POST['end_time']) ? $_POST['end_time'] : null);

    // If the date and time were given in separate strings, combine them
    if (empty($start_string) && isset($start_date_string))
        $start_string = $start_date_string . (isset($start_time_string) ? ' ' . $start_time_string : '');
    if (empty($end_string) && isset($end_date_string))
        $end_string = $end_date_string . (isset($end_time_string) ? ' ' . $end_time_string : '');

    // If some form of string input was given, override individually defined options with it
    if (isset($start_string))
    {
        $start_string_parsed = date_parse($start_string);
        if (empty($start_string_parsed['error_count']) && empty($start_string_parsed['warning_count']))
        {
            if ($start_string_parsed['year'] != false)
            {
                $start_year = $start_string_parsed['year'];
                $start_month = $start_string_parsed['month'];
                $start_day = $start_string_parsed['day'];
            }
            if ($start_string_parsed['hour'] != false)
            {
                $start_hour = $start_string_parsed['hour'];
                $start_minute = $start_string_parsed['minute'];
                $start_second = $start_string_parsed['second'];
            }
        }
    }
    if (isset($end_string))
    {
        $end_string_parsed = date_parse($end_string);
        if (empty($end_string_parsed['error_count']) && empty($end_string_parsed['warning_count']))
        {
            if ($end_string_parsed['year'] != false)
            {
                $end_year = $end_string_parsed['year'];
                $end_month = $end_string_parsed['month'];
                $end_day = $end_string_parsed['day'];
            }
            if ($end_string_parsed['hour'] != false)
            {
                $end_hour = $end_string_parsed['hour'];
                $end_minute = $end_string_parsed['minute'];
                $end_second = $end_string_parsed['second'];
            }
        }
    }

    // Validate input
    $start_date_isvalid = checkdate($start_month, $start_day, $start_year);
    $end_date_isvalid = checkdate($end_month, $end_day, $end_year);

    $start_time_isset = (isset($start_hour) && isset($start_minute) && isset($start_second));
    $d = date_parse(sprintf('%02d:%02d:%02d', $start_hour, $start_minute, $start_second));
    $start_time_isvalid = ($d['error_count'] == 0 && $d['warning_count'] == 0) ? true : false;

    $end_time_isset = (isset($end_hour) && isset($end_minute) && isset($end_second));
    $d = date_parse(sprintf('%02d:%02d:%02d', $end_hour, $end_minute, $end_second));
    $end_time_isvalid = ($d['error_count'] == 0 && $d['warning_count'] == 0) ? true : false;

    // Uh-oh...
    if ($start_date_isvalid === false)
    {
        fatal_lang_error('invalid_date', false);
    }

    // Make sure we use valid values for everything
    if ($end_date_isvalid === false)
    {
        $end_year = $start_year;
        $end_month = $start_month;
        $end_day = $start_day;
    }

    if ($allday === true || $start_time_isset === false || $start_time_isvalid === false)
    {
        $allday = true;
        $start_hour = 0;
        $start_minute = 0;
        $start_second = 0;
    }

    if ($allday === true || $end_time_isvalid === false || $end_time_isset === false)
    {
        $end_hour = $start_hour;
        $end_minute = $start_minute;
        $end_second = $start_second;
    }

    // Now create our datetime objects
    $start_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
    $end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $end_year, $end_month, $end_day, $end_hour, $end_minute, $end_second) . ' ' . $tz);

    // Is $end_object too early?
    if ($start_object >= $end_object)
    {
        $end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
        if ($span > 0)
            date_add($end_object, date_interval_create_from_date_string($span . ' days'));
        else
            date_add($end_object, date_interval_create_from_date_string('1 hour'));
    }

    // Is $end_object too late?
    if (!empty($modSettings['cal_maxspan']))
    {
        $date_diff = date_diff($start_object, $end_object);
        if ($date_diff->days > $modSettings['cal_maxspan'])
        {
            if ($modSettings['cal_maxspan'] > 1)
            {
                $end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, $start_hour, $start_minute, $start_second) . ' ' . $tz);
                date_add($end_object, date_interval_create_from_date_string($modSettings['cal_maxspan'] . ' days'));
            }
            else
                $end_object = date_create(sprintf('%04d-%02d-%02d %02d:%02d:%02d', $start_year, $start_month, $start_day, '11', '59', '59') . ' ' . $tz);
        }
    }

    // Finally, make our strings
    $start_date = date_format($start_object, 'Y-m-d');
    $end_date = date_format($end_object, 'Y-m-d');

    if ($allday == true)
    {
        $start_time = null;
        $end_time = null;
        $tz = null;
    }
    else
    {
        $start_time = date_format($start_object, 'H:i:s');
        $end_time = date_format($end_object, 'H:i:s');
    }

    return array($start_date, $end_date, $start_time, $end_time, $tz);
}

/**
 * Helper function for getEventRange, getEventProperties, getNewEventDatetimes, etc.
 *
 * @param array $row A database row representing an event from the calendar table
 * @return array An array containing the start and end date and time properties for the event
 */
function buildEventDatetimes($row)
{
    global $sourcedir, $user_info, $txt;
    static $date_format = '', $time_format = '';

    require_once($sourcedir . '/Subs.php');
    static $timezone_array = array();

    loadLanguage('Timezones');

    // First, try to create a better date format, ignoring the "time" elements.
    if (empty($date_format))
        $date_format = get_date_or_time_format('date');

    // We want a fairly compact version of the time, but as close as possible to the user's settings.
    if (empty($time_format))
        $time_format = strtr(get_date_or_time_format('time'), array(
            '%I' => '%l',
            '%H' => '%k',
            '%S' => '',
            '%r' => '%l:%M %p',
            '%R' => '%k:%M',
            '%T' => '%l:%M',
        ));

    // Should this be an all day event?
    $allday = (empty($row['start_time']) || empty($row['end_time']) || empty($row['timezone']) || !in_array($row['timezone'], timezone_identifiers_list(DateTimeZone::ALL_WITH_BC))) ? true : false;

    // How many days does this event span?
    $span = 1 + date_interval_format(date_diff(date_create($row['start_date']), date_create($row['end_date'])), '%d');

    // We need to have a defined timezone in the steps below
    if (empty($row['timezone']))
        $row['timezone'] = getUserTimezone();

    if (empty($timezone_array[$row['timezone']]))
        $timezone_array[$row['timezone']] = timezone_open($row['timezone']);

    // Get most of the standard date information for the start and end datetimes
    $start = date_parse($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''));
    $end = date_parse($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''));

    // But we also want more info, so make some DateTime objects we can use
    $start_object = date_create($row['start_date'] . (!$allday ? ' ' . $row['start_time'] : ''), $timezone_array[$row['timezone']]);
    $end_object = date_create($row['end_date'] . (!$allday ? ' ' . $row['end_time'] : ''), $timezone_array[$row['timezone']]);

    // Unix timestamps are good
    $start['timestamp'] = date_format($start_object, 'U');
    $end['timestamp'] = date_format($end_object, 'U');

    // Datetime string without timezone  (e.g. '2016-12-28 22:45:30')
    $start['datetime'] = date_format($start_object, 'Y-m-d H:i:s');
    $end['datetime'] = date_format($start_object, 'Y-m-d H:i:s');

    // ISO formatted datetime string, relative to UTC (e.g. '2016-12-29T05:45:30+00:00')
    $start['iso_gmdate'] = gmdate('c', $start['timestamp']);
    $end['iso_gmdate'] = gmdate('c', $end['timestamp']);

    // Strings showing the datetimes in the user's preferred format, relative to the user's time zone
    list($start['date_local'], $start['time_local']) = explode(' § ', timeformat($start['timestamp'], $date_format . ' § ' . $time_format));
    list($end['date_local'], $end['time_local']) = explode(' § ', timeformat($end['timestamp'], $date_format . ' § ' . $time_format));

    // Strings showing the datetimes in the user's preferred format, relative to the event's time zone
    list($start['date_orig'], $start['time_orig']) = explode(' § ', timeformat(strtotime(date_format($start_object, 'Y-m-d H:i:s')), $date_format . ' § ' . $time_format, 'none'));
    list($end['date_orig'], $end['time_orig']) = explode(' § ', timeformat(strtotime(date_format($end_object, 'Y-m-d H:i:s')), $date_format . ' § ' . $time_format, 'none'));

    // The time zone identifier (e.g. 'Europe/London') and abbreviation (e.g. 'GMT')
    $tz = date_format($start_object, 'e');
    $tz_abbrev = date_format($start_object, 'T');

    // If the abbreviation is just a numerical offset from UTC, make that clear.
    if (strspn($tz_abbrev, '+-') > 0)
        $tz_abbrev = 'UTC' . $tz_abbrev;

    return array($start, $end, $allday, $span, $tz, $tz_abbrev);
}

/**
 * Gets a member's selected timezone identifier directly from the database
 *
 * @param int $id_member The member id to look up. If not provided, the current user's id will be used.
 * @return string The timezone identifier string for the user's timezone.
 */
function getUserTimezone($id_member = null)
{
    global $smcFunc, $context, $user_info, $modSettings, $user_settings;
    static $member_cache = array();

    if (is_null($id_member) && $user_info['is_guest'] == false)
        $id_member = $context['user']['id'];

    //check if the cache got the data
    if (isset($id_member) && isset($member_cache[$id_member]))
    {
        return $member_cache[$id_member];
    }

    //maybe the current user is the one
    if (isset($user_settings['id_member']) && $user_settings['id_member'] == $id_member && !empty($user_settings['timezone']))
    {
        $member_cache[$id_member] = $user_settings['timezone'];
        return $user_settings['timezone'];
    }

    if (isset($id_member))
    {
        $request = $smcFunc['db_query']('', '
            SELECT timezone
            FROM {db_prefix}members
            WHERE id_member = {int:id_member}',
            array(
                'id_member' => $id_member,
            )
        );
        list($timezone) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
    }

    if (empty($timezone) || !in_array($timezone, timezone_identifiers_list(DateTimeZone::ALL_WITH_BC)))
        $timezone = isset($modSettings['default_timezone']) ? $modSettings['default_timezone'] : date_default_timezone_get();

    if (isset($id_member))
        $member_cache[$id_member] = $timezone;

    return $timezone;
}

/**
 * Gets all of the holidays for the listing
 *
 * @param int $start The item to start with (for pagination purposes)
 * @param int $items_per_page How many items to show on each page
 * @param string $sort A string indicating how to sort the results
 * @return array An array of holidays, each of which is an array containing the id, year, month, day and title of the holiday
 */
function list_getHolidays($start, $items_per_page, $sort)
{
    global $smcFunc;

    $request = $smcFunc['db_query']('', '
        SELECT id_holiday, YEAR(event_date) AS year, MONTH(event_date) AS month, DAYOFMONTH(event_date) AS day, title
        FROM {db_prefix}calendar_holidays
        ORDER BY {raw:sort}
        LIMIT {int:start}, {int:max}',
        array(
            'sort' => $sort,
            'start' => $start,
            'max' => $items_per_page,
        )
    );
    $holidays = array();
    while ($row = $smcFunc['db_fetch_assoc']($request))
        $holidays[] = $row;
    $smcFunc['db_free_result']($request);

    return $holidays;
}

/**
 * Helper function to get the total number of holidays
 *
 * @return int The total number of holidays
 */
function list_getNumHolidays()
{
    global $smcFunc;

    $request = $smcFunc['db_query']('', '
        SELECT COUNT(*)
        FROM {db_prefix}calendar_holidays',
        array(
        )
    );
    list($num_items) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);

    return (int) $num_items;
}

/**
 * Remove a holiday from the calendar
 *
 * @param array $holiday_ids An array of IDs of holidays to delete
 */
function removeHolidays($holiday_ids)
{
    global $smcFunc;

    $smcFunc['db_query']('', '
        DELETE FROM {db_prefix}calendar_holidays
        WHERE id_holiday IN ({array_int:id_holiday})',
        array(
            'id_holiday' => $holiday_ids,
        )
    );

    updateSettings(array(
        'calendar_updated' => time(),
    ));
}

?>
API documentation generated by ApiGen