// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../clike/clike"));
    else if (typeof define == "function" && define.amd) // AMD
        define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod);
    else // Plain browser env
        mod(CodeMirror);
})(function(CodeMirror) {
    "use strict";

    function keywords(str) {
        var obj = {}, words = str.split(" ");
        for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
        return obj;
    }

    // Helper for stringWithEscapes
    function matchSequence(list, end) {
        if (list.length == 0) return stringWithEscapes(end);
        return function (stream, state) {
            var patterns = list[0];
            for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) {
                state.tokenize = matchSequence(list.slice(1), end);
                return patterns[i][1];
            }
            state.tokenize = stringWithEscapes(end);
            return "string";
        };
    }
    function stringWithEscapes(closing) {
        return function(stream, state) { return stringWithEscapes_(stream, state, closing); };
    }
    function stringWithEscapes_(stream, state, closing) {
        // "Complex" syntax
        if (stream.match("${", false) || stream.match("{$", false)) {
            state.tokenize = null;
            return "string";
        }

        // Simple syntax
        if (stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) {
            // After the variable name there may appear array or object operator.
            if (stream.match("[", false)) {
                // Match array operator
                state.tokenize = matchSequence([
                    [["[", null]],
                    [[/\d[\w\.]*/, "number"],
                        [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"],
                        [/[\w\$]+/, "variable"]],
                    [["]", null]]
                ], closing);
            }
            if (stream.match(/\-\>\w/, false)) {
                // Match object operator
                state.tokenize = matchSequence([
                    [["->", null]],
                    [[/[\w]+/, "variable"]]
                ], closing);
            }
            return "variable-2";
        }

        var escaped = false;
        // Normal string
        while (!stream.eol() &&
        (escaped || (!stream.match("{$", false) &&
        !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) {
            if (!escaped && stream.match(closing)) {
                state.tokenize = null;
                state.tokStack.pop(); state.tokStack.pop();
                break;
            }
            escaped = stream.next() == "\\" && !escaped;
        }
        return "string";
    }

    var phpKeywords = "abstract and array as break case catch class clone const continue declare default " +
        "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " +
        "for foreach function global goto if implements interface instanceof namespace " +
        "new or private protected public static switch throw trait try use var while xor " +
        "die echo empty exit eval include include_once isset list require require_once return " +
        "print unset __halt_compiler self static parent yield insteadof finally";
    var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__" +
        " $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV $HTTP_RAW_POST_DATA $http_response_header $argc $argv";
    // var phpBuiltin = "abs acos acosh addcslashes addslashes apache_child_terminate getenv get_modules get_version lookup_uri note request_headers reset_timeout response_headers setenv cu_add cache_info cas clear_cache dec delete entry exists fetch inc sma_info store c_add bin_dump dumpfile load loadfile cache_info cas clear_cache compile_file dec fine_constants lete lete_file exists fetch inc load_constants sma_info store d_breakpoint callstack clunk continue croak dump_function_table dump_persistent_resources dump_regular_resources echo get_active_symbols set_pprof_trace session session_trace session_trace_socket array _change_key_case hunk olumn ombine ount_values _diff _assoc _key _uassoc _ukey _fill ill_keys ilter lip _intersect _assoc _key _uassoc _ukey _keys _exists _first _last _map erge erge_recursive ultisort _pad op roduct ush _rand educe eplace eplace_recursive everse _search hift lice plice um _udiff diff_assoc diff_uassoc intersect intersect_assoc intersect_uassoc nique nshift _values _walk _walk_recursive sort asin inh ort sert sert_options atan atan2 atanh base64_decode 64_encode name _convert bbcode_add_element add_smiley create destroy parse set_arg_parser set_flags bcadd comp div mod mul ompiler_load load_exe parse_class read write_class constant exe_footer file footer function functions_from_file header included_filename pow powmod scale sqrt sub bin2hex dec dtextdomain d_textdomain_codeset blenc_encrypt boolval bson_decode bson_encode bzclose compress decompress errno error errstr flush open read write cairo_create font_options_create equal get_antialias hint_metrics hint_style subpixel_order hash merge set_antialias hint_metrics hint_style subpixel_order status rmat_stride_for_width image_surface_create create_for_data create_from_png get_data format height stride width matrix_create_scale create_translate invert multiply transform_distance transform_point translate pattern_add_color_stop_rgb add_color_stop_rgba create_for_surface linear radial rgb rgba get_color_stop_count color_stop_rgba extend filter linear_points matrix radial_circles rgba surface type set_extend set_filter set_matrix status pdf_surface_create pdf_surface_set_size ps_get_levels level_to_string surface_create dsc_begin_page_setup dsc_begin_setup dsc_comment get_eps restrict_to_level set_eps set_size scaled_font_create extents get_ctm font_face font_matrix font_options scale_matrix type glyph_extents status text_extents surface_copy_page create_similar finish flush get_content device_offset font_options type mark_dirty mark_dirty_rectangle set_device_offset set_fallback_resolution show_page status write_to_png svg_surface_create svg_surface_restrict_to_version svg_version_to_string ll_user_func func_array method method_array l_days_in_month from_jd info to_jd ceil chdb_create dir eckdate eckdnsrr grp mod op own r root unk_split classkit_import method_add copy redefine remove rename _alias _exists _implements _parents _uses earstatcache i_get_process_title i_set_process_title osedir oselog compact m_create_guid event_sink get_active_object load_typelib message_pump print_typeinfo nnection_aborted nnection_status nstant nvert_cyr_string nvert_uudecode nvert_uuencode py s sh unt unt_chars crack_check closedict getlastmessage opendict c32 eate_function ypt ctype_alnum alpha cntrl digit graph lower print punct space upper xdigit cubrid_affected_rows bind client_encoding ose ose_prepare ose_request column_names lumn_types l_get l_size mmit nnect nnect_with_url current_oid data_seek db_name disconnect drop errno or _code _code_facility _msg execute fetch _array _assoc _field _lengths _object _row field_flags len name seek table type free_result get _autocommit _charset _class_name _client_info _db_parameter _query_timeout _server_info insert_id is_instance list_dbs load_from_glo b2_bind close export import new read seek seek64 size size64 tell tell64 write b_close export get send size ck_read ck_write move_cursor new_glo next_result num_cols num_fields num_rows pconnect pconnect_with_url ping prepare put query real_escape_string result rollback save_to_glo schema send_glo q_drop q_insert q_put t_add autocommit db_parameter drop query_timeout unbuffered_query version rl_close copy_handle errno error escape exec getinfo init multi_add_handle close errno exec getcontent info_read init remove_handle select setopt strerror pause reset setopt setopt_array share_close errno init setopt strerror strerror unescape version rrent cyrus_authenticate bind close connect query unbind date _add _create _from_format _immutable _immutable_from_format _date_set efault_timezone_get efault_timezone_set iff _format _get_last_errors _interval_create_from_date_string _interval_format _isodate_set _modify _offset_get _parse _parse_from_format _sub nrise nset n_info _timestamp_get stamp_set zone_get zone_set _set db2_autocommit bind_param client_info close columns lumn_privileges mmit nnect nn_error nn_errormsg cursor_type escape_string exec execute fetch_array assoc both object row field_display_size name num precision scale type width foreign_keys free_result free_stmt get_option last_insert_id lob_read next_result num_fields num_rows pclose pconnect prepare imary_keys ocedures ocedure_columns result rollback server_info set_option special_columns statistics stmt_error stmt_errormsg tables table_privileges ase_add_record close create delete_record get_header_info get_record get_record_with_names numfields numrecords open pack replace_record a_close delete exists fetch firstkey handlers insert key_split list nextkey open optimize popen replace sync plus_add aql chdir close curr errcode errno find first flush freealllocks freelock freerlocks getlock getunique info last lockrel next open prev rchperm reate rtexact rtlike resolve restorepos rkeys ropen rquery rrename rsecindex runlink rzap savepos setindex setindexbynumber sql tcl tremove undo doprepare lockrel select update xlockrel xunlockrel x_close compare connect error escape_string fetch_row query sort dcgettext dcngettext debug_backtrace bug_print_backtrace bug_zval_dump cbin chex coct fine fined fine_syslog_variables flate_add flate_init g2rad lete dgettext die o_close fcntl open read seek stat tcsetattr truncate write r rname skfreespace sk_free_space sk_total_space dl dngettext s_check_record s_get_mx s_get_record dom_import_simplexml doubleval each easter_date easter_days echo eio_busy cancel chmod chown close custom dup2 event_loop fallocate fchmod fchown fdatasync fstat fstatvfs fsync ftruncate futime get_event_stream get_last_error grp _add _cancel _limit init link lstat mkdir mknod nop npending nready nreqs nthreads open poll read ahead dir link alpath name rmdir seek ndfile t_max_idle parallel poll_reqs poll_time in_parallel stat statvfs symlink nc ncfs nc_file_range truncate unlink utime write empty enchant_broker_describe dict_exists free free_dict get_dict_path get_error init list_dicts request_dict request_pwl_dict set_dict_path set_ordering dict_add_to_personal add_to_session check describe get_error is_in_session quick_check store_replacement suggest d ereg i i_replace _replace ror_clear_last get_last log reporting escapeshellarg escapeshellcmd eval ent_base_free loop loopbreak loopexit new priority_init reinit set buffer_base_set disable enable fd_set free new priority_set read set_callback timeout_set watermark_set write new priority_set timer_add del new set exec if_imagetype read_data tagname thumbnail it p pect_expectl pect_popen plode pm1 pression tension_loaded tract ezmlm_hash fam_cancel_monitor close monitor_collection monitor_directory monitor_file next_event open pending resume_monitor suspend_monitor nn_cascadetrain_on_data cascadetrain_on_file clear_scaling_params copy create_from_file shortcut shortcut_array sparse sparse_array standard standard_array train train_from_callback descale_input cale_output cale_train troy troy_train duplicate_train_data get_activation_function activation_steepness bias_array bit_fail bit_fail_limit cascade_activation_functions functions_count steepnesses steepnesses_count candidate_change_fraction candidate_limit candidate_stagnation_epochs max_cand_epochs max_out_epochs min_cand_epochs min_out_epochs num_candidates num_candidate_groups output_change_fraction output_stagnation_epochs weight_multiplier connection_array connection_rate errno errstr layer_array learning_momentum learning_rate MSE network_type num_input num_layers num_output quickprop_decay quickprop_mu rprop_decrease_factor lta_max lta_min lta_zero increase_factor sarprop_step_error_shift step_error_threshold_factor temperature weight_decay_shift total_connections total_neurons training_algorithm train_error_function train_stop_function init_weights length_train_data merge_train_data num_input_train_data num_output_train_data print_error randomize_weights read_train_from_file set_errno set_errstr set_MSE run save save_train scale_input input_train_data output output_train_data train train_data set_activation_function _hidden _layer _output steepness _hidden _layer _output bit_fail_limit callback scade_activation_functions activation_steepnesses candidate_change_fraction candidate_limit candidate_stagnation_epochs max_cand_epochs max_out_epochs min_cand_epochs min_out_epochs num_candidate_groups output_change_fraction output_stagnation_epochs weight_multiplier error_log input_scaling_params learning_momentum learning_rate output_scaling_params quickprop_decay quickprop_mu rprop_decrease_factor lta_max lta_min lta_zero increase_factor sarprop_step_error_shift step_error_threshold_factor temperature weight_decay_shift scaling_params training_algorithm train_error_function train_stop_function weight weight_array shuffle_train_data subset_train_data test test_data train _epoch _on_data _on_file stcgi_finish_request fbsql_affected_rows autocommit blob_size change_user clob_size close commit connect create_blob create_clob create_db database database_password data_seek db_query db_status drop_db errno error fetch_array assoc field lengths object row field_flags len name seek table type free_result get_autostart_info hostname insert_id list_dbs list_fields list_tables next_result num_fields num_rows password pconnect query read_blob read_clob result rollback rows_fetched select_db t_characterset lob_mode password transaction start_db stop_db tablename table_name username warnings fclose fdf_add_doc_javascript add_template close create enum_values errno error get_ap attachment encoding file flags opt status value version header next_field_name open open_string remove_item save save_string set_ap encoding file flags javascript_action on_import_javascript opt status submit_form_action target_frame value version feof fflush fgetc csv s ss file atime ctime group inode mtime owner perms pro _fieldcount name type width _retrieve _rowcount size type _exists _get_contents _put_contents lter_has_var id input input_array list var var_array nfo_close nfo_open floatval ock oor ush fmod fnmatch fopen forward_static_call forward_static_call_array fpassthru rintf utcsv uts fread frenchtojd fribidi_log2vis fscanf eek ockopen tat ftell ok p_alloc append cdup chdir chmod close connect delete exec fget fput get get_option login mdtm mkdir mlsd nb_continue fget fput get put nlist pasv put pwd quit raw rawlist rename rmdir set_option site size ssl_connect systype runcate function_exists _get_arg _get_args _num_args fwrite gc_collect_cycles disable enable enabled mem_caches gd_info geoip_asnum_by_name continent_code_by_name untry_code3_by_name untry_code_by_name untry_name_by_name database_info db_avail db_filename db_get_all_info domain_by_name id_by_name isp_by_name netspeedcell_by_name org_by_name record_by_name region_by_name region_name_by_code setup_custom_directory time_zone_by_country_and_region tallheaders tcwd tdate tenv thostbyaddr byname bynamel name timagesize timagesizefromstring tlastmod tmxrr ygid yinode ypid yuid topt tprotobyname tprotobynumber trandmax trusage tservbyname tservbyport tSession ttext ttimeofday ttype t_browser called_class cfg_var class class_methods class_vars current_user declared_classes clared_interfaces clared_traits fined_constants fined_functions fined_vars extension_funcs headers html_translation_table included_files include_path loaded_extensions magic_quotes_gpc magic_quotes_runtime meta_tags object_vars parent_class required_files resources resource_type glob gmdate mktime p_abs add and clrbit cmp com div exact _q _qr _r export fact gcd gcdext hamdist import init intval invert jacobi legendre mod mul neg nextprime or perfect_square popcount pow powm prob_prime random _bits _range _seed root rootrem scan0 scan1 setbit sign sqrt sqrtrem strval sub testbit xor strftime gnupg_adddecryptkey addencryptkey addsignkey cleardecryptkeys clearencryptkeys clearsignkeys decrypt decryptverify encrypt encryptsign export geterror getprotocol import init keyinfo setarmor seterrormode setsignmode sign verify gopher_parsedir grapheme_extract stripos istr len pos ripos rpos str substr egoriantojd gupnp_context_get_host_ip get_port get_subscription_timeout host_path new set_subscription_timeout timeout_add unhost_path rol_point_browse_start browse_stop callback_set new device_action_callback_set device_info_get device_info_get_service root_device_get_available get_relative_location new set_available start stop service_action_get return return_error set freeze_notify info_get info_get_introspection introspection_get_state_variable notify proxy_action_get action_set add_notify callback_set get_subscribed remove_notify set_subscribed thaw_notify gzclose compress decode deflate encode eof file getc gets getss inflate open passthru puts read rewind seek tell uncompress write hash _algos _copy _equals _file _final _hkdf mac mac_algos mac_file _init _pbkdf2 _update _update_file _update_stream header s_list s_sent _register_callback _remove brev brevc x2bin xdec highlight_file highlight_string hrtime htmlentities specialchars specialchars_decode _entity_decode tp_build_query tp_response_code hwapi_attribute_new content_new hgcsp object_new hypot ibase_add_user affected_rows backup blob_add cancel close create echo get import info open close commit commit_ret connect db_info delete_user drop_db errcode errmsg execute fetch_assoc fetch_object fetch_row field_info free_event_handler free_query free_result gen_id maintain_db modify_user name_result num_fields num_params param_info pconnect prepare query restore rollback rollback_ret server_info rvice_attach rvice_detach t_event_handler trans wait_event iconv _get_encoding _mime_decode _mime_decode_headers _mime_encode _set_encoding trlen trpos trrpos ubstr id3_get_frame_long_name frame_short_name genre_id genre_list genre_name tag version remove_tag set_tag ate n_to_ascii n_to_utf8 ifxus_close_slob create_slob free_slob open_slob read_slob seek_slob tell_slob write_slob _affected_rows _blobinfile_mode _byteasvarchar _close onnect opy_blob reate_blob reate_char _do _error _errormsg _fetch_row ieldproperties ieldtypes ree_blob ree_char ree_result _getsqlca _get_blob _get_char _htmltbl_result _nullformat _num_fields _num_rows _pconnect _prepare _query _textasvarchar _update_blob _update_char ignore_user_abort iis_add_server get_dir_security script_map server_by_comment er_by_path er_rights ice_state remove_server set_app_settings dir_security script_map server_rights start_server art_service op_server op_service image2wbmp affine affinematrixconcat affinematrixget alphablending antialias arc bmp char charup colorallocate allocatealpha at closest closestalpha closesthwb deallocate exact exactalpha match resolve resolvealpha set sforindex stotal transparent nvolution py merge mergegray resampled resized create frombmp gd gd2 gd2part gif jpeg png string wbmp webp xbm xpm truecolor op opauto dashedline destroy ellipse fill ledarc ellipse polygon rectangle ltoborder ter flip fontheight fontwidth ftbbox fttext gammacorrect gd gd2 getclip gif grabscreen grabwindow interlace istruecolor jpeg layereffect line loadfont openpolygon palettecopy palettetotruecolor png polygon psbbox encodefont extendfont freefont loadfont slantfont text rectangle resolution rotate savealpha scale setbrush clip interpolation pixel style thickness tile string stringup sx sy truecolortopalette ttfbbox ttftext types wbmp webp xbm _type_to_extension _type_to_mime_type ap_8bit alerts append base64 binary body bodystruct check clearflag_full close create createmailbox delete deletemailbox errors expunge fetchbody header mime structure text _overview gc getacl mailboxes subscribed _quota _quotaroot header headerinfo headers last_error list mailbox scan subscribed lsub mail boxmsginfo _compose _copy _move mime_header_decode msgno mutf7_to_utf8 num_msg num_recent open ping qprint rename renamemailbox reopen rfc822_parse_adrlist rfc822_parse_headers rfc822_write_address savebody scan scanmailbox search tacl tflag_full t_quota sort status subscribe thread timeout uid undelete unsubscribe utf7_decode 7_encode 8 8_to_mutf7 plode port_request_variables inclued_get_data et_ntop et_pton flate_add get_read_len get_status init gres_autocommit autocommit_state charset close commit connect cursor errno error errsqlstate escape_string execute fetch_array assoc object proc_return row field_length name nullable precision scale type free_result next_error num_fields num_rows pconnect prepare query result_seek rollback set_environment unbuffered_query i_alter get get_all restore set otify_add_watch init queue_len read rm_watch tdiv terface_exists tl_error_name get_error_code get_error_message is_failure tval _array ip2long iptcembed iptcparse isset _a _array _bool _callable _countable _dir _double _executable _file _finite _float _infinite nt nteger terable _link _long _nan _null _numeric _object _readable _real _resource _scalar oap_fault tring ubclass_of _tainted _uploaded_file _writable _writeable iterator_apply iterator_count iterator_to_array jddayofweek monthname tofrench gregorian jewish julian unix jewishtojd join jpeg2wbmp json_decode encode last_error last_error_msg judy_type judy_version juliantojd kadm5_chpass_principal create_principal delete_principal destroy flush get_policies get_principal get_principals init_with_password modify_principal key key_exists krsort ksort lcfirst g_value hgrp hown ldap_8859_to_t61 add bind close compare nnect ntrol_paged_result ntrol_paged_result_response unt_entries delete dn2ufn err2str errno error escape exop _passwd _refresh _whoami plode_dn first_attribute first_entry first_reference free_result get_attributes dn entries option values values_len list modify ify_batch _add _del _replace next_attribute next_entry next_reference parse_exop parse_reference parse_result read rename sasl_bind search set_option set_rebind_proc sort start_tls t61_to_8859 unbind levenshtein libxml_clear_errors disable_entity_loader get_errors get_last_error set_external_entity_loader set_streams_context use_internal_errors nk nkinfo st localeconv caltime g g1p g10 g_cmd_delete cmd_insert cmd_update getmore killcursor reply write_batch ng2ip lstat ltrim lzf_compress lzf_decompress lzf_optimized_for magic_quotes_runtime il parse_determine_best_xfer_encoding msg_create extract_part extract_part_file extract_whole_part_file free get_part get_part_data get_structure parse parse_file rfc822_parse_addresses stream_encode uudecode_all in x xdb_affected_rows autocommit bind_param bind_result change_user character_set_name client_encoding close close_long_data commit nnect nnect_errno nnect_error data_seek debug disable_reads_from_master disable_rpl_parse dump_debug_info embedded_connect enable_reads_from_master enable_rpl_parse errno error escape_string execute fetch _array _assoc _field _fields _field_direct _lengths _object _row field_count field_seek field_tell free_result get_client_info client_version host_info metadata proto_info server_info server_version info init insert_id kill master_query more_results multi_query next_result num_fields num_rows options param_count ping prepare query real_connect al_escape_string al_query port rollback rpl_parse_enabled rpl_probe rpl_query_type select_db nd_long_data nd_query rver_end rver_init t_opt sqlstate ssl_set stat mt_affected_rows bind_param bind_result close close_long_data data_seek errno error execute fetch free_result init num_rows param_count prepare reset result_metadata send_long_data sqlstate store_result ore_result thread_id thread_safe use_result warning_count mb_check_encoding chr convert_case encoding kana variables decode_mimeheader code_numericentity tect_encoding tect_order encode_mimeheader encode_numericentity encoding_aliases ereg i i_replace _match _replace _replace_callback _search _getpos _getregs _init _pos _regs _setpos get_info http_input http_output internal_encoding language list_encodings ord output_handler parse_str preferred_mime_name regex_encoding regex_set_options scrub send_mail split strcut imwidth ipos istr len pos rchr richr ripos rpos str tolower toupper width substitute_character substr substr_count mcrypt_cbc cfb create_iv decrypt ecb encrypt _get_algorithms_name block_size iv_size key_size modes_name supported_key_sizes _is_block_algorithm _is_block_algorithm_mode _is_block_mode _self_test generic _deinit _end _init t_block_size cipher_name iv_size key_size list_algorithms list_modes module_close get_algo_block_size get_algo_key_size get_supported_key_sizes is_block_algorithm is_block_algorithm_mode is_block_mode open self_test ofb md5 md5_file mdecrypt_generic memcache_debug mory_get_peak_usage mory_get_usage taphone thod_exists mhash _count _get_block_size _get_hash_name _keygen_s2k microtime me_content_type n ng_keypress setcubicthreshold setscale setswfcompression useconstants useswfversion mkdir mktime money_format move_uploaded_file mqseries_back begin close cmit conn connx disc get inq open put put1 set strerror msession_connect count create destroy disconnect find get get_array get_data inc list listvar lock plugin randstr set set_array set_data timeout uniq unlock g_get_queue queue_exists receive remove_queue send set_queue stat_queue ql _affected_rows _close onnect reatedb reate_db _data_seek bname b_query rop_db _error _fetch_array field object row ieldflags len name table type _flags _len _name _seek _table _type ree_result _list_dbs _list_fields _list_tables _numfields rows _fields _rows _pconnect _query _regcase _result _select_db _tablename sql_bind close connect data_seek execute fetch_array assoc batch field object row field_length name seek type free_result free_statement get_last_message guid_string init min_error_severity min_message_severity next_result num_fields num_rows pconnect query result rows_affected select_db mt_getrandmax mt_rand mt_srand mysqli_bind_param bind_result client_encoding connect disable_rpl_parse enable_reads_from_master enable_rpl_parse escape_string execute fetch get_cache_stats client_stats links_stats metadata master_query param_count report rpl_parse_enabled rpl_probe send_long_data slave_query nd_memcache_get_config memcache_set ms_dump_servers fabric_select_global fabric_select_shard get_last_gtid get_last_used_connection get_stats match_wild query_is_select set_qos set_user_pick_server xa_begin commit gc rollback qc_clear_cache get_available_handlers cache_info core_stats normalized_query_trace_log query_trace_log set_cache_condition is_select storage_handler user_handlers uh_convert_to_mysqlnd uh_set_connection_proxy uh_set_statement_proxy _affected_rows _client_encoding lose onnect reate_db _data_seek b_name b_query rop_db _errno _error _escape_string _fetch_array assoc field lengths object row ield_flags len name seek table type ree_result _get_client_info host_info proto_info server_info _info _insert_id _list_dbs fields processes tables _num_fields _num_rows _pconnect _ping _query _real_escape_string _result _select_db _set_charset _stat _tablename _thread_id _unbuffered_query m_checkstatus completeauthorizations connect connectionerror deletetrans destroyconn destroyengine getcell cellbynum commadelimited header initconn initengine iscommadelimited maxconntimeout monitor numcolumns numrows parsecommadelimited responsekeys responseparam returnstatus setblocking dropfile ip ssl ssl_cafile ssl_files timeout sslcert_gen_hash transactionssent inqueue keyval new send uwait validateidentifier verifyconnection verifysslcert natcasesort natsort ncurses_addch chnstr chstr nstr str assume_default_colors attroff attron attrset baudrate beep bkgd bkgdset border bottom_panel can_change_color cbreak clear clrtobot clrtoeol color_content color_set curs_set define_key f_prog_mode f_shell_mode lay_output lch leteln lwin l_panel doupdate echo echochar end erase erasechar filter flash flushinp getch maxyx mouse yx halfdelay s_colors ic il key hide_panel hline inch it it_color it_pair sch sdelln sertln sstr str isendwin keyok keypad killchar longname meta mouseinterval usemask use_trafo ve ve_panel mvaddch chnstr chstr nstr str cur delch getch hline inch vline waddstr napms newpad newwin new_panel nl nocbreak echo nl qiflush raw pair_content nel_above nel_below nel_window pnoutrefresh prefresh putp qiflush raw refresh place_panel setty set_prog_mode set_shell_mode savetty scrl _dump _init _restore _set show_panel slk_attr off on set clear color init noutrefresh refresh restore set touch standend standout start_color termattrs termname timeout top_panel typeahead ungetch ungetmouse update_panels use_default_colors use_env use_extended_names vidattr vline waddch ddstr ttroff ttron ttrset wborder wclear wcolor_set werase wgetch whline wmouse_trafo wmove wnoutrefresh wrefresh wstandend wstandout wvline newt_bell button button_bar centered_window checkbox _get_value _set_flags _set_value _tree _add_item _find_item _get_current entry_value multi_selection selection _multi _set_current entry entry_value width clear_key_buffer cls compact_button component_add_callback component_takes_focus create_grid cursor_off cursor_on delay draw_form draw_root_text entry _get_value _set _set_filter _set_flags finished form _add_component _add_components _add_hot_key _destroy _get_current _run _set_background height size timer width _watch_fd get_screen_size grid_add_components_to_form basic_window free get_size h_close_stacked h_stacked place set_field simple_window v_close_stacked v_stacked wrapped_window wrapped_window_at init label label_set_text listbox _append_entry _clear _clear_selection _delete_entry _get_current _get_selection _insert_entry _item_count _select_item t_current current_by_key data entry width item item_get_data item_set open_window pop_help_line pop_window push_help_line radiobutton radio_get_current redraw_help_line flow_text fresh size_screen sume run_form scale scale_set scrollbar_set set_help_callback set_suspend_callback suspend textbox _get_num_lines _reflowed _set_height _set_text vertical_scrollbar wait_for_key win_choice entries menu message messagev ternary xt ngettext nl2br nl_langinfo nsapi_request_headers nsapi_response_headers nsapi_virtual number_format oauth_get_sbs oauth_urlencode ob_clean end_clean end_flush flush get_clean contents flush length level status gzhandler iconv_handler implicit_flush list_handlers start tidyhandler ocibindbyname icancel loselob ollappend lassign lassignelem lgetelem lmax lsize ltrim umnisnull name precision scale size type typeraw ommit idefinebyname ierror iexecute ifetch etchinto etchstatement reecollection cursor desc statement iinternaldebug iloadlob ilogoff ilogon inewcollection ewcursor ewdescriptor logon umcols iparse iplogon iresult irollback irowcount isavelob avelobfile erverversion etprefetch tatementtype iwritelobtofile iwritetemporarylob i_bind_array_by_name bind_by_name cancel client_version close commit connect define_by_name error execute fetch _all _array _assoc _object _row field_is_null name precision scale size type type_raw free_descriptor free_statement get_implicit_resultset internal_debug lob_copy lob_is_equal new_collection connect cursor descriptor num_fields num_rows parse password_change pconnect register_taf_callback result rollback server_version t_action client_identifier client_info edition module_name prefetch statement_type unregister_taf_callback tdec odbc_autocommit binmode close close_all columnprivileges lumns mmit nnect cursor data_source do error errormsg exec execute fetch_array into object row field_len name num precision scale type foreignkeys free_result gettypeinfo longreadlen next_result num_fields num_rows pconnect prepare imarykeys ocedurecolumns ocedures result result_all rollback setoption specialcolumns statistics tableprivileges tables opcache_compile_file get_configuration get_status invalidate is_script_cached reset enal_buffer_create data destroy get loadwav context_create current destroy process suspend device_close device_open listener_get listener_set source_create destroy get pause play rewind set stop stream dir log ssl_cipher_iv_length csr_export export_to_file get_public_key get_subject new sign decrypt dh_compute_key digest encrypt error_string free_key get_cert_locations cipher_methods curve_names md_methods privatekey publickey open pbkdf2 pkcs7_decrypt encrypt read sign verify 12_export 12_export_to_file 12_read ey_export export_to_file free get_details get_private get_public new private_decrypt private_encrypt public_decrypt public_encrypt random_pseudo_bytes seal sign spki_export export_challenge new verify verify x509_checkpurpose check_private_key export export_to_file fingerprint free parse read ord output_add_rewrite_var output_reset_rewrite_vars override_function pack rsekit_compile_file kit_compile_string kit_func_arginfo _ini_file _ini_string _str _url ssthru word_get_info hash needs_rehash verify thinfo pclose ntl_alarm async_signals errno exec fork getpriority get_last_error setpriority signal nal_dispatch nal_get_handler procmask timedwait waitinfo strerror wait waitpid wexitstatus wifexited wifsignaled wifstopped wstopsig wtermsig PDF_activate_item add_annotation bookmark launchlink locallink nameddest note outline pdflink table_cell textflow thumbnail weblink arc arcn attach_file begin_document font glyph item layer page page_ext pattern template template_ext circle clip ose path path_fill_stroke path_stroke _image _pdi _pdi_page concat continue_text create_3dview action annotation bookmark field fieldgroup gstate pvf textflow curveto define_layer lete _pvf _table _textflow encoding_set_char dpath d_document font glyph item layer page page_ext pattern template fill _imageblock _pdfblock _stroke _textblock ndfont t_image pdi_page table textflow textline get_apiname buffer errmsg errnum font fontname fontsize image_height image_width majorversion minorversion parameter pdi_parameter pdi_value value info_font matchbox table textflow textline itgraphics lineto load_3ddata font iccprofile image makespotcolor moveto new open_ccitt file gif image image_file jpeg memory_image pdi pdi_document pdi_page tiff pcos_get_number pcos_get_stream pcos_get_string place_image place_pdi_page process_pdi rect restore resume_page rotate save scale setcolor dash dashpattern flat font gray gray_fill gray_stroke linecap linejoin linewidth matrix miterlimit polydash rgbcolor rgbcolor_fill rgbcolor_stroke _border_color _border_dash _border_style _char_spacing _duration _gstate _horiz_scaling _info _author _creator _keywords _subject _title _layer_dependency _leading _parameter _text_matrix pos rendering rise _value _word_spacing shading ading_pattern fill ow ow_boxed ow_xy skew stringwidth stroke suspend_page translate utf8_to_utf16 utf16_to_utf8 utf32_to_utf16 pfsockopen pg_affected_rows cancel_query client_encoding close connect ion_busy ion_reset ion_status _poll nsume_input nvert py_from py_to dbname delete end_copy escape_bytea identifier literal string execute fetch_all all_columns array assoc object result row field_is_null name num prtlen size table type type_oid flush free_result get_notify get_pid get_result host insert last_error last_notice last_oid lo_close create export import open read read_all seek tell truncate unlink write meta_data num_fields num_rows options parameter_status pconnect ping port prepare put_line query query_params result_error error_field seek status select nd_execute prepare query query_params t_client_encoding t_error_verbosity socket trace transaction_status tty unescape_bytea untrace update version phpcredits dbg_break_file function method next clear color end_oplog exec get_executable prompt start_oplog info version _check_syntax _ini_loaded_file _ini_scanned_files _logo_guid _sapi_name _strip_whitespace _uname pi png2wbmp popen s six_access ctermid errno getcwd egid euid gid grgid grnam groups login pgid pgrp pid ppid pwnam pwuid rlimit sid uid _last_error initgroups isatty kill mkfifo mknod setegid euid gid pgid rlimit sid uid strerror times ttyname uname w preg_filter grep last_error match match_all quote replace replace_callback replace_callback_array split ev int intf int_r oc_close get_status nice open terminate operty_exists pspell_add_to_personal add_to_session check clear_session config_create data_dir dict_dir ignore mode personal repl runtogether save_repl new new_config new_personal save_wordlist store_replacement suggest _add_bookmark launchlink locallink note pdflink weblink rc rcn _begin_page _begin_pattern _begin_template _circle lip lose path path_stroke _image ontinue_text urveto _delete _end_page _end_pattern _end_template _fill _fill_stroke _findfont _get_buffer _get_parameter _get_value _hyphenate _include_file _lineto _makespotcolor _moveto _new _open_file image image_file memory_image _place_image _rect _restore _rotate _save cale etcolor dash flat font gray linecap linejoin linewidth miterlimit overprintmode polydash _border_color _border_dash _border_style _info _parameter _text_pos _value hading hading_pattern hfill how 2 _boxed _xy _xy2 tringwidth tring_geometry troke ymbol ymbol_name ymbol_width _translate putenv px_close create_fp date2string delete delete_record get_field info parameter record schema value insert_record new numfields numrecords open_fp put_record retrieve_record set_blob_file parameter tablename targetencoding value timestamp2string update_record quoted_printable_decode quoted_printable_encode quotemeta rad2deg dius_acct_open add_server auth_open close config create_request cvt_addr cvt_int cvt_string demangle demangle_mppe_key get_attr tagged_attr_data tagged_attr_tag vendor_attr put_addr attr int string vendor_addr attr int string request_authenticator salt_encrypt_attr send_request server_secret strerror nd ndom_bytes ndom_int nge r_wrapper_cache_stats wurldecode wurlencode readdir file gzfile line e_add_history callback_handler_install callback_handler_remove callback_read_char clear_history completion_function info list_history on_new_line read_history redisplay write_history k _exif_data alpath alpath_cache_get alpath_cache_size code code_file code_string gister_shutdown_function gister_tick_function name name_function set store_error_handler store_exception_handler store_include_path wind winddir rmdir round rpm_close get_tag is_valid open version rrdc_disconnect _create _error _fetch _first _graph _info _last _lastupdate _restore _tune _update _version _xport rsort rtrim runkit_class_adopt class_emancipate constant_add constant_redefine constant_remove function_add copy redefine remove rename import lint lint_file method_add copy redefine remove rename return_value_used sandbox_output_handler superglobals sapi_windows_cp_conv get is_utf8 set vt100_support scandir seaslog_get_author aslog_get_version m_acquire get release remove rialize ssion_abort cache_expire cache_limiter commit create_id decode destroy encode gc get_cookie_params id is_registered module_name name pgsql_add_error get_error get_field reset set_field status regenerate_id gister gister_shutdown set save_path set_cookie_params set_save_handler start status unregister unset write_close tcookie tlocale tproctitle trawcookie tthreadtitle ttype t_error_handler exception_handler file_buffer include_path magic_quotes_runtime socket_blocking time_limit sha1 a1_file ell_exec mop_close delete open read size write m_attach detach get_var has_var put_var remove remove_var ow_source uffle similar_text mplexml_import_dom mplexml_load_file mplexml_load_string n nh zeof sleep snmp2_get getnext real_walk set walk 3_get getnext real_walk set walk get getnext realwalk set walk walkoid _get_quick_print _get_valueretrieval _read_mib _set_enum_print oid_numeric_print oid_output_format quick_print valueretrieval socket_accept addrinfo_bind connect explain lookup bind clear_error close cmsg_space connect create create_listen create_pair export_stream getopt peername sockname _option _status import_stream last_error listen read cv cvfrom cvmsg select nd ndmsg ndto topt t_block blocking nonblock option timeout shutdown strerror write dium_add base642bin bin2base64 bin2hex compare crypto_aead_aes256gcm_decrypt encrypt is_available keygen chacha20poly1305_decrypt encrypt ietf_decrypt ietf_encrypt ietf_keygen keygen xchacha20poly1305_ietf_decrypt xchacha20poly1305_ietf_encrypt xchacha20poly1305_ietf_keygen auth auth_keygen auth_verify box _keypair _keypair_from_secretkey_and_publickey _open _publickey _publickey_from_secretkey _seal al_open cretkey ed_keypair generichash _final _init _keygen _update kdf_derive_from_key kdf_keygen kx_client_session_keys keypair publickey secretkey seed_keypair server_session_keys pwhash _scryptsalsa208sha256 cryptsalsa208sha256_str cryptsalsa208sha256_str_verify tr tr_needs_rehash tr_verify scalarmult scalarmult_base secretbox box_keygen box_open stream_xchacha20poly1305_init_pull init_push keygen pull push rekey shorthash shorthash_keygen sign _detached _ed25519_pk_to_curve25519 _ed25519_sk_to_curve25519 _keypair _keypair_from_secretkey_and_publickey _open _publickey _publickey_from_secretkey _secretkey _seed_keypair _verify_detached stream stream_keygen stream_xor hex2bin increment memcmp memzero pad unpad lr_get_version rt undex split liti l_autoload _call _extensions _functions _register _unregister classes object_hash object_id rintf sqlite_array_query busy_timeout changes close column create_aggregate create_function current error_string escape_string exec factory fetch_all array column_types object single string field_name has_more has_prev key last_error last_insert_rowid libencoding libversion next num_fields num_rows open popen prev query rewind seek single_query udf_decode_binary udf_encode_binary unbuffered_query valid lsrv_begin_transaction cancel client_info close commit configure connect errors execute fetch fetch_array fetch_object field_metadata free_stmt get_config get_field has_rows next_result num_fields num_rows prepare query rollback rows_affected send_stream_data server_info l_regcase rt srand sscanf deep_fuzzy_compare deep_fuzzy_hash deep_fuzzy_hash_filename h2_auth_agent hostbased_file none password pubkey_file connect disconnect exec fetch_stream fingerprint methods_negotiated publickey_add init list remove scp_recv scp_send sftp _chmod _lstat _mkdir _readlink ealpath ename mdir _stat _symlink _unlink shell tunnel stat s_absolute_deviation cdf_beta binomial cauchy chisquare exponential f gamma laplace logistic negative_binomial noncentral_chisquare ncentral_f ncentral_t rmal poisson t uniform weibull covariance dens_beta cauchy chisquare exponential f gamma laplace logistic normal pmf_binomial hypergeometric negative_binomial poisson t uniform weibull harmonic_mean kurtosis rand_gen_beta chisquare exponential f funiform gamma ibinomial ibinomial_negative int ipoisson iuniform noncenral_chisquare tral_chisquare tral_f tral_t rmal t t_seeds phrase_to_seeds ranf setall skew standard_deviation t_binomial_coef correlation factorial independent_t innerproduct paired_t percentile powersum variance omp_connect_error omp_version rcasecmp hr mp oll spn ream_bucket_append make_writeable new prepend context_create get_default get_options get_params set_default set_option set_params py_to_stream encoding filter_append prepend register remove get_contents filters line meta_data transports wrappers isatty is_local notification_callback register_wrapper resolve_include_path select t_blocking chunk_size read_buffer timeout write_buffer socket_accept client enable_crypto get_name pair recvfrom sendto server shutdown supports_lock wrapper_register wrapper_restore wrapper_unregister rftime ripcslashes pos pslashes p_tags str rlen rnatcasecmp atcmp casecmp cmp rpbrk rpos rptime rrchr ev ipos pos rspn rstr rtok olower otime oupper r rval r_getcsv ireplace pad repeat replace rot13 shuffle split word_count substr _compare _count _replace svn_add auth_get_parameter auth_set_parameter blame cat checkout cleanup client_version commit delete diff export fs_abort_txn apply_text begin_txn2 change_node_prop check_path contents_changed copy delete dir_entries file_contents file_length is_dir is_file make_dir make_file node_created_rev node_prop props_changed revision_prop revision_root txn_root youngest_rev import log ls mkdir repos_create fs fs_begin_txn_for_commit fs_commit_txn hotcopy open recover vert status update swoole_async_dns_lookup read readfile set write writefile client_select cpu_num errno event_add defer del exit set wait write get_local_ip last_error load_module select set_process_name strerror timer_after timer_exists timer_tick version sybase_affected_rows close connect data_seek deadlock_retry_count fetch_array assoc field object row field_seek free_result get_last_message min_client_severity error_severity message_severity server_severity num_fields num_rows pconnect query result select_db set_message_handler unbuffered_query mlink slog stem s_getloadavg s_get_temp_dir taint tan tanh tcpwrap_check tempnam textdomain tidy_access_count config_count error_count get_output load_config reset_config save_config setopt set_encoding warning_count me zone_abbreviations_list identifiers_list location_get name_from_abbr name_get offset_get open transitions_get version_get _nanosleep _sleep_until tmpfile token_get_all token_name touch trader_acos ad d osc x xr apo aroon aroonosc asin atan atr avgprice bbands beta bop cci cdl2crows 3blackcrows 3inside 3linestrike 3outside 3starsinsouth 3whitesoldiers abandonedbaby advanceblock belthold breakaway closingmarubozu concealbabyswall counterattack darkcloudcover doji dojistar dragonflydoji engulfing eveningdojistar eveningstar gapsidesidewhite gravestonedoji hammer ngingman rami ramicross highwave hikkake hikkakemod homingpigeon identical3crows inneck invertedhammer kicking kickingbylength ladderbottom longleggeddoji longline marubozu matchinglow mathold morningdojistar morningstar onneck piercing rickshawman risefall3methods separatinglines shootingstar shortline spinningtop stalledpattern sticksandwich takuri tasukigap thrusting tristar unique3river upsidegap2crows xsidegap3methods ceil cmo correl cos cosh dema div dx ema errno exp floor get_compat get_unstable_period ht_dcperiod dcphase phasor sine trendline trendmode kama linearreg _angle _intercept _slope ln log10 ma cd cdext cdfix ma vp x xindex medprice mfi midpoint dprice n nindex nmax nmaxindex nus_di nus_dm mom mult natr obv plus_di plus_dm ppo roc p r r100 rsi sar sarext set_compat set_unstable_period sin sinh sma sqrt stddev och ochf ochrsi sub sum t3 tan tanh tema trange trima trix tsf typprice ultosc var wclprice willr wma ait_exists igger_error im uasort ucfirst ucwords udm_add_search_limit alloc_agent alloc_agent_array api_version cat_list cat_path check_charset clear_search_limits crc32 errno error find free_agent free_ispell_data free_res get_doc_count get_res_field get_res_param hash32 load_ispell_data set_agent_param uksort umask uniqid ixtojd link pack register_tick_function serialize set taint uopz_add_function allow_exit backup compose copy delete del_function extend flags function get_exit_status hook mock property return static implement overload redefine rename restore set_hook mock property return static undefine set_hook set_mock set_return urldecode urlencode user_error e_soap_error_handler leep ort utf8_decode utf8_encode variant_abs add and cast cat cmp date_from_timestamp date_to_timestamp div eqv fix get_type idiv imp int mod mul neg not or pow round set set_type sub xor _dump _export version_compare vfprintf virtual vpopmail_add_alias_domain alias_domain_ex domain domain_ex user alias_add del del_domain get get_all auth_user del_domain del_domain_ex del_user error passwd set_user_quota rintf vsprintf wddx_add_vars deserialize packet_end packet_start serialize_value serialize_vars win32_continue_service create_service delete_service get_last_control_message pause_service ps_list_procs ps_stat_mem ps_stat_proc query_service_status set_service_status start_service start_service_ctrl_dispatcher stop_service cache_fcache_fileinfo fcache_meminfo lock ocache_fileinfo ocache_meminfo refresh_if_changed rplist_fileinfo rplist_meminfo scache_info scache_meminfo ucache_add cas clear dec delete exists get inc info meminfo set unlock wordwrap xattr_get list remove set supported xdiff_file_bdiff bdiff_size bpatch diff diff_binary merge3 patch patch_binary rabdiff string_bdiff bdiff_size bpatch diff diff_binary merge3 patch patch_binary rabdiff xhprof_disable enable sample_disable sample_enable xmlrpc_decode decode_request encode encode_request get_type is_fault parse_method_descriptions server_add_introspection_data call_method create destroy register_introspection_callback register_method t_type _error_string _get_current_byte_index current_column_number current_line_number error_code _parse r_create create_ns free get_option set_option _into_struct _set_character_data_handler default_handler element_handler end_namespace_decl_handler external_entity_ref_handler notation_decl_handler object processing_instruction_handler start_namespace_decl_handler unparsed_entity_decl_handler yaml_emit emit_file parse parse_file parse_url z_addinfo ccl_conf ccl_parse close connect database element errno error es es_result get_option hits itemorder present range record scan scan_result schema search set_option sort syntax wait yp_all cat errno err_string first get_default_domain master match next order zend_logo_guid zend_thread_id zend_version zip_close entry_close compressedsize compressionmethod filesize name open read open read zlib_decode zlib_encode zlib_get_coding_type __autoload __halt_compiler";
    var phpBuiltin = "func_num_args func_get_arg func_get_args strlen strcmp strncmp strcasecmp strncasecmp each error_reporting define" +
        " defined trigger_error user_error set_error_handler restore_error_handler get_declared_classes get_loaded_extensions" +
        " extension_loaded get_extension_funcs debug_backtrace constant bin2hex hex2bin sleep usleep time mktime gmmktime strftime" +
        " gmstrftime strtotime date gmdate getdate localtime checkdate flush wordwrap htmlspecialchars htmlentities html_entity_decode" +
        " md5 md5_file crc32 getimagesize image_type_to_mime_type phpinfo phpversion phpcredits strnatcmp strnatcasecmp substr_count" +
        " strspn strcspn strtok strtoupper strtolower strpos strrpos strrev hebrev hebrevc nl2br basename dirname pathinfo stripslashes" +
        " stripcslashes strstr stristr strrchr str_shuffle str_word_count strcoll substr substr_replace quotemeta ucfirst ucwords" +
        " strtr addslashes addcslashes rtrim str_replace str_repeat count_chars chunk_split trim ltrim strip_tags similar_text explode" +
        " implode setlocale localeconv parse_str str_pad chop strchr sprintf printf vprintf vsprintf sscanf fscanf parse_url urlencode" +
        " urldecode rawurlencode rawurldecode readlink linkinfo link unlink exec system escapeshellcmd escapeshellarg passthru" +
        " shell_exec proc_open proc_close rand srand getrandmax mt_rand mt_srand mt_getrandmax base64_decode base64_encode abs ceil" +
        " floor round is_finite is_nan is_infinite bindec hexdec octdec decbin decoct dechex base_convert number_format fmod ip2long" +
        " long2ip getenv putenv getopt microtime gettimeofday getrusage uniqid quoted_printable_decode set_time_limit get_cfg_var" +
        " magic_quotes_runtime set_magic_quotes_runtime get_magic_quotes_gpc get_magic_quotes_runtime import_request_variables error_log" +
        " serialize unserialize memory_get_usage var_dump var_export debug_zval_dump print_r highlight_file show_source highlight_string" +
        " ini_get ini_get_all ini_set ini_alter ini_restore get_include_path set_include_path restore_include_path setcookie header" +
        " headers_sent connection_aborted connection_status ignore_user_abort parse_ini_file is_uploaded_file move_uploaded_file intval" +
        " floatval doubleval strval gettype settype is_null is_resource is_bool is_long is_float is_int is_integer is_double is_real" +
        " is_numeric is_string is_array is_object is_scalar ereg ereg_replace eregi eregi_replace split spliti join sql_regcase dl" +
        " pclose popen readfile rewind rmdir umask fclose feof fgetc fgets fgetss fread fopen fpassthru ftruncate fstat fseek ftell" +
        " fflush fwrite fputs mkdir rename copy tempnam tmpfile file file_get_contents stream_select stream_context_create" +
        " stream_context_set_params stream_context_set_option stream_context_get_options stream_filter_prepend stream_filter_append" +
        " fgetcsv flock get_meta_tags stream_set_write_buffer set_file_buffer set_socket_blocking stream_set_blocking socket_set_blocking" +
        " stream_get_meta_data stream_register_wrapper stream_wrapper_register stream_set_timeout socket_set_timeout socket_get_status" +
        " realpath fnmatch fsockopen pfsockopen pack unpack get_browser crypt opendir closedir chdir getcwd rewinddir readdir dir glob" +
        " fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype file_exists is_writable is_writeable" +
        " is_readable is_executable is_file is_dir is_link stat lstat chown touch clearstatcache mail ob_start ob_flush ob_clean" +
        " ob_end_flush ob_end_clean ob_get_flush ob_get_clean ob_get_length ob_get_level ob_get_status ob_get_contents ob_implicit_flush" +
        " ob_list_handlers ksort krsort natsort natcasesort asort arsort sort rsort usort uasort uksort shuffle array_walk count" +
        " end prev next reset current key min max in_array array_search extract compact array_fill range array_multisort array_push" +
        " array_pop array_shift array_unshift array_splice array_slice array_merge array_merge_recursive array_keys array_values" +
        " array_count_values array_reverse array_reduce array_pad array_flip array_change_key_case array_rand array_unique array_intersect" +
        " array_intersect_assoc array_diff array_diff_assoc array_sum array_filter array_map array_chunk array_key_exists pos" +
        " sizeof key_exists assert assert_options version_compare ftok str_rot13 aggregate session_name session_module_name" +
        " session_save_path session_id session_regenerate_id session_decode session_register session_unregister session_is_registered" +
        " session_encode session_start session_destroy session_unset session_set_save_handler session_cache_limiter session_cache_expire" +
        " session_set_cookie_params session_get_cookie_params session_write_close preg_match preg_match_all preg_replace" +
        " preg_replace_callback preg_split preg_quote preg_grep overload ctype_alnum ctype_alpha ctype_cntrl ctype_digit ctype_lower" +
        " ctype_graph ctype_print ctype_punct ctype_space ctype_upper ctype_xdigit virtual apache_request_headers apache_note" +
        " apache_lookup_uri apache_child_terminate apache_setenv apache_response_headers apache_get_version getallheaders mysql_connect" +
        " mysql_pconnect mysql_close mysql_select_db mysql_create_db mysql_drop_db mysql_query mysql_unbuffered_query mysql_db_query" +
        " mysql_list_dbs mysql_list_tables mysql_list_fields mysql_list_processes mysql_error mysql_errno mysql_affected_rows" +
        " mysql_insert_id mysql_result mysql_num_rows mysql_num_fields mysql_fetch_row mysql_fetch_array mysql_fetch_assoc" +
        " mysql_fetch_object mysql_data_seek mysql_fetch_lengths mysql_fetch_field mysql_field_seek mysql_free_result mysql_field_name" +
        " mysql_field_table mysql_field_len mysql_field_type mysql_field_flags mysql_escape_string mysql_real_escape_string mysql_stat" +
        " mysql_thread_id mysql_client_encoding mysql_get_client_info mysql_get_host_info mysql_get_proto_info mysql_get_server_info" +
        " mysql_info mysql mysql_fieldname mysql_fieldtable mysql_fieldlen mysql_fieldtype mysql_fieldflags mysql_selectdb mysql_createdb" +
        " mysql_dropdb mysql_freeresult mysql_numfields mysql_numrows mysql_listdbs mysql_listtables mysql_listfields mysql_db_name" +
        " mysql_dbname mysql_tablename mysql_table_name pg_connect pg_pconnect pg_close pg_connection_status pg_connection_busy" +
        " pg_connection_reset pg_host pg_dbname pg_port pg_tty pg_options pg_ping pg_query pg_send_query pg_cancel_query pg_fetch_result" +
        " pg_fetch_row pg_fetch_assoc pg_fetch_array pg_fetch_object pg_fetch_all pg_affected_rows pg_get_result pg_result_seek" +
        " pg_result_status pg_free_result pg_last_oid pg_num_rows pg_num_fields pg_field_name pg_field_num pg_field_size pg_field_type" +
        " pg_field_prtlen pg_field_is_null pg_get_notify pg_get_pid pg_result_error pg_last_error pg_last_notice pg_put_line" +
        " pg_end_copy pg_copy_to pg_copy_from pg_trace pg_untrace pg_lo_create pg_lo_unlink pg_lo_open pg_lo_close pg_lo_read" +
        " pg_lo_write pg_lo_read_all pg_lo_import pg_lo_export pg_lo_seek pg_lo_tell pg_escape_string pg_escape_bytea pg_unescape_bytea" +
        " pg_client_encoding pg_set_client_encoding pg_meta_data pg_convert pg_insert pg_update pg_delete pg_select pg_exec" +
        " pg_getlastoid pg_cmdtuples pg_errormessage pg_numrows pg_numfields pg_fieldname pg_fieldsize pg_fieldtype pg_fieldnum" +
        " pg_fieldprtlen pg_fieldisnull pg_freeresult pg_result pg_loreadall pg_locreate pg_lounlink pg_loopen pg_loclose pg_loread" +
        " pg_lowrite pg_loimport pg_loexport http_response_code get_declared_traits getimagesizefromstring socket_import_stream" +
        " stream_set_chunk_size trait_exists header_register_callback class_uses session_status session_register_shutdown echo print" +
        " global static exit array empty eval isset unset die include require include_once require_once json_decode json_encode" +
        " json_last_error json_last_error_msg curl_close curl_copy_handle curl_errno curl_error curl_escape curl_exec curl_file_create" +
        " curl_getinfo curl_init curl_multi_add_handle curl_multi_close curl_multi_exec curl_multi_getcontent curl_multi_info_read" +
        " curl_multi_init curl_multi_remove_handle curl_multi_select curl_multi_setopt curl_multi_strerror curl_pause curl_reset" +
        " curl_setopt_array curl_setopt curl_share_close curl_share_init curl_share_setopt curl_strerror curl_unescape curl_version" +
        " mysqli_affected_rows mysqli_autocommit mysqli_change_user mysqli_character_set_name mysqli_close mysqli_commit" +
        " mysqli_connect_errno mysqli_connect_error mysqli_connect mysqli_data_seek mysqli_debug mysqli_dump_debug_info mysqli_errno" +
        " mysqli_error_list mysqli_error mysqli_fetch_all mysqli_fetch_array mysqli_fetch_assoc mysqli_fetch_field_direct mysqli_fetch_field" +
        " mysqli_fetch_fields mysqli_fetch_lengths mysqli_fetch_object mysqli_fetch_row mysqli_field_count mysqli_field_seek" +
        " mysqli_field_tell mysqli_free_result mysqli_get_charset mysqli_get_client_info mysqli_get_client_stats mysqli_get_client_version" +
        " mysqli_get_connection_stats mysqli_get_host_info mysqli_get_proto_info mysqli_get_server_info mysqli_get_server_version" +
        " mysqli_info mysqli_init mysqli_insert_id mysqli_kill mysqli_more_results mysqli_multi_query mysqli_next_result mysqli_num_fields" +
        " mysqli_num_rows mysqli_options mysqli_ping mysqli_prepare mysqli_query mysqli_real_connect mysqli_real_escape_string" +
        " mysqli_real_query mysqli_reap_async_query mysqli_refresh mysqli_rollback mysqli_select_db mysqli_set_charset" +
        " mysqli_set_local_infile_default mysqli_set_local_infile_handler mysqli_sqlstate mysqli_ssl_set mysqli_stat mysqli_stmt_init" +
        " mysqli_store_result mysqli_thread_id mysqli_thread_safe mysqli_use_result mysqli_warning_count";
    CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" "));

    CodeMirror.registerHelper("wordChars", "php", /[\w$]/);

    CodeMirror.registerHelper("hint", "fromList", function(cm, options) {
        var cur = cm.getCursor(), token = cm.getTokenAt(cur);
        var found = [];
        var variables = (cm.getValue().match(/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/g) || []).filter(function(elem,pos,arr) { return arr.indexOf(elem) == pos; });
        var words = [].concat(options.words, variables, [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" ").sort());

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            if (word.slice(0, token.string.length) == token.string)
                found.push(word);
        }

        if (found.length) {
            return {
                list: found,
                from: CodeMirror.Pos(cur.line, token.start),
                to: CodeMirror.Pos(cur.line, token.end)
            };
        } else {
            return {
                list: words,
                from: CodeMirror.Pos(cur.line, token.end),
                to: CodeMirror.Pos(cur.line, token.end)
            };
        }
    });

    var phpConfig = {
        name: "clike",
        helperType: "php",
        keywords: keywords(phpKeywords),
        blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"),
        atoms: keywords(phpAtoms),
        builtin: keywords(phpBuiltin),
        multiLineStrings: true,
        hooks: {
            "$": function(stream) {
                stream.eatWhile(/[\w\$_]/);
                return "variable-2";
            },
            "<": function(stream, state) {
                if (stream.match(/<</)) {
                    stream.eatWhile(/[\w\.]/);
                    var delim = stream.current().slice(3);
                    if (delim) {
                        (state.tokStack || (state.tokStack = [])).push(delim, 0);
                        state.tokenize = stringWithEscapes(delim);
                        return "string";
                    }
                }
                return false;
            },
            "#": function(stream) {
                while (!stream.eol() && !stream.match("?>", false)) stream.next();
                return "comment";
            },
            "/": function(stream) {
                if (stream.eat("/")) {
                    while (!stream.eol() && !stream.match("?>", false)) stream.next();
                    return "comment";
                }
                return false;
            },
            '"': function(_stream, state) {
                (state.tokStack || (state.tokStack = [])).push('"', 0);
                state.tokenize = stringWithEscapes('"');
                return "string";
            },
            "{": function(_stream, state) {
                if (state.tokStack && state.tokStack.length)
                    state.tokStack[state.tokStack.length - 1]++;
                return false;
            },
            "}": function(_stream, state) {
                if (state.tokStack && state.tokStack.length > 0 &&
                    !--state.tokStack[state.tokStack.length - 1]) {
                    state.tokenize = stringWithEscapes(state.tokStack[state.tokStack.length - 2]);
                }
                return false;
            }
        }
    };

    CodeMirror.defineMode("scriptcase", function(config, parserConfig) {
        CodeMirror.registerHelper("hintWords", "php", macros);

        var htmlMode = CodeMirror.getMode(config, "text/html");

        var phpMode = CodeMirror.getMode(config, phpConfig);

        function dispatch(stream, state) {

            var isPHP = state.curMode == phpMode;
            if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null;
            if (!isPHP) {
                if (stream.match(/^<\?\w*/)) {
                    state.curMode = phpMode;
                    state.curState = state.php;
                    return "meta";
                }
                if (state.pending == '"' || state.pending == "'") {
                    while (!stream.eol() && stream.next() != state.pending) {}
                    var style = "string";
                } else if (state.pending && stream.pos < state.pending.end) {
                    stream.pos = state.pending.end;
                    var style = state.pending.style;
                } else {
                    var style = htmlMode.token(stream, state.curState);
                }
                if (state.pending) state.pending = null;
                var cur = stream.current(), openPHP = cur.search(/<\?/), m;
                if (openPHP != -1) {
                    if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0];
                    else state.pending = {end: stream.pos, style: style};
                    stream.backUp(cur.length - openPHP);
                }
                return style;
            } else if (isPHP && state.php.tokenize == null && stream.match("?>")) {
                state.curMode = htmlMode;
                state.curState = state.html;
                return "meta";
            } else {
                return phpMode.token(stream, state.curState);
            }
        }

        return {
            startState: function() {
                var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode);
                return {html: html,
                    php: php,
                    curMode: parserConfig.startOpen ? phpMode : htmlMode,
                    curState: parserConfig.startOpen ? php : html,
                    pending: null};
            },

            copyState: function(state) {
                var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html),
                    php = state.php, phpNew = CodeMirror.copyState(phpMode, php), cur;
                if (state.curMode == htmlMode) cur = htmlNew;
                else cur = phpNew;
                return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur,
                    pending: state.pending};
            },

            token: dispatch,

            indent: function(state, textAfter) {
                if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) ||
                    (state.curMode == phpMode && /^\?>/.test(textAfter)))
                    return htmlMode.indent(state.html, textAfter);
                return state.curMode.indent(state.curState, textAfter);
            },

            blockCommentStart: "/*",
            blockCommentEnd: "*/",
            lineComment: "//",

            innerMode: function(state) { return {state: state.curState, mode: state.curMode}; }
        };
    }, "htmlmixed", "clike");

    CodeMirror.defineMIME("application/x-httpd-scriptcase", "scriptcase");
    CodeMirror.defineMIME("application/x-httpd-scriptcase-open", {name: "scriptcase", startOpen: true});
    CodeMirror.defineMIME("text/x-php", phpConfig);
});
