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: 
<?php

/**
 * This file handles the uploading and creation of attachments
 * as well as the auto management of the attachment directories.
 *
 * 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...');

/**
 * Check if the current directory is still valid or not.
 * If not creates the new directory
 *
 * @return void|bool False if any error occurred
 */
function automanage_attachments_check_directory()
{
    global $smcFunc, $boarddir, $modSettings, $context;

    // Not pretty, but since we don't want folders created for every post. It'll do unless a better solution can be found.
    if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'admin')
        $doit = true;
    elseif (empty($modSettings['automanage_attachments']))
        return;
    elseif (!isset($_FILES))
        return;
    elseif (isset($_FILES['attachment']))
        foreach ($_FILES['attachment']['tmp_name'] as $dummy)
            if (!empty($dummy))
            {
                $doit = true;
                break;
            }

    if (!isset($doit))
        return;

    $year = date('Y');
    $month = date('m');

    $rand = md5(mt_rand());
    $rand1 = $rand[1];
    $rand = $rand[0];

    if (!empty($modSettings['attachment_basedirectories']) && !empty($modSettings['use_subdirectories_for_attachments']))
    {
        if (!is_array($modSettings['attachment_basedirectories']))
            $modSettings['attachment_basedirectories'] = $smcFunc['json_decode']($modSettings['attachment_basedirectories'], true);
        $base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
    }
    else
        $base_dir = 0;

    if ($modSettings['automanage_attachments'] == 1)
    {
        if (!isset($modSettings['last_attachments_directory']))
            $modSettings['last_attachments_directory'] = array();
        if (!is_array($modSettings['last_attachments_directory']))
            $modSettings['last_attachments_directory'] = $smcFunc['json_decode']($modSettings['last_attachments_directory'], true);
        if (!isset($modSettings['last_attachments_directory'][$base_dir]))
            $modSettings['last_attachments_directory'][$base_dir] = 0;
    }

    $basedirectory = (!empty($modSettings['use_subdirectories_for_attachments']) ? ($modSettings['basedirectory_for_attachments']) : $boarddir);
    //Just to be sure: I don't want directory separators at the end
    $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
    $basedirectory = rtrim($basedirectory, $sep);

    switch ($modSettings['automanage_attachments'])
    {
        case 1:
            $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . (isset($modSettings['last_attachments_directory'][$base_dir]) ? $modSettings['last_attachments_directory'][$base_dir] : 0);
            break;
        case 2:
            $updir = $basedirectory . DIRECTORY_SEPARATOR . $year;
            break;
        case 3:
            $updir = $basedirectory . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month;
            break;
        case 4:
            $updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand;
            break;
        case 5:
            $updir = $basedirectory . DIRECTORY_SEPARATOR . (empty($modSettings['use_subdirectories_for_attachments']) ? 'attachments-' : 'random_') . $rand . DIRECTORY_SEPARATOR . $rand1;
            break;
        default :
            $updir = '';
    }

    if (!is_array($modSettings['attachmentUploadDir']))
        $modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
    if (!in_array($updir, $modSettings['attachmentUploadDir']) && !empty($updir))
        $outputCreation = automanage_attachments_create_directory($updir);
    elseif (in_array($updir, $modSettings['attachmentUploadDir']))
        $outputCreation = true;

    if ($outputCreation)
    {
        $modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
        $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];

        updateSettings(array(
            'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
        ));
    }

    return $outputCreation;
}

/**
 * Creates a directory
 *
 * @param string $updir The directory to be created
 *
 * @return bool False on errors
 */
function automanage_attachments_create_directory($updir)
{
    global $smcFunc, $modSettings, $context, $boarddir;

    $tree = get_directory_tree_elements($updir);
    $count = count($tree);

    $directory = attachments_init_dir($tree, $count);
    if ($directory === false)
    {
        // Maybe it's just the folder name
        $tree = get_directory_tree_elements($boarddir . DIRECTORY_SEPARATOR . $updir);
        $count = count($tree);

        $directory = attachments_init_dir($tree, $count);
        if ($directory === false)
            return false;
    }

    $directory .= DIRECTORY_SEPARATOR . array_shift($tree);

    while (!@is_dir($directory) || $count != -1)
    {
        if (!@is_dir($directory))
        {
            if (!@mkdir($directory, 0755))
            {
                $context['dir_creation_error'] = 'attachments_no_create';
                return false;
            }
        }

        $directory .= DIRECTORY_SEPARATOR . array_shift($tree);
        $count--;
    }

    // Check if the dir is writable.
    if (!smf_chmod($directory))
    {
        $context['dir_creation_error'] = 'attachments_no_write';
        return false;
    }

    // Everything seems fine...let's create the .htaccess
    if (!file_exists($directory . DIRECTORY_SEPARATOR . '.htaccess'))
        secureDirectory($updir, true);

    $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
    $updir = rtrim($updir, $sep);

    // Only update if it's a new directory
    if (!in_array($updir, $modSettings['attachmentUploadDir']))
    {
        $modSettings['currentAttachmentUploadDir'] = max(array_keys($modSettings['attachmentUploadDir'])) + 1;
        $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']] = $updir;

        updateSettings(array(
            'attachmentUploadDir' => $smcFunc['json_encode']($modSettings['attachmentUploadDir']),
            'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
        ), true);
        $modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
    }

    $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];
    return true;
}

/**
 * Called when a directory space limit is reached.
 * Creates a new directory and increments the directory suffix number.
 *
 * @return void|bool False on errors, true if successful, nothing if auto-management of attachments is disabled
 */
function automanage_attachments_by_space()
{
    global $smcFunc, $modSettings, $boarddir;

    if (!isset($modSettings['automanage_attachments']) || (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] != 1))
        return;

    $basedirectory = !empty($modSettings['use_subdirectories_for_attachments']) ? $modSettings['basedirectory_for_attachments'] : $boarddir;
    // Just to be sure: I don't want directory separators at the end
    $sep = (DIRECTORY_SEPARATOR === '\\') ? '\/' : DIRECTORY_SEPARATOR;
    $basedirectory = rtrim($basedirectory, $sep);

    // Get the current base directory
    if (!empty($modSettings['use_subdirectories_for_attachments']) && !empty($modSettings['attachment_basedirectories']))
    {
        $base_dir = array_search($modSettings['basedirectory_for_attachments'], $modSettings['attachment_basedirectories']);
        $base_dir = !empty($modSettings['automanage_attachments']) ? $base_dir : 0;
    }
    else
        $base_dir = 0;

    // Get the last attachment directory for that base directory
    if (empty($modSettings['last_attachments_directory'][$base_dir]))
        $modSettings['last_attachments_directory'][$base_dir] = 0;
    // And increment it.
    $modSettings['last_attachments_directory'][$base_dir]++;

    $updir = $basedirectory . DIRECTORY_SEPARATOR . 'attachments_' . $modSettings['last_attachments_directory'][$base_dir];
    if (automanage_attachments_create_directory($updir))
    {
        $modSettings['currentAttachmentUploadDir'] = array_search($updir, $modSettings['attachmentUploadDir']);
        updateSettings(array(
            'last_attachments_directory' => $smcFunc['json_encode']($modSettings['last_attachments_directory']),
            'currentAttachmentUploadDir' => $modSettings['currentAttachmentUploadDir'],
        ));
        $modSettings['last_attachments_directory'] = $smcFunc['json_decode']($modSettings['last_attachments_directory'], true);

        return true;
    }
    else
        return false;
}

/**
 * Split a path into a list of all directories and subdirectories
 *
 * @param string $directory A path
 *
 * @return array|bool An array of all the directories and subdirectories or false on failure
 */
function get_directory_tree_elements($directory)
{
    /*
        In Windows server both \ and / can be used as directory separators in paths
        In Linux (and presumably *nix) servers \ can be part of the name
        So for this reasons:
            * in Windows we need to explode for both \ and /
            * while in linux should be safe to explode only for / (aka DIRECTORY_SEPARATOR)
    */
    if (DIRECTORY_SEPARATOR === '\\')
        $tree = preg_split('#[\\\/]#', $directory);
    else
    {
        if (substr($directory, 0, 1) != DIRECTORY_SEPARATOR)
            return false;

        $tree = explode(DIRECTORY_SEPARATOR, trim($directory, DIRECTORY_SEPARATOR));
    }
    return $tree;
}

/**
 * Return the first part of a path (i.e. c:\ or / + the first directory), used by automanage_attachments_create_directory
 *
 * @param array $tree An array
 * @param int $count The number of elements in $tree
 *
 * @return string|bool The first part of the path or false on error
 */
function attachments_init_dir(&$tree, &$count)
{
    $directory = '';
    // If on Windows servers the first part of the path is the drive (e.g. "C:")
    if (DIRECTORY_SEPARATOR === '\\')
    {
        //Better be sure that the first part of the path is actually a drive letter...
        //...even if, I should check this in the admin page...isn't it?
        //...NHAAA Let's leave space for users' complains! :P
        if (preg_match('/^[a-z]:$/i', $tree[0]))
            $directory = array_shift($tree);
        else
            return false;

        $count--;
    }
    return $directory;
}

/**
 * Moves an attachment to the proper directory and set the relevant data into $_SESSION['temp_attachments']
 */
function processAttachments()
{
    global $context, $modSettings, $smcFunc, $txt, $user_info;

    // Make sure we're uploading to the right place.
    if (!empty($modSettings['automanage_attachments']))
        automanage_attachments_check_directory();

    if (!is_array($modSettings['attachmentUploadDir']))
        $modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);

    $context['attach_dir'] = $modSettings['attachmentUploadDir'][$modSettings['currentAttachmentUploadDir']];

    // Is the attachments folder actualy there?
    if (!empty($context['dir_creation_error']))
        $initial_error = $context['dir_creation_error'];
    elseif (!is_dir($context['attach_dir']))
    {
        $initial_error = 'attach_folder_warning';
        log_error(sprintf($txt['attach_folder_admin_warning'], $context['attach_dir']), 'critical');
    }

    if (!isset($initial_error) && !isset($context['attachments']))
    {
        // If this isn't a new post, check the current attachments.
        if (isset($_REQUEST['msg']))
        {
            $request = $smcFunc['db_query']('', '
                SELECT COUNT(*), SUM(size)
                FROM {db_prefix}attachments
                WHERE id_msg = {int:id_msg}
                    AND attachment_type = {int:attachment_type}',
                array(
                    'id_msg' => (int) $_REQUEST['msg'],
                    'attachment_type' => 0,
                )
            );
            list ($context['attachments']['quantity'], $context['attachments']['total_size']) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
        }
        else
            $context['attachments'] = array(
                'quantity' => 0,
                'total_size' => 0,
            );
    }

    // Hmm. There are still files in session.
    $ignore_temp = false;
    if (!empty($_SESSION['temp_attachments']['post']['files']) && count($_SESSION['temp_attachments']) > 1)
    {
        // Let's try to keep them. But...
        $ignore_temp = true;
        // If new files are being added. We can't ignore those
        foreach ($_FILES['attachment']['tmp_name'] as $dummy)
            if (!empty($dummy))
            {
                $ignore_temp = false;
                break;
            }

        // Need to make space for the new files. So, bye bye.
        if (!$ignore_temp)
        {
            foreach ($_SESSION['temp_attachments'] as $attachID => $attachment)
                if (strpos($attachID, 'post_tmp_' . $user_info['id']) !== false)
                    unlink($attachment['tmp_name']);

            $context['we_are_history'] = $txt['error_temp_attachments_flushed'];
            $_SESSION['temp_attachments'] = array();
        }
    }

    if (!isset($_FILES['attachment']['name']))
        $_FILES['attachment']['tmp_name'] = array();

    if (!isset($_SESSION['temp_attachments']))
        $_SESSION['temp_attachments'] = array();

    // Remember where we are at. If it's anywhere at all.
    if (!$ignore_temp)
        $_SESSION['temp_attachments']['post'] = array(
            'msg' => !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : 0,
            'last_msg' => !empty($_REQUEST['last_msg']) ? $_REQUEST['last_msg'] : 0,
            'topic' => !empty($topic) ? $topic : 0,
            'board' => !empty($board) ? $board : 0,
        );

    // If we have an initial error, lets just display it.
    if (!empty($initial_error))
    {
        $_SESSION['temp_attachments']['initial_error'] = $initial_error;

        // And delete the files 'cos they ain't going nowhere.
        foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
            if (file_exists($_FILES['attachment']['tmp_name'][$n]))
                unlink($_FILES['attachment']['tmp_name'][$n]);

        $_FILES['attachment']['tmp_name'] = array();
    }

    // Loop through $_FILES['attachment'] array and move each file to the current attachments folder.
    foreach ($_FILES['attachment']['tmp_name'] as $n => $dummy)
    {
        if ($_FILES['attachment']['name'][$n] == '')
            continue;

        // First, let's first check for PHP upload errors.
        $errors = array();
        if (!empty($_FILES['attachment']['error'][$n]))
        {
            if ($_FILES['attachment']['error'][$n] == 2)
                $errors[] = array('file_too_big', array($modSettings['attachmentSizeLimit']));
            elseif ($_FILES['attachment']['error'][$n] == 6)
                log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_6'], 'critical');
            else
                log_error($_FILES['attachment']['name'][$n] . ': ' . $txt['php_upload_error_' . $_FILES['attachment']['error'][$n]]);
            if (empty($errors))
                $errors[] = 'attach_php_error';
        }

        // Try to move and rename the file before doing any more checks on it.
        $attachID = 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand());
        $destName = $context['attach_dir'] . '/' . $attachID;
        if (empty($errors))
        {
            // The reported MIME type of the attachment might not be reliable.
            // Fortunately, PHP 5.3+ lets us easily verify the real MIME type.
            if (function_exists('mime_content_type'))
                $_FILES['attachment']['type'][$n] = mime_content_type($_FILES['attachment']['tmp_name'][$n]);

            $_SESSION['temp_attachments'][$attachID] = array(
                'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
                'tmp_name' => $destName,
                'size' => $_FILES['attachment']['size'][$n],
                'type' => $_FILES['attachment']['type'][$n],
                'id_folder' => $modSettings['currentAttachmentUploadDir'],
                'errors' => array(),
            );

            // Move the file to the attachments folder with a temp name for now.
            if (@move_uploaded_file($_FILES['attachment']['tmp_name'][$n], $destName))
                smf_chmod($destName, 0644);
            else
            {
                $_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_timeout';
                if (file_exists($_FILES['attachment']['tmp_name'][$n]))
                    unlink($_FILES['attachment']['tmp_name'][$n]);
            }
        }
        else
        {
            $_SESSION['temp_attachments'][$attachID] = array(
                'name' => $smcFunc['htmlspecialchars'](basename($_FILES['attachment']['name'][$n])),
                'tmp_name' => $destName,
                'errors' => $errors,
            );

            if (file_exists($_FILES['attachment']['tmp_name'][$n]))
                unlink($_FILES['attachment']['tmp_name'][$n]);
        }
        // If there's no errors to this point. We still do need to apply some additional checks before we are finished.
        if (empty($_SESSION['temp_attachments'][$attachID]['errors']))
            attachmentChecks($attachID);
    }
    // Mod authors, finally a hook to hang an alternate attachment upload system upon
    // Upload to the current attachment folder with the file name $attachID or 'post_tmp_' . $user_info['id'] . '_' . md5(mt_rand())
    // Populate $_SESSION['temp_attachments'][$attachID] with the following:
    //   name => The file name
    //   tmp_name => Path to the temp file ($context['attach_dir'] . '/' . $attachID).
    //   size => File size (required).
    //   type => MIME type (optional if not available on upload).
    //   id_folder => $modSettings['currentAttachmentUploadDir']
    //   errors => An array of errors (use the index of the $txt variable for that error).
    // Template changes can be done using "integrate_upload_template".
    call_integration_hook('integrate_attachment_upload', array());
}

/**
 * Performs various checks on an uploaded file.
 * - Requires that $_SESSION['temp_attachments'][$attachID] be properly populated.
 *
 * @param int $attachID The ID of the attachment
 * @return bool Whether the attachment is OK
 */
function attachmentChecks($attachID)
{
    global $modSettings, $context, $sourcedir, $smcFunc;

    // No data or missing data .... Not necessarily needed, but in case a mod author missed something.
    if (empty($_SESSION['temp_attachments'][$attachID]))
        $error = '$_SESSION[\'temp_attachments\'][$attachID]';

    elseif (empty($attachID))
        $error = '$attachID';

    elseif (empty($context['attachments']))
        $error = '$context[\'attachments\']';

    elseif (empty($context['attach_dir']))
        $error = '$context[\'attach_dir\']';

    // Let's get their attention.
    if (!empty($error))
        fatal_lang_error('attach_check_nag', 'debug', array($error));

    // Just in case this slipped by the first checks, we stop it here and now
    if ($_SESSION['temp_attachments'][$attachID]['size'] == 0)
    {
        $_SESSION['temp_attachments'][$attachID]['errors'][] = 'attach_0_byte_file';
        return false;
    }

    // First, the dreaded security check. Sorry folks, but this shouldn't be avoided.
    $size = @getimagesize($_SESSION['temp_attachments'][$attachID]['tmp_name']);
    if (is_array($size) && isset($size[2], $context['valid_image_types'][$size[2]]))
    {
        require_once($sourcedir . '/Subs-Graphics.php');
        if (!checkImageContents($_SESSION['temp_attachments'][$attachID]['tmp_name'], !empty($modSettings['attachment_image_paranoid'])))
        {
            // It's bad. Last chance, maybe we can re-encode it?
            if (empty($modSettings['attachment_image_reencode']) || (!reencodeImage($_SESSION['temp_attachments'][$attachID]['tmp_name'], $size[2])))
            {
                // Nothing to do: not allowed or not successful re-encoding it.
                $_SESSION['temp_attachments'][$attachID]['errors'][] = 'bad_attachment';
                return false;
            }
            // Success! However, successes usually come for a price:
            // we might get a new format for our image...
            $old_format = $size[2];
            $size = @getimagesize($_SESSION['temp_attachments'][$attachID]['tmp_name']);
            if (!(empty($size)) && ($size[2] != $old_format))
                $_SESSION['temp_attachments'][$attachID]['type'] = 'image/' . $context['valid_image_types'][$size[2]];
        }
    }

    // Is there room for this sucker?
    if (!empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
    {
        // Check the folder size and count. If it hasn't been done already.
        if (empty($context['dir_size']) || empty($context['dir_files']))
        {
            $request = $smcFunc['db_query']('', '
                SELECT COUNT(*), SUM(size)
                FROM {db_prefix}attachments
                WHERE id_folder = {int:folder_id}
                    AND attachment_type != {int:type}',
                array(
                    'folder_id' => $modSettings['currentAttachmentUploadDir'],
                    'type' => 1,
                )
            );
            list ($context['dir_files'], $context['dir_size']) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
        }
        $context['dir_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
        $context['dir_files']++;

        // Are we about to run out of room? Let's notify the admin then.
        if (empty($modSettings['attachment_full_notified']) && !empty($modSettings['attachmentDirSizeLimit']) && $modSettings['attachmentDirSizeLimit'] > 4000 && $context['dir_size'] > ($modSettings['attachmentDirSizeLimit'] - 2000) * 1024
            || (!empty($modSettings['attachmentDirFileLimit']) && $modSettings['attachmentDirFileLimit'] * .95 < $context['dir_files'] && $modSettings['attachmentDirFileLimit'] > 500))
        {
            require_once($sourcedir . '/Subs-Admin.php');
            emailAdmins('admin_attachments_full');
            updateSettings(array('attachment_full_notified' => 1));
        }

        // // No room left.... What to do now???
        if (!empty($modSettings['attachmentDirFileLimit']) && $context['dir_files'] > $modSettings['attachmentDirFileLimit']
            || (!empty($modSettings['attachmentDirSizeLimit']) && $context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024))
        {
            if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1)
            {
                // Move it to the new folder if we can.
                if (automanage_attachments_by_space())
                {
                    rename($_SESSION['temp_attachments'][$attachID]['tmp_name'], $context['attach_dir'] . '/' . $attachID);
                    $_SESSION['temp_attachments'][$attachID]['tmp_name'] = $context['attach_dir'] . '/' . $attachID;
                    $_SESSION['temp_attachments'][$attachID]['id_folder'] = $modSettings['currentAttachmentUploadDir'];
                    $context['dir_size'] = 0;
                    $context['dir_files'] = 0;
                }
                // Or, let the user know that it ain't gonna happen.
                else
                {
                    if (isset($context['dir_creation_error']))
                        $_SESSION['temp_attachments'][$attachID]['errors'][] = $context['dir_creation_error'];
                    else
                        $_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
                }
            }
            else
                $_SESSION['temp_attachments'][$attachID]['errors'][] = 'ran_out_of_space';
        }
    }

    // Is the file too big?
    $context['attachments']['total_size'] += $_SESSION['temp_attachments'][$attachID]['size'];
    if (!empty($modSettings['attachmentSizeLimit']) && $_SESSION['temp_attachments'][$attachID]['size'] > $modSettings['attachmentSizeLimit'] * 1024)
        $_SESSION['temp_attachments'][$attachID]['errors'][] = array('file_too_big', array(comma_format($modSettings['attachmentSizeLimit'], 0)));

    // Check the total upload size for this post...
    if (!empty($modSettings['attachmentPostLimit']) && $context['attachments']['total_size'] > $modSettings['attachmentPostLimit'] * 1024)
        $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attach_max_total_file_size', array(comma_format($modSettings['attachmentPostLimit'], 0), comma_format($modSettings['attachmentPostLimit'] - (($context['attachments']['total_size'] - $_SESSION['temp_attachments'][$attachID]['size']) / 1024), 0)));

    // Have we reached the maximum number of files we are allowed?
    $context['attachments']['quantity']++;

    // Set a max limit if none exists
    if (empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] >= 50)
        $modSettings['attachmentNumPerPostLimit'] = 50;

    if (!empty($modSettings['attachmentNumPerPostLimit']) && $context['attachments']['quantity'] > $modSettings['attachmentNumPerPostLimit'])
        $_SESSION['temp_attachments'][$attachID]['errors'][] = array('attachments_limit_per_post', array($modSettings['attachmentNumPerPostLimit']));

    // File extension check
    if (!empty($modSettings['attachmentCheckExtensions']))
    {
        $allowed = explode(',', strtolower($modSettings['attachmentExtensions']));
        foreach ($allowed as $k => $dummy)
            $allowed[$k] = trim($dummy);

        if (!in_array(strtolower(substr(strrchr($_SESSION['temp_attachments'][$attachID]['name'], '.'), 1)), $allowed))
        {
            $allowed_extensions = strtr(strtolower($modSettings['attachmentExtensions']), array(',' => ', '));
            $_SESSION['temp_attachments'][$attachID]['errors'][] = array('cant_upload_type', array($allowed_extensions));
        }
    }

    // Undo the math if there's an error
    if (!empty($_SESSION['temp_attachments'][$attachID]['errors']))
    {
        if (isset($context['dir_size']))
            $context['dir_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
        if (isset($context['dir_files']))
            $context['dir_files']--;
        $context['attachments']['total_size'] -= $_SESSION['temp_attachments'][$attachID]['size'];
        $context['attachments']['quantity']--;
        return false;
    }

    return true;
}

/**
 * Create an attachment, with the given array of parameters.
 * - Adds any additional or missing parameters to $attachmentOptions.
 * - Renames the temporary file.
 * - Creates a thumbnail if the file is an image and the option enabled.
 *
 * @param array $attachmentOptions An array of attachment options
 * @return bool Whether the attachment was created successfully
 */
function createAttachment(&$attachmentOptions)
{
    global $modSettings, $sourcedir, $smcFunc, $context, $txt;

    require_once($sourcedir . '/Subs-Graphics.php');

    // If this is an image we need to set a few additional parameters.
    $size = @getimagesize($attachmentOptions['tmp_name']);
    list ($attachmentOptions['width'], $attachmentOptions['height']) = $size;

    // If it's an image get the mime type right.
    if (empty($attachmentOptions['mime_type']) && $attachmentOptions['width'])
    {
        // Got a proper mime type?
        if (!empty($size['mime']))
            $attachmentOptions['mime_type'] = $size['mime'];

        // Otherwise a valid one?
        elseif (isset($context['valid_image_types'][$size[2]]))
            $attachmentOptions['mime_type'] = 'image/' . $context['valid_image_types'][$size[2]];
    }

    // It is possible we might have a MIME type that isn't actually an image but still have a size.
    // For example, Shockwave files will be able to return size but be 'application/shockwave' or similar.
    if (!empty($attachmentOptions['mime_type']) && strpos($attachmentOptions['mime_type'], 'image/') !== 0)
    {
        $attachmentOptions['width'] = 0;
        $attachmentOptions['height'] = 0;
    }

    // Get the hash if no hash has been given yet.
    if (empty($attachmentOptions['file_hash']))
        $attachmentOptions['file_hash'] = getAttachmentFilename($attachmentOptions['name'], false, null, true);

    // Assuming no-one set the extension let's take a look at it.
    if (empty($attachmentOptions['fileext']))
    {
        $attachmentOptions['fileext'] = strtolower(strrpos($attachmentOptions['name'], '.') !== false ? substr($attachmentOptions['name'], strrpos($attachmentOptions['name'], '.') + 1) : '');
        if (strlen($attachmentOptions['fileext']) > 8 || '.' . $attachmentOptions['fileext'] == $attachmentOptions['name'])
            $attachmentOptions['fileext'] = '';
    }

    // This defines which options to use for which columns in the insert query.
    // Mods using the hook can add columns and even change the properties of existing columns,
    // but if they delete one of these columns, it will be reset to the default defined here.
    $attachmentStandardInserts = $attachmentInserts = array(
        // Format: 'column' => array('type', 'option')
        'id_folder' => array('int', 'id_folder'),
        'id_msg' => array('int', 'post'),
        'filename' => array('string-255', 'name'),
        'file_hash' => array('string-40', 'file_hash'),
        'fileext' => array('string-8', 'fileext'),
        'size' => array('int', 'size'),
        'width' => array('int', 'width'),
        'height' => array('int', 'height'),
        'mime_type' => array('string-20', 'mime_type'),
        'approved' => array('int', 'approved'),
    );

    // Last chance to change stuff!
    call_integration_hook('integrate_createAttachment', array(&$attachmentOptions, &$attachmentInserts));

    // Make sure the folder is valid...
    $tmp = is_array($modSettings['attachmentUploadDir']) ? $modSettings['attachmentUploadDir'] : $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
    $folders = array_keys($tmp);
    if (empty($attachmentOptions['id_folder']) || !in_array($attachmentOptions['id_folder'], $folders))
        $attachmentOptions['id_folder'] = $modSettings['currentAttachmentUploadDir'];

    // Make sure all required columns are present, in case a mod screwed up.
    foreach ($attachmentStandardInserts as $column => $insert_info)
        if (!isset($attachmentInserts[$column]))
            $attachmentInserts[$column] = $insert_info;

    // Set up the columns and values to insert, in the correct order.
    $attachmentColumns = array();
    $attachmentValues = array();
    foreach ($attachmentInserts as $column => $insert_info)
    {
        $attachmentColumns[$column] = $insert_info[0];

        if (!empty($insert_info[0]) && $insert_info[0] == 'int')
            $attachmentValues[] = (int) $attachmentOptions[$insert_info[1]];
        else
            $attachmentValues[] = $attachmentOptions[$insert_info[1]];
    }

    // Create the attachment in the database.
    $attachmentOptions['id'] = $smcFunc['db_insert']('',
        '{db_prefix}attachments',
        $attachmentColumns,
        $attachmentValues,
        array('id_attach'),
        1
    );

    // Attachment couldn't be created.
    if (empty($attachmentOptions['id']))
    {
        loadLanguage('Errors');
        log_error($txt['attachment_not_created'], 'general');
        return false;
    }

    // Now that we have the attach id, let's rename this sucker and finish up.
    $attachmentOptions['destination'] = getAttachmentFilename(basename($attachmentOptions['name']), $attachmentOptions['id'], $attachmentOptions['id_folder'], false, $attachmentOptions['file_hash']);
    rename($attachmentOptions['tmp_name'], $attachmentOptions['destination']);

    // If it's not approved then add to the approval queue.
    if (!$attachmentOptions['approved'])
    {
        $smcFunc['db_insert']('',
            '{db_prefix}approval_queue',
            array(
                'id_attach' => 'int', 'id_msg' => 'int',
            ),
            array(
                $attachmentOptions['id'], (int) $attachmentOptions['post'],
            ),
            array()
        );

        // Queue background notification task.
        $smcFunc['db_insert'](
            'insert',
            '{db_prefix}background_tasks',
            array(
                'task_file' => 'string',
                'task_class' => 'string',
                'task_data' => 'string',
                'claimed_time' => 'int'
            ),
            array(
                    '$sourcedir/tasks/CreateAttachment-Notify.php',
                    'CreateAttachment_Notify_Background',
                    $smcFunc['json_encode'](
                        array(
                            'id' => $attachmentOptions['id'],
                        )
                    ),
                0
            ),
            array(
                'id_task'
            )
        );
    }

    if (empty($modSettings['attachmentThumbnails']) || (empty($attachmentOptions['width']) && empty($attachmentOptions['height'])))
        return true;

    // Like thumbnails, do we?
    if (!empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachmentOptions['width'] > $modSettings['attachmentThumbWidth'] || $attachmentOptions['height'] > $modSettings['attachmentThumbHeight']))
    {
        if (createThumbnail($attachmentOptions['destination'], $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
        {
            // Figure out how big we actually made it.
            $size = @getimagesize($attachmentOptions['destination'] . '_thumb');
            list ($thumb_width, $thumb_height) = $size;

            if (!empty($size['mime']))
                $thumb_mime = $size['mime'];
            elseif (isset($context['valid_image_types'][$size[2]]))
                $thumb_mime = 'image/' . $context['valid_image_types'][$size[2]];
            // Lord only knows how this happened...
            else
                $thumb_mime = '';

            $thumb_filename = $attachmentOptions['name'] . '_thumb';
            $thumb_size = filesize($attachmentOptions['destination'] . '_thumb');
            $thumb_file_hash = getAttachmentFilename($thumb_filename, false, null, true);
            $thumb_path = $attachmentOptions['destination'] . '_thumb';

            // We should check the file size and count here since thumbs are added to the existing totals.
            if (!empty($modSettings['automanage_attachments']) && $modSettings['automanage_attachments'] == 1 && !empty($modSettings['attachmentDirSizeLimit']) || !empty($modSettings['attachmentDirFileLimit']))
            {
                $context['dir_size'] = isset($context['dir_size']) ? $context['dir_size'] += $thumb_size : $context['dir_size'] = 0;
                $context['dir_files'] = isset($context['dir_files']) ? $context['dir_files']++ : $context['dir_files'] = 0;

                // If the folder is full, try to create a new one and move the thumb to it.
                if ($context['dir_size'] > $modSettings['attachmentDirSizeLimit'] * 1024 || $context['dir_files'] + 2 > $modSettings['attachmentDirFileLimit'])
                {
                    if (automanage_attachments_by_space())
                    {
                        rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
                        $thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
                        $context['dir_size'] = 0;
                        $context['dir_files'] = 0;
                    }
                }
            }
            // If a new folder has been already created. Gotta move this thumb there then.
            if ($modSettings['currentAttachmentUploadDir'] != $attachmentOptions['id_folder'])
            {
                rename($thumb_path, $context['attach_dir'] . '/' . $thumb_filename);
                $thumb_path = $context['attach_dir'] . '/' . $thumb_filename;
            }

            // To the database we go!
            $attachmentOptions['thumb'] = $smcFunc['db_insert']('',
                '{db_prefix}attachments',
                array(
                    'id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string-255', 'file_hash' => 'string-40', 'fileext' => 'string-8',
                    'size' => 'int', 'width' => 'int', 'height' => 'int', 'mime_type' => 'string-20', 'approved' => 'int',
                ),
                array(
                    $modSettings['currentAttachmentUploadDir'], (int) $attachmentOptions['post'], 3, $thumb_filename, $thumb_file_hash, $attachmentOptions['fileext'],
                    $thumb_size, $thumb_width, $thumb_height, $thumb_mime, (int) $attachmentOptions['approved'],
                ),
                array('id_attach'),
                1
            );

            if (!empty($attachmentOptions['thumb']))
            {
                $smcFunc['db_query']('', '
                    UPDATE {db_prefix}attachments
                    SET id_thumb = {int:id_thumb}
                    WHERE id_attach = {int:id_attach}',
                    array(
                        'id_thumb' => $attachmentOptions['thumb'],
                        'id_attach' => $attachmentOptions['id'],
                    )
                );

                rename($thumb_path, getAttachmentFilename($thumb_filename, $attachmentOptions['thumb'], $modSettings['currentAttachmentUploadDir'], false, $thumb_file_hash));
            }
        }
    }

    return true;
}

/**
 * Assigns the given attachments to the given message ID.
 *
 * @param $attachIDs array of attachment IDs to assign.
 * @param $msgID integer the message ID.
 *
 * @return boolean false on error or missing params.
 */
function assignAttachments($attachIDs = array(), $msgID = 0)
{
    global $smcFunc;

    // Oh, come on!
    if (empty($attachIDs) || empty($msgID))
        return false;

    // "I see what is right and approve, but I do what is wrong."
    call_integration_hook('integrate_assign_attachments', array(&$attachIDs, &$msgID));

    // One last check
    if (empty($attachIDs))
        return false;

    // Perform.
    $smcFunc['db_query']('', '
        UPDATE {db_prefix}attachments
        SET id_msg = {int:id_msg}
        WHERE id_attach IN ({array_int:attach_ids})',
        array(
            'id_msg' => $msgID,
            'attach_ids' => $attachIDs,
        )
    );

    return true;
}

/**
 * Gets an attach ID and tries to load all its info.
 *
 * @param int $attachID the attachment ID to load info from.
 *
 * @return mixed If succesful, it will return an array of loaded data. String, most likely a $txt key if there was some error.
 */
function parseAttachBBC($attachID = 0)
{
    global $board, $modSettings, $context, $scripturl, $smcFunc;
    static $view_attachment_boards;

    if (!isset($view_attachment_boards))
        $view_attachment_boards = boardsAllowedTo('view_attachments');

    // Meh...
    if (empty($attachID))
        return 'attachments_no_data_loaded';

    // Make it easy.
    $msgID = !empty($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : 0;

    // Perhaps someone else wants to do the honors? Yes, this also includes dealing with previews ;)
    $externalParse = call_integration_hook('integrate_pre_parseAttachBBC', array($attachID, $msgID));

    // "I am innocent of the blood of this just person: see ye to it."
    if (!empty($externalParse) && (is_string($externalParse) || is_array($externalParse)))
        return $externalParse;

    // Are attachments enabled?
    if (empty($modSettings['attachmentEnable']))
        return 'attachments_not_enable';

    // There is always the chance someone else has already done our dirty work...
    // If so, all pertinent checks were already done. Hopefully...
    if (!empty($context['current_attachments']) && !empty($context['current_attachments'][$attachID]))
        return $context['current_attachments'][$attachID];

    // If we are lucky enough to be in $board's scope then check it!
    if (!empty($board) && $view_attachment_boards !== array(0) && !in_array($board, $view_attachment_boards))
        return 'attachments_not_allowed_to_see';

    // Get the message info associated with this particular attach ID.
    $attachInfo = getAttachMsgInfo($attachID);

    // There is always the chance this attachment no longer exists or isn't associated to a message anymore...
    if (empty($attachInfo) || empty($attachInfo['msg']) && empty($context['preview_message']))
        return 'attachments_no_msg_associated';

    // Hold it! got the info now check if you can see this attachment.
    if ($view_attachment_boards !== array(0) && !in_array($attachInfo['board'], $view_attachment_boards))
        return 'attachments_not_allowed_to_see';

    if (empty($context['loaded_attachments'][$attachInfo['msg']]))
        prepareAttachsByMsg(array($attachInfo['msg']));

    if (isset($context['loaded_attachments'][$attachInfo['msg']][$attachID]))
        $attachContext = $context['loaded_attachments'][$attachInfo['msg']][$attachID];

    // In case the user manually typed the thumbnail's ID into the BBC
    elseif (!empty($context['loaded_attachments'][$attachInfo['msg']]))
    {
        foreach ($context['loaded_attachments'][$attachInfo['msg']] as $foundAttachID => $foundAttach)
        {
            if ($foundAttach['id_thumb'] == $attachID)
            {
                $attachContext = $context['loaded_attachments'][$attachInfo['msg']][$foundAttachID];
                $attachID = $foundAttachID;
                break;
            }
        }
    }

    // Load this particular attach's context.
    if (!empty($attachContext))
        $attachLoaded = loadAttachmentContext($attachContext['id_msg'], $context['loaded_attachments']);

    // One last check, you know, gotta be paranoid...
    else
        return 'attachments_no_data_loaded';

    // This is the last "if" I promise!
    if (empty($attachLoaded))
        return 'attachments_no_data_loaded';

    else
        $attachContext = $attachLoaded[$attachID];

    // No point in keep going further.
    if ($view_attachment_boards !== array(0) && !in_array($attachContext['board'], $view_attachment_boards))
        return 'attachments_not_allowed_to_see';

    // Previewing much? no msg ID has been set yet.
    if (!empty($context['preview_message']))
    {
        $attachContext['href'] = $scripturl . '?action=dlattach;attach=' . $attachID . ';type=preview';

        $attachContext['link'] = '<a href="' . $scripturl . '?action=dlattach;attach=' . $attachID . ';type=preview' . (empty($attachContext['is_image']) ? ';file' : '') . '" class="bbc_link">' . $smcFunc['htmlspecialchars']($attachContext['name']) . '</a>';

        // Fix the thumbnail too, if the image has one.
        if (!empty($attachContext['thumbnail']) && !empty($attachContext['thumbnail']['has_thumb']))
            $attachContext['thumbnail']['href'] = $scripturl . '?action=dlattach;attach=' . $attachContext['thumbnail']['id'] . ';image;type=preview';
    }

    // You may or may not want to show this under the post.
    if (!empty($modSettings['dont_show_attach_under_post']) && !isset($context['show_attach_under_post'][$attachID]))
        $context['show_attach_under_post'][$attachID] = $attachID;

    // Last minute changes?
    call_integration_hook('integrate_post_parseAttachBBC', array(&$attachContext));

    // Don't do any logic with the loaded data, leave it to whoever called this function.
    return $attachContext;
}

/**
 * Gets raw info directly from the attachments table.
 *
 * @param array $attachIDs An array of attachments IDs.
 *
 * @return array.
 */
function getRawAttachInfo($attachIDs)
{
    global $smcFunc, $modSettings;

    if (empty($attachIDs))
        return array();

    $return = array();

    $request = $smcFunc['db_query']('', '
        SELECT a.id_attach, a.id_msg, a.id_member, a.size, a.mime_type, a.id_folder, a.filename' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
            COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
        FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
            LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
        WHERE a.id_attach IN ({array_int:attach_ids})
        LIMIT 1',
        array(
            'attach_ids' => (array) $attachIDs,
        )
    );

    if ($smcFunc['db_num_rows']($request) != 1)
        return array();

    while ($row = $smcFunc['db_fetch_assoc']($request))
        $return[$row['id_attach']] = array(
            'name' => $smcFunc['htmlspecialchars']($row['filename']),
            'size' => $row['size'],
            'attachID' => $row['id_attach'],
            'unchecked' => false,
            'approved' => 1,
            'mime_type' => $row['mime_type'],
            'thumb' => $row['id_thumb'],
        );
    $smcFunc['db_free_result']($request);

    return $return;
}

/**
 * Gets all needed message data associated with an attach ID
 *
 * @param int $attachID the attachment ID to load info from.
 *
 * @return array.
 */
function getAttachMsgInfo($attachID)
{
    global $smcFunc, $context;

    if (empty($attachID))
        return array();

    if (!isset($context['loaded_attachments']))
        $context['loaded_attachments'] = array();

    foreach ($context['loaded_attachments'] as $msgRows)
    {
        if (empty($msgRows[$attachID]))
            continue;

        $row = array(
            'msg' => $msgRows[$attachID]['id_msg'],
            'topic' => $msgRows[$attachID]['topic'],
            'board' => $msgRows[$attachID]['board'],
        );

        return $row;
    }

    $request = $smcFunc['db_query']('', '
        SELECT a.id_msg AS msg, m.id_topic AS topic, m.id_board AS board
        FROM {db_prefix}attachments AS a
            LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
        WHERE id_attach = {int:id_attach}
        LIMIT 1',
        array(
            'id_attach' => (int) $attachID,
        )
    );

    if ($smcFunc['db_num_rows']($request) != 1)
        return array();

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

    return $row;
}

/**
 * This loads an attachment's contextual data including, most importantly, its size if it is an image.
 * It requires the view_attachments permission to calculate image size.
 * It attempts to keep the "aspect ratio" of the posted image in line, even if it has to be resized by
 * the max_image_width and max_image_height settings.
 *
 * @param int $id_msg ID of the post to load attachments for
 * @param array $attachments  An array of already loaded attachments. This function no longer depends on having $topic declared, thus, you need to load the actual topic ID for each attachment.
 * @return array An array of attachment info
 */
function loadAttachmentContext($id_msg, $attachments)
{
    global $modSettings, $txt, $scripturl, $sourcedir, $smcFunc, $context;

    if (empty($attachments) || empty($attachments[$id_msg]))
        return array();

    // Set up the attachment info - based on code by Meriadoc.
    $attachmentData = array();
    $have_unapproved = false;
    if (isset($attachments[$id_msg]) && !empty($modSettings['attachmentEnable']))
    {
        foreach ($attachments[$id_msg] as $i => $attachment)
        {
            $attachmentData[$i] = array(
                'id' => $attachment['id_attach'],
                'name' => preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', $smcFunc['htmlspecialchars']($attachment['filename'])),
                'downloads' => $attachment['downloads'],
                'size' => ($attachment['filesize'] < 1024000) ? round($attachment['filesize'] / 1024, 2) . ' ' . $txt['kilobyte'] : round($attachment['filesize'] / 1024 / 1024, 2) . ' ' . $txt['megabyte'],
                'byte_size' => $attachment['filesize'],
                'href' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'],
                'link' => '<a href="' . $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_attach'] . '" class="bbc_link">' . $smcFunc['htmlspecialchars']($attachment['filename']) . '</a>',
                'is_image' => !empty($attachment['width']) && !empty($attachment['height']) && !empty($modSettings['attachmentShowImages']),
                'is_approved' => $attachment['approved'],
                'topic' => $attachment['topic'],
                'board' => $attachment['board'],
                'mime_type' => $attachment['mime_type'],
            );

            // If something is unapproved we'll note it so we can sort them.
            if (!$attachment['approved'])
                $have_unapproved = true;

            if (!$attachmentData[$i]['is_image'])
                continue;

            $attachmentData[$i]['real_width'] = $attachment['width'];
            $attachmentData[$i]['width'] = $attachment['width'];
            $attachmentData[$i]['real_height'] = $attachment['height'];
            $attachmentData[$i]['height'] = $attachment['height'];

            // Let's see, do we want thumbs?
            if (!empty($modSettings['attachmentThumbnails']) && !empty($modSettings['attachmentThumbWidth']) && !empty($modSettings['attachmentThumbHeight']) && ($attachment['width'] > $modSettings['attachmentThumbWidth'] || $attachment['height'] > $modSettings['attachmentThumbHeight']) && strlen($attachment['filename']) < 249)
            {
                // A proper thumb doesn't exist yet? Create one!
                if (empty($attachment['id_thumb']) || $attachment['thumb_width'] > $modSettings['attachmentThumbWidth'] || $attachment['thumb_height'] > $modSettings['attachmentThumbHeight'] || ($attachment['thumb_width'] < $modSettings['attachmentThumbWidth'] && $attachment['thumb_height'] < $modSettings['attachmentThumbHeight']))
                {
                    $filename = getAttachmentFilename($attachment['filename'], $attachment['id_attach'], $attachment['id_folder']);

                    require_once($sourcedir . '/Subs-Graphics.php');
                    if (createThumbnail($filename, $modSettings['attachmentThumbWidth'], $modSettings['attachmentThumbHeight']))
                    {
                        // So what folder are we putting this image in?
                        if (!empty($modSettings['currentAttachmentUploadDir']))
                        {
                            if (!is_array($modSettings['attachmentUploadDir']))
                                $modSettings['attachmentUploadDir'] = $smcFunc['json_decode']($modSettings['attachmentUploadDir'], true);
                            $id_folder_thumb = $modSettings['currentAttachmentUploadDir'];
                        }
                        else
                        {
                            $id_folder_thumb = 1;
                        }

                        // Calculate the size of the created thumbnail.
                        $size = @getimagesize($filename . '_thumb');
                        list ($attachment['thumb_width'], $attachment['thumb_height']) = $size;
                        $thumb_size = filesize($filename . '_thumb');

                        // What about the extension?
                        $thumb_ext = isset($context['valid_image_types'][$size[2]]) ? $context['valid_image_types'][$size[2]] : '';

                        // Figure out the mime type.
                        if (!empty($size['mime']))
                            $thumb_mime = $size['mime'];
                        else
                            $thumb_mime = 'image/' . $thumb_ext;

                        $thumb_filename = $attachment['filename'] . '_thumb';
                        $thumb_hash = getAttachmentFilename($thumb_filename, false, null, true);
                        $old_id_thumb = $attachment['id_thumb'];

                        // Add this beauty to the database.
                        $attachment['id_thumb'] = $smcFunc['db_insert']('',
                            '{db_prefix}attachments',
                            array('id_folder' => 'int', 'id_msg' => 'int', 'attachment_type' => 'int', 'filename' => 'string', 'file_hash' => 'string', 'size' => 'int', 'width' => 'int', 'height' => 'int', 'fileext' => 'string', 'mime_type' => 'string'),
                            array($id_folder_thumb, $id_msg, 3, $thumb_filename, $thumb_hash, (int) $thumb_size, (int) $attachment['thumb_width'], (int) $attachment['thumb_height'], $thumb_ext, $thumb_mime),
                            array('id_attach'),
                            1
                        );

                        if (!empty($attachment['id_thumb']))
                        {
                            $smcFunc['db_query']('', '
                                UPDATE {db_prefix}attachments
                                SET id_thumb = {int:id_thumb}
                                WHERE id_attach = {int:id_attach}',
                                array(
                                    'id_thumb' => $attachment['id_thumb'],
                                    'id_attach' => $attachment['id_attach'],
                                )
                            );

                            $thumb_realname = getAttachmentFilename($thumb_filename, $attachment['id_thumb'], $id_folder_thumb, false, $thumb_hash);
                            rename($filename . '_thumb', $thumb_realname);

                            // Do we need to remove an old thumbnail?
                            if (!empty($old_id_thumb))
                            {
                                require_once($sourcedir . '/ManageAttachments.php');
                                removeAttachments(array('id_attach' => $old_id_thumb), '', false, false);
                            }
                        }
                    }
                }

                // Only adjust dimensions on successful thumbnail creation.
                if (!empty($attachment['thumb_width']) && !empty($attachment['thumb_height']))
                {
                    $attachmentData[$i]['width'] = $attachment['thumb_width'];
                    $attachmentData[$i]['height'] = $attachment['thumb_height'];
                }
            }

            if (!empty($attachment['id_thumb']))
                $attachmentData[$i]['thumbnail'] = array(
                    'id' => $attachment['id_thumb'],
                    'href' => $scripturl . '?action=dlattach;topic=' . $attachment['topic'] . '.0;attach=' . $attachment['id_thumb'] . ';image',
                );
            $attachmentData[$i]['thumbnail']['has_thumb'] = !empty($attachment['id_thumb']);

            // If thumbnails are disabled, check the maximum size of the image.
            if (!$attachmentData[$i]['thumbnail']['has_thumb'] && ((!empty($modSettings['max_image_width']) && $attachment['width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachment['height'] > $modSettings['max_image_height'])))
            {
                if (!empty($modSettings['max_image_width']) && (empty($modSettings['max_image_height']) || $attachment['height'] * $modSettings['max_image_width'] / $attachment['width'] <= $modSettings['max_image_height']))
                {
                    $attachmentData[$i]['width'] = $modSettings['max_image_width'];
                    $attachmentData[$i]['height'] = floor($attachment['height'] * $modSettings['max_image_width'] / $attachment['width']);
                }
                elseif (!empty($modSettings['max_image_width']))
                {
                    $attachmentData[$i]['width'] = floor($attachment['width'] * $modSettings['max_image_height'] / $attachment['height']);
                    $attachmentData[$i]['height'] = $modSettings['max_image_height'];
                }
            }
            elseif ($attachmentData[$i]['thumbnail']['has_thumb'])
            {
                // If the image is too large to show inline, make it a popup.
                if (((!empty($modSettings['max_image_width']) && $attachmentData[$i]['real_width'] > $modSettings['max_image_width']) || (!empty($modSettings['max_image_height']) && $attachmentData[$i]['real_height'] > $modSettings['max_image_height'])))
                    $attachmentData[$i]['thumbnail']['javascript'] = 'return reqWin(\'' . $attachmentData[$i]['href'] . ';image\', ' . ($attachment['width'] + 20) . ', ' . ($attachment['height'] + 20) . ', true);';
                else
                    $attachmentData[$i]['thumbnail']['javascript'] = 'return expandThumb(' . $attachment['id_attach'] . ');';
            }

            if (!$attachmentData[$i]['thumbnail']['has_thumb'])
                $attachmentData[$i]['downloads']++;
        }
    }

    // Do we need to instigate a sort?
    if ($have_unapproved)
        uasort($attachmentData, function($a, $b)
        {
            if ($a['is_approved'] == $b['is_approved'])
                return 0;

            return $a['is_approved'] > $b['is_approved'] ? -1 : 1;
        });

    return $attachmentData;
}

/**
 * prepare the Attachment api for all messages
 *
 * @param int array $msgIDs the message ID to load info from.
 *
 * @return void.
 */
function prepareAttachsByMsg($msgIDs)
{
    global $context, $modSettings, $smcFunc, $user_info;

    if (empty($context['loaded_attachments']))
        $context['loaded_attachments'] = array();
    // Remove all $msgIDs that we already processed
    else
        $msgIDs = array_diff($msgIDs, array_keys($context['loaded_attachments']), array(0));

    if (!empty($context['preview_message']))
        $msgIDs[] = 0;

    if (!empty($msgIDs))
    {
        $request = $smcFunc['db_query']('', '
            SELECT
                a.id_attach, a.id_folder, a.id_msg, a.filename, a.file_hash, COALESCE(a.size, 0) AS filesize, a.downloads, a.approved, m.id_topic AS topic, m.id_board AS board, m.id_member, a.mime_type,
                a.width, a.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
                COALESCE(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
            FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
                LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
                LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_msg)
            WHERE a.attachment_type = {int:attachment_type}
                AND a.id_msg IN ({array_int:message_id})',
            array(
                'message_id' => $msgIDs,
                'attachment_type' => 0,
            )
        );
        $rows = $smcFunc['db_fetch_all']($request);
        $smcFunc['db_free_result']($request);

        foreach ($rows as $row)
        {
            // Skip unapproved ones, unless they belong to the user or the user can approve them.
            if (!$row['approved'] && $modSettings['postmod_active'] && !allowedTo('approve_posts') && $row['id_member'] != $user_info['id'])
                continue;

            if (empty($context['loaded_attachments'][$row['id_msg']]))
                $context['loaded_attachments'][$row['id_msg']] = array();

            $context['loaded_attachments'][$row['id_msg']][$row['id_attach']] = $row;

            // This is better than sorting it with the query...
            ksort($context['loaded_attachments'][$row['id_msg']]);
        }
    }
}

?>
API documentation generated by ApiGen