Critical error – bailing out on search for "clubs"

Post

Posted
Rating:
#6175 (In Topic #1507)
Avatar
Standard member
Terry is in the usergroup ‘Fan in action’
Some sort of error. It's not a big issue, but it would be good to hear any ideas about what this could be caused from, if anyone has any ideas.

Search content - Witches Chat

and

Search content - Witches Chat

Yields a Bailing Out error

I have it narrowed down a bit. It only happens when searching for the term "club" or "clubs" or if you search for anything, if the Clubs box is ticked to search the Clubs, it bails.

I'm also not clear on what defines a Club as compared to a Forum for a special Usergroup. When a Club is created, it creates a special Usergroup and a special Forum, is that correct?

 
Online now: No Back to the top

Post

Posted
Rating:
#6176
Avatar
Site director
Chris Graham is in the usergroup ‘Administrators’
For reference:

Code

SELECT cached_for,identifier,the_value,date_and_time,dependencies FROM cms_cache WHERE the_theme='Witches_Chat' AND staff_status IS NULL AND the_member IS NULL AND `groups`='1' AND is_bot=0 AND timezone='America/Boise' AND lang='EN' AND (1=0 OR cached_for='menu' AND identifier='3e63c2db3de9b010335b3b0f19eeab32')/* f02ca0cc98fa1 *//

The final slash looks suspicious to me, I'll look into it.

A club is a usergroup with a setting to make it a club. Club usergroups have no permissions, meaning they don't bloat up the permission UI. When you add a club it will indeed add a forum, matched by the same name as the club.


Become a fan of Composr on Facebook or add me as a friend. Add me on on Twitter. Follow me on Minds (where I am most active). Support me on Patreon

Was I helpful?
  • If not, please let us know how we can do better (please try and propose any bigger ideas in such a way that they are fundable and scalable).
  • If so, please let others know about Composr whenever you see the opportunity or support me on Patreon.
  • If my reply is too Vulcan or expressed too much in business-strategy terms, and not particularly personal, I apologise. As a company & project maintainer, time is very limited to me, so usually when I write a reply I try and make it generic advice to all readers. I'm also naturally a joined-up thinker, so I always express my thoughts in combined business and technical terms. I recognise not everyone likes that, don't let my Vulcan-thinking stop you enjoying Composr on fun personal projects.
  • If my response can inspire a community tutorial, that's a great way of giving back to the project as a user.
Online now: No Back to the top

Post

Posted
Rating:
#6177
Avatar
Site director
Chris Graham is in the usergroup ‘Administrators’
Please reupload the latest sources/database.php in overwrite mode, not resume mode. I believe it's got slightly corrupted with a loose '/' character.


Become a fan of Composr on Facebook or add me as a friend. Add me on on Twitter. Follow me on Minds (where I am most active). Support me on Patreon

Was I helpful?
  • If not, please let us know how we can do better (please try and propose any bigger ideas in such a way that they are fundable and scalable).
  • If so, please let others know about Composr whenever you see the opportunity or support me on Patreon.
  • If my reply is too Vulcan or expressed too much in business-strategy terms, and not particularly personal, I apologise. As a company & project maintainer, time is very limited to me, so usually when I write a reply I try and make it generic advice to all readers. I'm also naturally a joined-up thinker, so I always express my thoughts in combined business and technical terms. I recognise not everyone likes that, don't let my Vulcan-thinking stop you enjoying Composr on fun personal projects.
  • If my response can inspire a community tutorial, that's a great way of giving back to the project as a user.
Online now: No Back to the top

Post

Posted
Rating:
#6178
Avatar
Standard member
Terry is in the usergroup ‘Fan in action’
The only location I can think of that has sources/database.php is either the original 10.0.28 (this is the one I installed) zip Composr extracted from, or at github/lab. I went to github and downloaded sources/database.php and replaced the sources/database.php on my site. it didn't make any difference. I downloaded the manuel Composr zip install and took the sources/database.php file and put it into the website's sources/database.php but it yields the same error. The Bail seems to come only from Club searching, especially when searching for things and you tick Clubs as one of the things to be searched.

 

Critical error – bailing out

This is an error that has been elevated to critical error status because it occurred during the primary error mechanism reporting system itself (possibly due to it occurring within the standard output framework). It may be masking a secondary error that occurred before this, but was never output - if so, it is likely strongly related to this one, thus fixing this will fix the other.
Unfortunately a query has failed [SELECT cached_for,identifier,the_value,date_and_time,dependencies FROM cms_cache WHERE the_theme='Witches_Chat' AND staff_status IS NULL AND the_member IS NULL AND `groups`='' AND is_bot=0 AND timezone='America/Boise' AND lang='EN' AND (1=0 OR cached_for='top_login' AND identifier='5d374855e6118a4d918ea76e17e537fc')/] [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1] (version: 10.0.28, PHP version: 7.3.12, URL: /index.php?page=search&type=results&all_defaults=0&content=club&author=&days=-1&sort=relevance&direction=DESC&search_cns_clubs=1&search_downloads=1&search_galleries=1&search_images=1&search_news=1&search_polls=1)

Stack trace…

File -> 'sources/failure.php'
Line -> 984
Function -> 'die_html_trace'
Args -> array

File -> 'sources/global2.php'
Line -> 1,046
Function -> '_fatal_exit'
Args -> array

File -> 'sources/database/mysqli.php'
Line -> 269
Function -> 'fatal_exit'
Args -> array

File -> 'sources/database.php'
Line -> 1,757
Function -> 'db_query'
Class -> 'Database_Static_mysqli'
Object -> O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}}s:14:"last_select_db";a:2:{i:0;r:3;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}
Type -> '->'
Args -> array

File -> 'sources/database.php'
Line -> 1,529
Function -> '_query'
Class -> 'DatabaseConnector'
Object -> O:17:"DatabaseConnector":8:{s:12:"table_prefix";s:4:"cms_";s:15:"connection_read";a:2:{i:0;O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}i:1;s:16:"witclgqz_witches";}s:16:"connection_write";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:26:"text_lookup_original_cache";a:0:{}s:17:"text_lookup_cache";a:0:{}s:18:"table_exists_cache";a:0:{}s:9:"static_ob";O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";r:4;}s:14:"last_select_db";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}s:11:"dedupe_mode";b:1;}
Type -> '->'
Args -> array

File -> 'sources/caches.php'
Line -> 728
Function -> 'query'
Class -> 'DatabaseConnector'
Object -> O:17:"DatabaseConnector":8:{s:12:"table_prefix";s:4:"cms_";s:15:"connection_read";a:2:{i:0;O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}i:1;s:16:"witclgqz_witches";}s:16:"connection_write";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:26:"text_lookup_original_cache";a:0:{}s:17:"text_lookup_cache";a:0:{}s:18:"table_exists_cache";a:0:{}s:9:"static_ob";O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";r:4;}s:14:"last_select_db";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}s:11:"dedupe_mode";b:1;}
Type -> '->'
Args -> array

File -> 'sources/caches.php'
Line -> 650
Function -> '_get_cache_entries'
Args -> a:2:{i:0;a:1:{i:0;a:8:{i:0;s:9:"top_login";i:1;s:14:"a:1:{i:0;b:1;}";i:2;s:32:"5d374855e6118a4d918ea76e17e537fc";i:3;i:24;i:4;i:1440;i:5;b:1;i:6;b:0;i:7;a:2:{s:5:"block";s:9:"top_login";s:5:"cache";s:1:"1";}}}i:1;i:24;}

File -> 'sources/zones.php'
Line -> 1,123
Function -> 'get_cache_entry'
Args -> a:7:{i:0;s:9:"top_login";i:1;s:14:"a:1:{i:0;b:1;}";i:2;i:24;i:3;i:1440;i:4;b:1;i:5;b:0;i:6;a:2:{s:5:"block";s:9:"top_login";s:5:"cache";s:1:"1";}}

File -> 'sources/tempcode.php'
Line -> 1,098
Function -> 'do_block'
Args -> a:2:{i:0;s:9:"top_login";i:1;a:2:{s:5:"block";s:9:"top_login";s:5:"cache";s:1:"1";}}

File -> 'sources/tempcode.php'
Line -> 1,793
Function -> 'handle_symbol_preprocessing'
Args -> array

File -> 'sources/global3.php'
Line -> 547
Function -> 'handle_symbol_preprocessing'
Class -> 'Tempcode'
Object -> Tempcode -> …
Type -> '->'
Args -> a:0:{}

File -> 'sources/failure.php'
Line -> 1,011
Function -> 'globalise'
Args -> array

File -> 'sources/global2.php'
Line -> 1,046
Function -> '_fatal_exit'
Args -> array

File -> 'sources/database/mysqli.php'
Line -> 269
Function -> 'fatal_exit'
Args -> array

File -> 'sources/database.php'
Line -> 1,757
Function -> 'db_query'
Class -> 'Database_Static_mysqli'
Object -> O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}}s:14:"last_select_db";a:2:{i:0;r:3;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}
Type -> '->'
Args -> array

File -> 'sources/database.php'
Line -> 1,529
Function -> '_query'
Class -> 'DatabaseConnector'
Object -> O:17:"DatabaseConnector":8:{s:12:"table_prefix";s:4:"cms_";s:15:"connection_read";a:2:{i:0;O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}i:1;s:16:"witclgqz_witches";}s:16:"connection_write";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:26:"text_lookup_original_cache";a:0:{}s:17:"text_lookup_cache";a:0:{}s:18:"table_exists_cache";a:0:{}s:9:"static_ob";O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";r:4;}s:14:"last_select_db";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}s:11:"dedupe_mode";b:1;}
Type -> '->'
Args -> a:7:{i:0;s:191:"(SELECT COUNT(*) FROM (SELECT 1 AS x FROM cms_f_groups r WHERE g_hidden=0 AND g_is_private_club=1 AND ((MATCH (r.g_name,r.g_title) AGAINST ('club'))) LIMIT 0,1000) counter)";i:1;i:1;i:2;N;i:3;b:0;i:4;b:0;i:5;N;i:6;s:0:"";}

File -> 'sources/database.php'
Line -> 1,335
Function -> 'query'
Class -> 'DatabaseConnector'
Object -> O:17:"DatabaseConnector":8:{s:12:"table_prefix";s:4:"cms_";s:15:"connection_read";a:2:{i:0;O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}i:1;s:16:"witclgqz_witches";}s:16:"connection_write";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:26:"text_lookup_original_cache";a:0:{}s:17:"text_lookup_cache";a:0:{}s:18:"table_exists_cache";a:0:{}s:9:"static_ob";O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";r:4;}s:14:"last_select_db";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}s:11:"dedupe_mode";b:1;}
Type -> '->'
Args -> a:6:{i:0;s:172:"(SELECT COUNT(*) FROM (SELECT 1 AS x FROM cms_f_groups r WHERE g_hidden=0 AND g_is_private_club=1 AND ((MATCH (r.g_name,r.g_title) AGAINST ('club'))) LIMIT 0,1000) counter)";i:1;i:1;i:2;N;i:3;b:0;i:4;b:0;i:5;N;}

File -> 'sources/database_search.php'
Line -> 1,461
Function -> 'query_value_if_there'
Class -> 'DatabaseConnector'
Object -> O:17:"DatabaseConnector":8:{s:12:"table_prefix";s:4:"cms_";s:15:"connection_read";a:2:{i:0;O:6:"mysqli":19:{s:13:"affected_rows";N;s:11:"client_info";N;s:14:"client_version";N;s:13:"connect_errno";N;s:13:"connect_error";N;s:5:"errno";N;s:5:"error";N;s:10:"error_list";N;s:11:"field_count";N;s:9:"host_info";N;s:4:"info";N;s:9:"insert_id";N;s:11:"server_info";N;s:14:"server_version";N;s:4:"stat";N;s:8:"sqlstate";N;s:16:"protocol_version";N;s:9:"thread_id";N;s:13:"warning_count";N;}i:1;s:16:"witclgqz_witches";}s:16:"connection_write";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:26:"text_lookup_original_cache";a:0:{}s:17:"text_lookup_cache";a:0:{}s:18:"table_exists_cache";a:0:{}s:9:"static_ob";O:22:"Database_Static_mysqli":3:{s:8:"cache_db";a:1:{s:54:"a:2:{i:0;s:16:"witclgqz_witches";i:1;s:9:"localhost";}";r:4;}s:14:"last_select_db";a:2:{i:0;r:4;i:1;s:16:"witclgqz_witches";}s:16:"reconnected_once";b:0;}s:11:"dedupe_mode";b:1;}
Type -> '->'
Args -> a:1:{i:0;s:172:"(SELECT COUNT(*) FROM (SELECT 1 AS x FROM cms_f_groups r WHERE g_hidden=0 AND g_is_private_club=1 AND ((MATCH (r.g_name,r.g_title) AGAINST ('club'))) LIMIT 0,1000) counter)";}

File -> 'sources/hooks/modules/search/cns_clubs.php'
Line -> 140
Function -> 'get_search_rows'
Args -> array

File -> 'site/pages/modules/search.php'
Line -> 679
Function -> 'run'
Class -> 'Hook_search_cns_clubs'
Object -> O:21:"Hook_search_cns_clubs":0:{}
Type -> '->'
Args -> a:16:{i:0;s:4:"club";i:1;b:0;i:2;s:4:"DESC";i:3;i:10;i:4;i:0;i:5;b:0;i:6;s:26:"MATCH (?) AGAINST ('club')";i:7;s:0:"";i:8;N;i:9;N;i:10;s:9:"relevance";i:11;i:10;i:12;s:2:"OR";i:13;s:39:" AND g_hidden=0 AND g_is_private_club=1";i:14;s:1:"!";i:15;i:0;}

File -> 'site/pages/modules/search.php'
Line -> 487
Function -> 'results'
Class -> 'Module_search'
Object -> O:13:"Module_search":3:{s:5:"title";O:8:"Tempcode":5:{s:18:"code_to_preexecute";a:1:{s:33:"tcpfunc_5df3b5b4435652.33188068_1";s:2630:"$tpl_funcs['tcpfunc_5df3b5b4435652.33188068_1']=$KEEP_TPL_FUNCS['tcpfunc_5df3b5b4435652.33188068_1']=recall_named_function('5df3b5b44356e8.62543098','$parameters,$cl',"extract(\$parameters,EXTR_PREFIX_ALL,'bound'); echo (isset(\$bound_ID)?(\"\n<a id=\\"title__\".(empty(\$bound_ID->pure_lang)?@htmlspecialchars(otp(isset(\$bound_ID)?\$bound_ID:null,\"SCREEN_TITLE:ID\"),ENT_QUOTES | ENT_SUBSTITUTE,get_charset()):otp(isset(\$bound_ID)?\$bound_ID:null,\"SCREEN_TITLE:ID\")).\"\\"></a>\n\"):''),\n \"\n\n<h1 class=\\"screen_title\\"\",\n ((ecv_NOT(\$cl,array(),array(ecv_GET(\$cl,array(),array(\"name_set_elsewhere\"))))==\"1\")?(\" itemprop=\\"name\\"\"):''),\n \">\n \",\n otp(isset(\$bound_TITLE)?\$bound_TITLE:null,\"SCREEN_TITLE:TITLE\"),\n \"\n \",\n (isset(\$bound_AWARDS)?(\"\n \".((otp(isset(\$bound_AWARDS)?\$bound_AWARDS:null,\"SCREEN_TITLE:AWARDS\")!='')?(\"\n \".ecv(\$cl,array(),4,\"SET\",array(\"AWARDS_TEXT\",\"\n <h2>Award winner</h2>\n <p class=\\"lonely_label\\">\".ecv(\$cl,array(),2,\"AWARDS_WON\",array(otp(isset(\$bound_AWARDS)?\$bound_AWARDS:null,\"SCREEN_TITLE:AWARDS\"))).\"</p>\n <ul>\n \".closure_loop(array(\"AWARDS\",'vars'=>\$parameters),array(\$parameters,\$cl),\nrecall_named_function('5df3b5b44343a1.06766217','\$parameters,\$cl',\"extract(\\$parameters,EXTR_PREFIX_ALL,'bound'); return \\"\\n <li>\\n <strong>\\".(empty(\\$bound_AWARD_TYPE->pure_lang)?@htmlspecialchars(otp(isset(\\$bound_AWARD_TYPE)?\\$bound_AWARD_TYPE:null,\\"SCREEN_TITLE:AWARD_TYPE\\"),ENT_QUOTES | ENT_SUBSTITUTE,get_charset()):otp(isset(\\$bound_AWARD_TYPE)?\\$bound_AWARD_TYPE:null,\\"SCREEN_TITLE:AWARD_TYPE\\")).\\"</strong>\\n <span>\\".ecv(\\$cl,array(),2,\\"AWARD_ON\\",array(ecv_DATE(\\$cl,array(1),array(\\"1\\",\\"1\\",\\"1\\",otp(isset(\\$bound_AWARD_TIMESTAMP)?\\$bound_AWARD_TIMESTAMP:null,\\"SCREEN_TITLE:AWARD_TIMESTAMP\\"))))).\\"</span>\\n </li>\\n \\";\")).\"\n </ul>\n \")).\"\n <a href=\\"\".ecv_PAGE_LINK(\$cl,array(1),array(\"_SEARCH:awards\")).\"\\"><img onmouseover=\\"if (typeof window.activate_tooltip!='undefined') activate_tooltip(this,event,'\".ecv_GET(\$cl,array(2,8,1),array(\"AWARDS_TEXT\")).\"','auto',null,null,false,true);\\" title=\\"\\" alt=\\"Award winner\\" src=\\"\".ecv_IMG(\$cl,array(1),array(\"awarded\",\"0\",\"Witches_Chat\")).\"\\" /></a>\n \"):'').\"\n \"):''),\n \"\n</h1>\n\n\",\n (isset(\$bound_SUB)?(\"\n <div class=\\"title_tagline\\">\n \".otp(isset(\$bound_SUB)?\$bound_SUB:null,\"SCREEN_TITLE:SUB\").\"\n </div>\n\"):''),\n \"\n\";");";}s:9:"seq_parts";a:1:{i:0;a:1:{i:0;a:5:{i:0;s:33:"tcpfunc_5df3b5b4435652.33188068_1";i:1;a:3:{s:5:"_GUID";s:32:"847ffbe4823eca6d2d5eac42828ee552";s:6:"AWARDS";a:0:{}s:5:"TITLE";O:8:"Tempcode":5:{s:18:"code_to_preexecute";a:1:{s:36:"do_runtime_5df467a78c6ee6.81919474_1";s:107:"$tpl_funcs['do_runtime_5df467a78c6ee6.81919474_1']="echo ecv(\$cl,array(),2,\"SEARCH_RESULTS\",array());"; ";}s:9:"seq_parts";a:1:{i:0;a:1:{i:0;a:5:{i:0;s:36:"do_runtime_5df467a78c6ee6.81919474_1";i:1;a:0:{}i:2;i:2;i:3;s:14:"SEARCH_RESULTS";i:4;s:0:"";}}}s:19:"preprocessable_bits";a:0:{}s:9:"pure_lang";b:1;s:8:"codename";s:10:":container";}}i:2;i:1;i:3;s:0:"";i:4;s:0:"";}}}s:19:"preprocessable_bits";a:0:{}s:9:"pure_lang";N;s:8:"codename";s:12:"SCREEN_TITLE";}s:2:"ob";N;s:4:"info";N;}
Type -> '->'
Args -> a:8:{i:0;s:0:"";i:1;s:0:"";i:2;N;i:3;N;i:4;s:9:"relevance";i:5;s:4:"DESC";i:6;b:0;i:7;s:1:"!";}

Details here are intended only for the website/system-administrator, not for regular website users.
» If you are a regular website user, please let the website staff deal with this problem.

Depending on the error, and only if the website installation finished, you may need to edit the installation options (the _config.php file).

ocProducts maintains full documentation for all procedures and tools (including disaster recovery). These may be found on the Composr website. If you are unable to easily solve this problem, we may be contacted from our website and can help resolve it for you.


Composr is a CMS for building websites, developed by ocProducts.

Online now: No Back to the top

Post

Posted
Rating:
#6179
Avatar
Site director
Chris Graham is in the usergroup ‘Administrators’
I know this seems strange, but are you absolutely certain the FTP tool you used wasn't in resume mode? Can you try deleting and then uploading the file? The error message has changed, and now there seems to be one character missing rather than one character added.

It's happening in the code in the database engine that adds a comment at the end of queries to label them. This code only runs during searches. It's not the search per-se throwing the error, but it's a code path activated by search and tangentially triggered when you do that search.

If it turns out to not be an issue with database.php I'll look again, but to me it looks like exactly one very specific part of database.php is corrupt.


Become a fan of Composr on Facebook or add me as a friend. Add me on on Twitter. Follow me on Minds (where I am most active). Support me on Patreon

Was I helpful?
  • If not, please let us know how we can do better (please try and propose any bigger ideas in such a way that they are fundable and scalable).
  • If so, please let others know about Composr whenever you see the opportunity or support me on Patreon.
  • If my reply is too Vulcan or expressed too much in business-strategy terms, and not particularly personal, I apologise. As a company & project maintainer, time is very limited to me, so usually when I write a reply I try and make it generic advice to all readers. I'm also naturally a joined-up thinker, so I always express my thoughts in combined business and technical terms. I recognise not everyone likes that, don't let my Vulcan-thinking stop you enjoying Composr on fun personal projects.
  • If my response can inspire a community tutorial, that's a great way of giving back to the project as a user.
Online now: No Back to the top

Post

Posted
Rating:
#6180
Avatar
Standard member
Terry is in the usergroup ‘Fan in action’
I re-extracted the manual zip of database.php again and after deleting the one on my site, I uploaded the extracted version to the site. I'm thinking that without the database.php file on my website, when I upload it again, it should be a perfect copy. That didn't do the trick. I tried a few other ways, too. Something interesting though…the number of lines, and the size of database.php as it exists in the original zip, is the same size with the same number of lines as in v11 on git. Maybe I'm mistaken, but I think they are identical. I'll post here database.php

Which line is it that you suspect has the extra / char?


<?php






function init__database()
{
    global $HAS_MULTI_LANG_CONTENT;
    $HAS_MULTI_LANG_CONTENT = null;

    global $QUERY_LIST, $QUERY_COUNT, $NO_QUERY_LIMIT, $NO_DB_SCOPE_CHECK, $QUERY_FILE_LOG, $SITE_INFO;
    $QUERY_LIST = array();
    $QUERY_COUNT = 0;
   
    $NO_QUERY_LIMIT = false;
   
    $NO_DB_SCOPE_CHECK = false;
    if (((!isset($SITE_INFO['no_extra_logs'])) || ($SITE_INFO['no_extra_logs'] != '1')) && (is_file(get_custom_file_base() . '/data_custom/queries.log'))) {
        $QUERY_FILE_LOG = fopen(get_custom_file_base() . '/data_custom/queries.log', 'at');
    } else {
        $QUERY_FILE_LOG = null;
    }

    // This will be generalised some-time
    require_code('database/' . get_db_type());
    $GLOBALS['DB_STATIC_OBJECT'] = object_factory('Database_Static_' . get_db_type());

    // Create our main database objects
    global $TABLE_LANG_FIELDS_CACHE;
    $TABLE_LANG_FIELDS_CACHE = array();
    if ((!empty($SITE_INFO['db_site'])) || (!empty($SITE_INFO['db_site_user']))) {
        global $SITE_DB;
       
        $SITE_DB = new DatabaseConnector(get_db_site(), get_db_site_host(), get_db_site_user(), get_db_site_password(), get_table_prefix());
    }

    global $UPON_QUERY_HOOKS_CACHE;
    $UPON_QUERY_HOOKS_CACHE = null;
}


function db_map_restrict($row, $fields, $remap = null)
{
    // TODO: Change null to array() in v11; remove these 3 lines
    if ($remap === null) {
        $remap = array();
    }

    $out = array();
    foreach ($fields as $field) {
        $out[$field] = $row[(array_key_exists($field, $remap) && array_key_exists($remap[$field], $row)) ? $remap[$field] : $field];
        if (isset($row[$field . '__text_parsed'])) {
            $out[$field . '__text_parsed'] = $row[$field . '__text_parsed'];
        }
        if (array_key_exists($field . '__source_user', $row)) {
            $out[$field . '__source_user'] = $row[$field . '__source_user'];
        }
    }
    return $out;
}


function multi_lang_content()
{
    global $HAS_MULTI_LANG_CONTENT;
    if ($HAS_MULTI_LANG_CONTENT === null) {
        global $SITE_INFO;
        $HAS_MULTI_LANG_CONTENT = isset($SITE_INFO['multi_lang_content']) ? ($SITE_INFO['multi_lang_content'] === '1') : true; // For legacy reasons
    }
    return $HAS_MULTI_LANG_CONTENT;
}


function _general_db_init()
{
    global $TABLE_LANG_FIELDS_CACHE;
    if (count($TABLE_LANG_FIELDS_CACHE) > 0) {
        return;
    }

    $TABLE_LANG_FIELDS_CACHE = function_exists('persistent_cache_get') ? persistent_cache_get('TABLE_LANG_FIELDS_CACHE') : null;
    if ($TABLE_LANG_FIELDS_CACHE === null) {
        reload_lang_fields();
    }
}


function reload_lang_fields($full = false, $only_table = null)
{
    global $TABLE_LANG_FIELDS_CACHE;
    if ($only_table === null) {
        $TABLE_LANG_FIELDS_CACHE = array();
    } else {
        unset($TABLE_LANG_FIELDS_CACHE[$only_table]);
    }

    $msn_running = (is_on_multi_site_network()) && (get_forum_type() == 'cns') && (isset($GLOBALS['FORUM_DB'])); // TODO: Change in v11

    if (multi_lang_content() || $full) {
        // We need to know about any kind of translated fields in these cases
        $like = db_string_equal_to('m_type', 'SHORT_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', 'LONG_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', 'SHORT_TRANS') . ' OR ' . db_string_equal_to('m_type', 'LONG_TRANS') . ' OR ' . db_string_equal_to('m_type', '?SHORT_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', '?LONG_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', '?SHORT_TRANS') . ' OR ' . db_string_equal_to('m_type', '?LONG_TRANS');
    } else {
        // In this case we only really need to know about Comcode fields
        $like = db_string_equal_to('m_type', 'SHORT_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', 'LONG_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', '?SHORT_TRANS__COMCODE') . ' OR ' . db_string_equal_to('m_type', '?LONG_TRANS__COMCODE');
    }
    $sql = 'SELECT m_name,m_table,m_type FROM ' . get_table_prefix() . 'db_meta WHERE (' . $like . ')';
    if ($only_table !== null) {
        $sql .= ' AND ' . db_string_equal_to('m_table', $only_table);
    }
    if (($msn_running) && (substr($only_table, 0, 2) === 'f_')) {
        $_table_lang_fields = array(); // Optimisation, as it'll get overwritten anyway
    } else {
        $_table_lang_fields = $GLOBALS['SITE_DB']->query($sql, null, null, true);
    }
    if ($_table_lang_fields !== null) {
        // Load in our data
        foreach ($_table_lang_fields as $lang_field) {
            if (!isset($TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']])) {
                $TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']] = array();
            }

            $TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']][$lang_field['m_name']] = $lang_field['m_type'];
        }

        // Get correct forum DB metadata from central site
        if (($msn_running) && (($only_table === null) || (substr($only_table, 0, 2) === 'f_'))) {
            if ($only_table !== null) {
                unset($TABLE_LANG_FIELDS_CACHE[$only_table]);
            }
            unset($TABLE_LANG_FIELDS_CACHE['f_member_custom_fields']); // This may vary between sites in undefined ways

            $sql .= ' AND m_table LIKE \'' . db_encode_like('f_%') . '\'';

            $_table_lang_fields_forum = $GLOBALS['FORUM_DB']->query($sql, null, null, true);
            if ($_table_lang_fields_forum !== null) {
                // Load in our data
                foreach ($_table_lang_fields_forum as $lang_field) {
                    if (!isset($TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']])) {
                        $TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']] = array();
                    }

                    $TABLE_LANG_FIELDS_CACHE[$lang_field['m_table']][$lang_field['m_name']] = $lang_field['m_type'];
                }
            }
        }
    }

    if (function_exists('persistent_cache_set')) {
        persistent_cache_set('TABLE_LANG_FIELDS_CACHE', $TABLE_LANG_FIELDS_CACHE);
    }
}


function can_arbitrary_groupby()
{
    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'can_arbitrary_groupby')) {
        return false;
    }
    return $GLOBALS['DB_STATIC_OBJECT']->can_arbitrary_groupby();
}


function db_get_first_id()
{
    return $GLOBALS['DB_STATIC_OBJECT']->db_get_first_id();
}


function db_string_equal_to($attribute, $compare)
{
    return $GLOBALS['DB_STATIC_OBJECT']->db_string_equal_to($attribute, $compare);
}


function db_string_not_equal_to($attribute, $compare)
{
    return $GLOBALS['DB_STATIC_OBJECT']->db_string_not_equal_to($attribute, $compare);
}


function db_encode_like($pattern)
{
    $ret = $GLOBALS['DB_STATIC_OBJECT']->db_encode_like($pattern);

    if (($GLOBALS['DEV_MODE']) || (!function_exists('has_solemnly_declared')) || (!has_solemnly_declared(I_UNDERSTAND_SQL_INJECTION))) {
        require_code('database_security_filter');
        $GLOBALS['DB_ESCAPE_STRING_LIST'][$ret] = true;
        $GLOBALS['DB_ESCAPE_STRING_LIST'][trim($ret, ' %')] = true;
    }

    return $ret;
}


function db_supports_drop_table_if_exists($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_supports_drop_table_if_exists')) {
        return false;
    }

    return $GLOBALS['DB_STATIC_OBJECT']->db_supports_drop_table_if_exists();
}


function db_has_full_text($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    return $GLOBALS['DB_STATIC_OBJECT']->db_has_full_text($db);
}


function db_full_text_assemble($content, $boolean)
{
    $ret = $GLOBALS['DB_STATIC_OBJECT']->db_full_text_assemble($content, $boolean);

    if (($GLOBALS['DEV_MODE']) || (!has_solemnly_declared(I_UNDERSTAND_SQL_INJECTION))) {
        require_code('database_security_filter');
        $GLOBALS['DB_ESCAPE_STRING_LIST'][$GLOBALS['DB_STATIC_OBJECT']->db_escape_string($content)] = true;
    }

    return $ret;
}


function db_has_subqueries($db)
{
    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_has_subqueries')) {
        return true;
    }

    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    return $GLOBALS['DB_STATIC_OBJECT']->db_has_subqueries($db);
}


function db_has_expression_ordering($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_has_expression_ordering')) {
        return false;
    }
    return $GLOBALS['DB_STATIC_OBJECT']->db_has_expression_ordering($db);
}


function db_uses_offset_syntax($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_has_expression_ordering')) {
        return false;
    }
    return $GLOBALS['DB_STATIC_OBJECT']->db_uses_offset_syntax($db);
}


function db_supports_truncate_table($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (!method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_supports_truncate_table')) {
        return false;
    }
    return $GLOBALS['DB_STATIC_OBJECT']->db_supports_truncate_table($db);
}


function db_start_transaction($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_start_transaction')) {
        $GLOBALS['DB_STATIC_OBJECT']->db_start_transaction($db);
    }
}


function db_end_transaction($db)
{
    if ((is_array($db)) && (count($db) > 4)) { // Okay, we can't be lazy anymore
        $db = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $db);
        _general_db_init();
    }

    if (method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_end_transaction')) {
        $GLOBALS['DB_STATIC_OBJECT']->db_end_transaction($db);
    }
}


function db_escape_string($string)
{
    if ((is_array($GLOBALS['SITE_DB']->connection_read)) && (count($GLOBALS['SITE_DB']->connection_read) > 4)) { // Okay, we can't be lazy anymore
        $GLOBALS['SITE_DB']->connection_read = call_user_func_array(array($GLOBALS['DB_STATIC_OBJECT'], 'db_get_connection'), $GLOBALS['SITE_DB']->connection_read);
        _general_db_init();
    }

    $ret = $GLOBALS['DB_STATIC_OBJECT']->db_escape_string($string);

    if (function_exists('has_solemnly_declared')) {
        if (($GLOBALS['DEV_MODE']) || (!has_solemnly_declared(I_UNDERSTAND_SQL_INJECTION))) {
            require_code('database_security_filter');
            $GLOBALS['DB_ESCAPE_STRING_LIST'][trim($ret, ' %')] = true;
        }
    }

    return $ret;
}


function db_function($function, $args = null)
{
    if ($args === null) {
        $args = array();
    }

    $args = @array_map('strval', $args);

    if (method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_function')) {
        return $GLOBALS['DB_STATIC_OBJECT']->db_function($function, $args);
    }

    switch ($function) {
        case 'CONCAT':
            switch (get_db_type()) {
                // Supported on most

                case 'sqlite':
                    return implode(' || ', $args);

                case 'access':
                    return implode(' & ', $args);
            }
            break;

        case 'REPLACE':
            if (count($args) != 3) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                // Supported on all Comparison of different SQL implementations
                // You don't even need to call this function.
            }
            break;

        case 'SUBSTR':
            if (count($args) != 3) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            if ($args[1] != '1') {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR')); // Can only act as a 'LEFT'
            }
            switch (get_db_type()) {
                case 'sqlserver':
                case 'sqlserver_odbc':
                    $function = 'SUBSTRING'; // Comparison of different SQL implementations
                    break;

                case 'access':
                    $function = 'LEFT'; // Is there an equivalent to the SUBSTRING function in MS Access SQL? - Stack Overflow
                    $args = array($args[0], $args[2]);
                    break;
            }
            break;

        case 'LENGTH':
            if (count($args) != 1) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'mysql':
                case 'mysqli':
                case 'mysql_pdo':
                case 'mysql_dbx':
                    $function = 'CHAR_LENGTH';
                    break;

                case 'sqlserver':
                case 'sqlserver_odbc':
                case 'access':
                    $function = 'LEN';
                    break;
            }
            break;

        case 'RAND':
            if (count($args) != 0) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'postgresql':
                case 'sqlite':
                    $function = 'RANDOM';
                    break;
            }
            break;

        case 'COALESCE':
            if (count($args) != 2) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'access':
                    $function = 'IIF';
                    $args[0] .= ' IS NULL';
                    break;
                default:
                    $all_null = true;
                    foreach ($args as $arg) {
                        if ($arg != 'NULL') {
                            $all_null = false;
                            break;
                        }
                    }
                    if ($all_null) {
                        return 'NULL';
                    }
            }
            break;

        case 'LEAST':
            switch (get_db_type()) {
                case 'sqlite':
                    $function = 'MIN';
                    break;
                case 'sqlserver':
                case 'sqlserver_odbc':
                case 'access':
                    $ret = '(SELECT MIN(X) FROM (';
                    foreach ($args as $i => $arg) {
                        if ($i != 0) {
                            $ret .= ' UNION ALL ';
                        }
                        $ret .= 'SELECT ' . $arg . ' AS X';
                    }
                    $ret .= ') ' . 'x' . md5(uniqid('', true)) . ')';
                    return $ret;
            }
            break;

        case 'GREATEST':
            switch (get_db_type()) {
                case 'sqlite':
                    $function = 'MAX';
                    break;
                case 'sqlserver':
                case 'sqlserver_odbc':
                case 'access':
                    $ret = '(SELECT MAX(X) FROM (';
                    foreach ($args as $i => $arg) {
                        if ($i != 0) {
                            $ret .= ' UNION ALL ';
                        }
                        $ret .= 'SELECT ' . $arg . ' AS X';
                    }
                    $ret .= ') ' . 'x' . md5(uniqid('', true)) . ')';
                    return $ret;
            }
            break;

        case 'MOD':
            if (count($args) != 2) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'access':
                    return $args[0] . ' MOD ' . $args[1];
                case 'postgresql':
                case 'sqlserver':
                case 'sqlserver_odbc':
                case 'sqlite':
                    return $args[0] . ' % ' . $args[1];
            }
            break;

        // This may not be fully supported on all database systems
        case 'GROUP_CONCAT':
            if (count($args) != 2) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'oracle':
                    return '(SELECT LISTAGG(' . $args[0] . ', \',\') WITHIN GROUP (ORDER BY ' . $args[0] . ') FROM ' . $args[1] . ')';
                case 'postgresql':
                    return '(SELECT array_to_string(array_agg(' . $args[0] . '), \',\') FROM ' . $args[1] . ')';
                case 'sqlserver':
                case 'sqlserver_odbc':
                    return 'STUFF((SELECT \',\'+' . $args[0] . ' FROM ' . $args[1] . ' FOR XML PATH(\'\')), 1, 1, \'\')';
                case 'access': // Not fully supported
                    return '(SELECT TOP 1 ' . $args[0] . ' FROM ' . $args[1] . ')';
                case 'ibm': // Not fully supported
                    return '(SELECT ' . $args[0] . ' FROM ' . $args[1] . ' fetch first 1 rows only)';
                case 'xml':
                    return '(SELECT X_GROUP_CONCAT(' . $args[0] . ') FROM ' . $args[1] . ')';
                case 'mysql':
                case 'mysqli':
                case 'mysql_pdo':
                case 'mysql_dbx':
                case 'sqlite':
                default:
                    return '(SELECT GROUP_CONCAT(' . $args[0] . ') FROM ' . $args[1] . ')';
            }
            break;

        case 'X_ORDER_BY_BOOLEAN':
            if (count($args) != 1) {
                fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
            }
            switch (get_db_type()) {
                case 'sqlserver':
                case 'sqlserver_odbc':
                    return '(CASE WHEN ' . $args[0] . ' THEN 0 ELSE 1 END)';

                default:
                    return $args[0];
            }
            break;
    }

    if (get_db_type() == 'xml') {
        $function = 'X_' . $function;
    }

    // Default handling
    return $function . '(' . implode(',', $args) . ')';
}


function get_table_count_approx($table, $where = null, $where_clause = null, $db = null)
{
    if ($db === null) {
        $db = $GLOBALS['SITE_DB'];
    }

    if ($where === null) {
        $where = array();
    }

    if (method_exists($GLOBALS['DB_STATIC_OBJECT'], 'get_table_count_approx')) {
        $test = $GLOBALS['DB_STATIC_OBJECT']->get_table_count_approx($table, $where, $where_clause, $db);
        if ($test !== null) {
            return $test;
        }
    }

    return $db->query_select_value($table, 'COUNT(*)', $where, ($where_clause === null) ? '' : (' AND ' . $where_clause));
}


function db_cast($field, $type)
{
    if (method_exists($GLOBALS['DB_STATIC_OBJECT'], 'db_cast')) {
        return $GLOBALS['DB_STATIC_OBJECT']->db_cast($field, $type);
    }

    switch ($type) {
        case 'CHAR':
        case 'INT':
        case 'FLOAT':
            $_type = $type;
            break;

        default:
            fatal_exit(do_lang_tempcode('INTERNAL_ERROR'));
    }

    return 'CAST(' . $field . ' AS ' . $_type . ')';
}


function get_db_type()
{
    global $SITE_INFO;
    if (!isset($SITE_INFO['db_type'])) {
        return is_dir(get_custom_file_base() . '/uploads/website_specific/' . get_db_site()) ? 'xml' : 'mysql';
    }
    $ret = $SITE_INFO['db_type'];
    if ($ret === 'mysql' && !function_exists('mysql_connect')) {
        $ret = 'mysqli';
    }
    return $ret;
}


function get_use_persistent()
{
    global $SITE_INFO;
    return (!empty($SITE_INFO['use_persistent'])) ? ($SITE_INFO['use_persistent'] == '1') : false;
}


function get_table_prefix()
{
    global $SITE_INFO;
    if (!isset($SITE_INFO['table_prefix'])) {
        return 'cms' . strval(cms_version()) . '_';
    }
    return $SITE_INFO['table_prefix'];
}


function get_db_site_host()
{
    global $SITE_INFO;
    return (!empty($SITE_INFO['db_site_host'])) ? $SITE_INFO['db_site_host'] : 'localhost';
}


function get_db_site()
{
    global $SITE_INFO;
    if (empty($SITE_INFO['db_site'])) {
        return basename(get_file_base());
    }
    return $SITE_INFO['db_site'] . (($GLOBALS['CURRENT_SHARE_USER'] === null) ? '' : ('_' . $GLOBALS['CURRENT_SHARE_USER']));
}


function get_db_site_user()
{
    global $SITE_INFO;
    if ($GLOBALS['CURRENT_SHARE_USER'] !== null) {
        return substr(md5($SITE_INFO['db_site_user'] . '_' . $GLOBALS['CURRENT_SHARE_USER']), 0, 16);
    }
    return (!empty($SITE_INFO['db_site_user'])) ? $SITE_INFO['db_site_user'] : 'root';
}


function get_db_site_password()
{
    global $SITE_INFO;
    return array_key_exists('db_site_password', $SITE_INFO) ? $SITE_INFO['db_site_password'] : '';
}


function get_db_forums_host()
{
    global $SITE_INFO;
    return (!empty($SITE_INFO['db_forums_host'])) ? $SITE_INFO['db_forums_host'] : (!empty($SITE_INFO['db_site_host']) ? $SITE_INFO['db_site_host'] : 'localhost');
}


function get_db_forums()
{
    global $SITE_INFO;
    if (empty($SITE_INFO['db_forums'])) {
        return get_db_site();
    }
    return $SITE_INFO['db_forums'] . (($GLOBALS['CURRENT_SHARE_USER'] === null) ? '' : ('_' . $GLOBALS['CURRENT_SHARE_USER']));
}


function get_db_forums_user()
{
    global $SITE_INFO;
    if (empty($SITE_INFO['db_forums_user'])) {
        return get_db_site_user();
    }
    if ($GLOBALS['CURRENT_SHARE_USER'] !== null) {
        return substr(md5($SITE_INFO['db_forums_user'] . '_' . $GLOBALS['CURRENT_SHARE_USER']), 0, 16);
    }
    return $SITE_INFO['db_forums_user'];
}


function get_db_forums_password()
{
    global $SITE_INFO;
    if (!array_key_exists('db_forums_password', $SITE_INFO)) {
        return get_db_site_password();
    }
    return $SITE_INFO['db_forums_password'];
}


function is_on_multi_site_network($db = null)
{
    static $cache = null;
    if ($db === null && $cache !== null) {
        return $cache;
    }

    if (get_forum_type() == 'none') {
        $cache = false;
        return false;
    }

    if ($db !== null) {
        $ret = !is_forum_db($db); // If passed connection is not the same as the forum connection, then it must be a multi-site-network
        return $ret;
    }
    $cache = ((get_db_site_host() != get_db_forums_host()) || (get_db_site() != get_db_forums()) || (isset($GLOBALS['FORUM_DRIVER'])) && ($GLOBALS['FORUM_DRIVER']->get_drivered_table_prefix() != get_table_prefix()));
    return $cache;
}


function is_forum_db($db)
{
    if (isset($db->is_forum_db)) {
        return $db->is_forum_db;
    }

    if (!is_on_multi_site_network()) {
        // Not on a multi-site-network
        return false;
    }

    $ret = ((isset($GLOBALS['FORUM_DB'])) && ($db->connection_write == $GLOBALS['FORUM_DB']->connection_write) && ($db->connection_write != $GLOBALS['SITE_DB']->connection_write));
    $db->is_forum_db = $ret;
    return $ret;
}


class DatabaseConnector
{
    public $table_prefix;
    public $connection_read, $connection_write;

    public $text_lookup_original_cache;
    public $text_lookup_cache;

    public $table_exists_cache;

    public $static_ob;

    public $dedupe_mode = false;

   
    public function __construct($db_name, $db_host, $db_user, $db_password, $table_prefix, $fail_ok = false, $static = null)
    {
        $this->text_lookup_original_cache = array();
        $this->text_lookup_cache = array();
        $this->table_exists_cache = array();

        $servers = explode(',', $db_host);
        if (count($servers) == 1) {
            $this->connection_write = array(get_use_persistent(), $db_name, $db_host, $db_user, $db_password, $fail_ok);
            $this->connection_read = $this->connection_write;
        } else {
            $this->connection_write = array(get_use_persistent(), $db_name, $servers[0], $db_user, $db_password, $fail_ok);
            $min = (count($servers) == 2) ? 0 : 1;
            $this->connection_read = array(get_use_persistent(), $db_name, $servers[mt_rand($min, count($servers) - 1)], $db_user, $db_password, $fail_ok);
        }
        $this->table_prefix = $table_prefix;

        if ($static !== null) {
            $this->static_ob = $static;
        } else {
            $this->static_ob = $GLOBALS['DB_STATIC_OBJECT'];
        }
    }

   
    public function get_table_prefix()
    {
        return $this->table_prefix;
    }

   
    public function table_exists($table_name, $really = false)
    {
        if ($really && strpos(get_db_type(), 'mysql') !== false) {
            // Just works with MySQL (too complex to do for all SQL's sql list all tables - SQL)
            $full_table_name = $this->get_table_prefix() . $table_name;
            $rows = $this->query("SHOW TABLES LIKE '" . $full_table_name . "'");
            foreach ($rows as $row) {
                foreach ($row as $field) {
                    if ($field == $full_table_name) {
                        return true;
                    }
                }
            }
            return false;
        }

        if (array_key_exists($table_name, $this->table_exists_cache)) {
            return $this->table_exists_cache[$table_name];
        }

        $test = $this->query_select_value_if_there('db_meta', 'm_name', array('m_table' => $table_name));
        $this->table_exists_cache[$table_name] = ($test !== null);
        return $this->table_exists_cache[$table_name];
    }

   
    public function create_table($table_name, $fields, $skip_size_check = false, $skip_null_check = false, $save_bytes = false)
    {
        require_code('database_helper');
        _helper_create_table($this, $table_name, $fields, $skip_size_check, $skip_null_check, $save_bytes);
    }

   
    public function create_index($table_name, $index_name, $fields, $unique_key_fields = null)
    {
        require_code('database_helper');
        _helper_create_index($this, $table_name, $index_name, $fields, $unique_key_fields);
    }

   
    public function bulk_insert_flip($maps)
    {
        $data = array();
        foreach ($maps as $map) {
            foreach ($map as $key => $val) {
                if (!isset($data[$key])) {
                    $data[$key] = array();
                }
                $data[$key][] = $val;
            }
        }
        return $data;
    }

   
    public function query_insert($table, $map, $ret = false, $fail_ok = false, $save_as_volatile = false)
    {
        $keys = '';
        $all_values = array(); // will usually only have a single entry; for bulk-inserts it will have as many as there are inserts

        $eis = $this->static_ob->db_empty_is_null();

        foreach ($map as $key => $value) {
            if ($keys !== '') {
                $keys .= ', ';
            }
            $keys .= $key;

            $_value = (!is_array($value)) ? array($value) : $value;

            $v = mixed();
            foreach ($_value as $i => $v) {
                if (!isset($all_values[$i])) {
                    $all_values[$i] = '';
                }
                $values = $all_values[$i];

                if ($values !== '') {
                    $values .= ', ';
                }

                if ($value === null) {
                    if (($eis) && ($v === '')) {
                        $values .= '\' \'';
                    } else {
                        $values .= 'NULL';
                    }
                } else {
                    if (($eis) && ($v === '')) {
                        $v = ' ';
                    }
                    if (is_integer($v)) {
                        $values .= strval($v);
                    } elseif (is_float($v)) {
                        $values .= float_to_raw_string($v, 10);
                    } elseif (($key === 'begin_num') || ($key === 'end_num')) {
                        $values .= $v; // FUDGE: for all our known large unsigned integers
                    } else {
                        $values .= '\'' . $this->static_ob->db_escape_string($v) . '\'';
                    }
                }

                $all_values[$i] = $values; // essentially appends, as $values was loaded from former $all_values[$i] value
            }
        }

        if (count($all_values) === 1) { // usually $all_values only has length of 1
            if ((function_exists('get_value')) && (get_value('enable_delayed_inserts') === '1') && (in_array($table, array('stats', 'banner_clicks', 'member_tracking', 'usersonline_track', 'download_logging'))) && (substr(get_db_type(), 0, 5) === 'mysql')) {
                $query = 'INSERT DELAYED INTO ' . $this->table_prefix . $table . ' (' . $keys . ') VALUES (' . $all_values[0] . ')';
            } else {
                $query = 'INSERT INTO ' . $this->table_prefix . $table . ' (' . $keys . ') VALUES (' . $all_values[0] . ')';
            }
        } else {
            if (count($all_values) === 0) {
                return null;
            }

            // So we can do batch inserts…
            $all_v = '';
            foreach ($all_values as $v) {
                if ($all_v !== '') {
                    $all_v .= ', ';
                }
                $all_v .= '(' . $v . ')';
            }

            $query = 'INSERT INTO ' . $this->table_prefix . $table . ' (' . $keys . ') VALUES ' . $all_v;
        }

        return $this->_query($query, null, null, $fail_ok, $ret, null, '', $save_as_volatile);
    }

   
    protected function _get_where_expand($table, $select_map = null, $where_map = null, $end = '')
    {
        global $DEV_MODE;

        if ($select_map === null) {
            $select_map = array('*');
        }

        $select = '';
        foreach ($select_map as $key) {
            //if (!is_string($key)) $key = strval($key);   Should not happen, but won't cause a problem if does. Don't do this check for performance reasons.

            if ($select !== '') {
                $select .= ',';
            }

            $select .= $key;
        }

        $where = '';
        if (($where_map !== null) && ($where_map != array())) {
            foreach ($where_map as $key => $value) {
                if ($DEV_MODE) {
                    if (!is_string($key)) {
                        fatal_exit('Parameters to the database API given in the wrong order. Please check the function call.');
                    }
                }

                if ($where !== '') {
                    $where .= ' AND ';
                }

                if (is_float($value)) {
                    $where .= $key . '=' . float_to_raw_string($value, 10);
                } elseif (is_integer($value)) {
                    $where .= $key . '=' . strval($value);
                } elseif (($key === 'begin_num') || ($key === 'end_num')) {
                    $where .= $key . '=' . $value; // FUDGE: for all our known large unsigned integers
                } else {
                    if ($value === null) {
                        $where .= $key . ' IS NULL';
                    } else {
                        if (($value === '') && ($this->static_ob->db_empty_is_null())) {
                            $value = ' ';
                        }

                        $where .= db_string_equal_to($key, $value);
                    }
                }
            }

            return 'SELECT ' . $select . ' FROM ' . $table . ' WHERE (' . $where . ') ' . $end;
        }
        if (substr(ltrim($end), 0, 6) !== 'WHERE ') {
            $end = 'WHERE 1=1 ' . $end; // We force a WHERE so that code of ours that alters queries can work robustly
        }
        return 'SELECT ' . $select . ' FROM ' . $table . ' ' . $end;
    }

   
    public function query_select_value($table, $selected_value, $where_map = null, $end = '', $fail_ok = false, $lang_fields = null)
    {
        $values = $this->query_select($table, array($selected_value), $where_map, $end, 1, null, $fail_ok, $lang_fields);
        if ($values === null) {
            return null; // error
        }
        if (!array_key_exists(0, $values)) {
            fatal_exit(do_lang_tempcode('QUERY_NULL', escape_html($this->_get_where_expand($this->table_prefix . $table, array($selected_value), $where_map, $end)))); // No result found
        }
        return $this->_query_select_value($values);
    }

   
    protected function _query_select_value($values)
    {
        if (!array_key_exists(0, $values)) {
            return null; // No result found
        }
        $first = $values[0];
        $v = current($first); // Result found. Maybe a value of 'null'
        return $v;
    }

   
    public function query_select_value_if_there($table, $select, $where_map = null, $end = '', $fail_ok = false, $lang_fields = null)
    {
        $values = $this->query_select($table, array($select), $where_map, $end, 1, null, $fail_ok, $lang_fields);
        if ($values === null) {
            return null; // error
        }
        return $this->_query_select_value($values);
    }

   
    public function query_value_if_there($query, $fail_ok = false, $skip_safety_check = false, $lang_fields = null)
    {
        global $DEV_MODE;

        if (($DEV_MODE) || (!has_solemnly_declared(I_UNDERSTAND_SQL_INJECTION))) {
            if (!is_bool($fail_ok)) {
                fatal_exit('You probably wanted to use query_select_value_if_there');
            }

            if (!$skip_safety_check) {
                require_code('database_security_filter');

                if (is_simple_query($query)) {
                    fatal_exit('It is highly recommended to use query_select/query_update/query_delete helper methods instead of the \'query\' method for this query – in order to avoid having to write any SQL');
                }

                if (!has_escaped_dynamic_sql($query)) {
                    fatal_exit('Dynamic SQL has not been escaped properly in ' . $query);
                }
            }
        }

        $values = $this->query($query, 1, null, $fail_ok, $skip_safety_check, $lang_fields);
        if ($values === null) {
            return null; // error
        }
        return $this->_query_select_value($values);
    }

   
    public function query_select($table, $select = null, $where_map = null, $end = '', $max = null, $start = null, $fail_ok = false, $lang_fields = null)
    {
        $full_table = $this->table_prefix . $table;

        $field_prefix = '';

        if ($select === null) {
            $select = array('*');
        }

        $this->_automatic_lang_fields($table, $full_table, $select, $where_map, $end, $lang_fields);

        return $this->_query($this->_get_where_expand($full_table, $select, $where_map, $end), $max, $start, $fail_ok, false, $lang_fields, $field_prefix);
    }

   
    protected function _automatic_lang_fields(&$table, &$full_table, &$select, &$where_map, &$end, &$lang_fields)
    {
        // Optimisation for entirely automatic translate table linkage (only done on non-joins, as this removes a whole lot of potential complexities – if people are doing joins they go a little further to do this manually anyway; also we make sure we're operating on our site's table prefix so we don't collect meta info for the wrong table set)
        if ($lang_fields === null) {
            if (
                ($table !== 'translate') &&
                (strpos($table, ' ') === false) &&
                (strpos($end, 'GROUP BY ') === false) &&
                ((isset($GLOBALS['SITE_DB'])) &&
                ($this->table_prefix === $GLOBALS['SITE_DB']->table_prefix) || (get_forum_type() === 'cns'))
            ) {
                global $TABLE_LANG_FIELDS_CACHE;
                $lang_fields_provisional = isset($TABLE_LANG_FIELDS_CACHE[$table]) ? $TABLE_LANG_FIELDS_CACHE[$table] : array();
                $lang_fields = array();

                if ($lang_fields_provisional !== array()) {
                    $full_table .= ' main';

                    foreach ($select as $i => $s) {
                        if (!is_string($s)) {
                            $lang_fields_provisional = array();
                            break; // Bad API call, but we'll let it fail naturally
                        }

                        if (preg_match('#^[A-Za-z\_\*]+$#', $s) !== 0) {
                            $select[$i] = 'main.' . $s;
                        }
                    }
                    if ($where_map !== null) {
                        foreach ($where_map as $i => $s) {
                            if (!is_string($i)) {
                                $lang_fields_provisional = array();
                                break; // Bad API call, but we'll let it fail naturally
                            }

                            if (preg_match('#^[A-Za-z\_]+$#', $i) !== 0) {
                                unset($where_map[$i]);
                                $where_map['main.' . $i] = $s;
                            }
                        }
                    }
                    if ($end !== '') {
                        $end = cms_preg_replace_safe('#(^|,|\s)([a-z]+)($|,|\s)#', '${1}main.${2}${3}', $end);
                    }

                    $field_prefix = 'main.';

                    $select_inv = array_flip($select);

                    foreach ($lang_fields_provisional as $lang_field => $field_type) {
                        if (
                            (isset($select_inv[$field_prefix . '*'])) ||

                            (isset($select_inv[$field_prefix . $lang_field])) ||

                            (isset($select_inv['t_' . $lang_field . '.text_original'])) ||
                            ((!is_null($where_map)) && (isset($where_map['t_' . $lang_field . '.text_original']))) ||
                            (strpos($end, 't_' . $lang_field . '.text_original') !== false)
                        ) {
                            $lang_fields[$lang_field] = $field_type;
                        }
                    }
                }
            }
        }
    }

   
    public function query_parameterised($query, $parameters, $max = null, $start = null, $fail_ok = false, $skip_safety_check = false, $lang_fields = null, $field_prefix = '')
    {
        if (isset($parameters['prefix'])) {
            warn_exit('prefix is a reserved parameter, you should not set it.');
        }

        $parameters += array('prefix' => $this->get_table_prefix());
        foreach ($parameters as $key => $val) {
            if (!is_string($val)) {
                $val = strval($val);
            }

            if ($key === 'prefix') {
                // Special case, not within quotes.
                $search = '#{' . preg_quote($key, '#') . '}#';
                $replace = $val;
            } else {
                // NB: It will always add quotes around in the query (if not already there), as that is needed for escaping to be valid.
                $search = '#\'?{' . preg_quote($key, '#') . '\}\'?#';
                $replace = '\'' . db_escape_string($val) . '\'';
            }
            $query = preg_replace($search, $replace, $query);
        }

        return $this->query($query, $max, $start, $fail_ok, $skip_safety_check, $lang_fields, $field_prefix);
    }

   
    public function query($query, $max = null, $start = null, $fail_ok = false, $skip_safety_check = false, $lang_fields = null, $field_prefix = '')
    {
        global $DEV_MODE;
        if (!$skip_safety_check && stripos($query, 'union') !== false && strpos(get_db_type(), 'mysql') !== false) {
            $_query = cms_preg_replace_safe('#\s#', ' ', strtolower($query));
            $queries = 1;//substr_count($_query,'insert into ')+substr_count($_query,'replace into ')+substr_count($_query,'update ')+substr_count($_query,'select ')+substr_count($_query,'delete from '); Not reliable
            if ((strpos(preg_replace('#\'[^\']*\'#', '\'\'', str_replace('\\'', '', $_query)), ' union ') !== false) || ($queries > 1)) {
                log_hack_attack_and_exit('SQL_INJECTION_HACK', $query);
            }

            if (function_exists('has_solemnly_declared')) {
                if (($DEV_MODE) || (!has_solemnly_declared(I_UNDERSTAND_SQL_INJECTION))) {
                    require_code('database_security_filter');

                    if (is_simple_query($query)) {
                        fatal_exit('It is highly recommended to use query_select/query_update/query_delete method instead of the \'query\' method for this query');
                    }

                    if (!has_escaped_dynamic_sql($query)) {
                        fatal_exit('Dynamic SQL has not been escaped properly');
                    }
                }
            }
        }

        return $this->_query($query, $max, $start, $fail_ok, false, $lang_fields, $field_prefix);
    }

   
    public function translate_field_ref($field_name)
    {
        if (multi_lang_content()) {
            return 't_' . $field_name . '.text_original';
        }
        return $field_name;
    }

   
    public function _query($query, $max = null, $start = null, $fail_ok = false, $get_insert_id = false, $lang_fields = null, $field_prefix = '', $save_as_volatile = false)
    {
        global $QUERY_COUNT, $NO_QUERY_LIMIT, $QUERY_LOG, $QUERY_LIST, $DEV_MODE, $IN_MINIKERNEL_VERSION, $QUERY_FILE_LOG, $UPON_QUERY_HOOKS_CACHE;

        if ($QUERY_FILE_LOG !== null) {
            flock($QUERY_FILE_LOG, LOCK_EX);
            fseek($QUERY_FILE_LOG, 0, SEEK_END);
            fwrite($QUERY_FILE_LOG, $query . ';' . "\n\n");
            flock($QUERY_FILE_LOG, LOCK_UN);
        }

        if ($DEV_MODE) {
            if (!$GLOBALS['NO_DB_SCOPE_CHECK']) {
                if ((!multi_lang_content()) && (strpos($query, $this->get_table_prefix() . 'translate') !== false) && (strpos($query, 'DROP TABLE') === false) && (strpos($query, 'DROP INDEX') === false) && (strpos($query, 'ALTER TABLE') === false) && (strpos($query, 'CREATE TABLE') === false)) {
                    fatal_exit('Assumption of multi-lang-content being on, and it\'s not');
                }

                if ((get_forum_type() != 'none') && (strpos($query, get_table_prefix() . 'f_') !== false) && (strpos($query, get_table_prefix() . 'f_') < 100) && (strpos($query, 'f_welcome_emails') === false) && (!is_forum_db($this)) && (is_cns_satellite_site())) {
                    fatal_exit('Using Conversr queries on the wrong driver');
                }
            }
        }

        if (!$NO_QUERY_LIMIT) {
            $QUERY_COUNT++;
           
        }
        if ((!headers_sent()) && (function_exists('fb')) && (get_param_integer('keep_firephp_queries', 0) === 1)) {
            fb('Query: ' . $query);
        }

        if (($QUERY_COUNT === 250) && (get_param_integer('keep_no_query_limit', 0) === 0) && ($GLOBALS['RELATIVE_PATH'] !== '_tests') && (count($_POST) === 0) && (get_page_name() !== 'admin_importer') && (!$IN_MINIKERNEL_VERSION) && (get_param_string('special_page_type', '') !== 'query')) {
            cms_profile_start_for('_query:HIGH_VOLUME_ALERT');

            $NO_QUERY_LIMIT = true;
            $log_path = get_custom_file_base() . '/data_custom/big_query_screens.log';
            if (is_writable_wrap($log_path)) {
                $myfile = fopen($log_path, 'at');
                flock($myfile, LOCK_EX);
                fseek($myfile, 0, SEEK_END);
                fwrite($myfile, get_self_url_easy(true) . "\n");
                flock($myfile, LOCK_UN);
                fclose($myfile);
            }
            if ($DEV_MODE) {
                $QUERY_COUNT = 0;
                fatal_exit(do_lang_tempcode('TOO_MANY_QUERIES'));
            }

            cms_profile_end_for('_query:HIGH_VOLUME_ALERT');
        }

        // Optimisation: Load language fields in advance so we don't need to do additional details when calling get_translated_* functions
        $lang_strings_expecting = array();
        if ($lang_fields !== null) {
            if (multi_lang_content()) {
                if ((strpos($query, 'text_original') !== false) || (function_exists('user_lang')) && ((is_null($start)) || ($start < 200))) {
                    $lang = function_exists('user_lang') ? user_lang() : get_site_default_lang(); // We can we assume this, as we will cache against it – if subsequently code wants something else it'd be a cache miss which is fine

                    foreach ($lang_fields as $field => $field_type) {
                        $field_stripped = preg_replace('#.*\.#', '', $field);

                        $join = ' LEFT JOIN ' . $this->table_prefix . 'translate t_' . $field_stripped . ' ON t_' . $field_stripped . '.id=' . $field_prefix . $field;
                        $join .= ' AND ' . db_string_equal_to('t_' . $field_stripped . '.language', $lang);

                        $_query = strtoupper($query);
                        $from_pos = strpos($_query, ' FROM ');
                        $where_pos = strpos($_query, ' WHERE ');
                        $from_in_subquery = ($from_pos !== false) && (strpos(substr($_query, 0, $from_pos), '(SELECT') !== false); // FROM clause seems to be in a subquery, so it's mroe robust for us to work backwards
                        $where_in_subquery = ($where_pos !== false) && (strpos(substr($_query, 0, $where_pos), '(SELECT') !== false); // WHERE clause seems to be in a subquery, so it's mroe robust for us to work backwards
                        if ($from_in_subquery || $where_in_subquery) {
                            $from_pos = strrpos($_query, ' FROM ');
                            $where_pos = strrpos($_query, ' WHERE ');
                        }
                        if ($where_pos === false) {
                            $_where_pos = 0;
                            do {
                                $_where_pos = strpos($_query, ' GROUP BY ', $_where_pos + 1);
                                if ($_where_pos !== false) {
                                    $where_pos = $_where_pos;
                                }
                            } while ($_where_pos !== false);
                        }
                        if ($where_pos === false) {
                            $_where_pos = 0;
                            do {
                                $_where_pos = strpos($_query, ' ORDER BY ', $_where_pos + 1);
                                if ($_where_pos !== false) {
                                    $where_pos = $_where_pos;
                                }
                            } while ($_where_pos !== false);
                        }
                        if ($where_pos !== false) {
                            $query = substr($query, 0, $where_pos) . $join . substr($query, $where_pos);
                        } else {
                            $query .= $join;
                        }

                        $before_from = substr($query, 0, $from_pos);
                        if (preg_match('#(COUNT|SUM|AVG|MIN|MAX)\(#', $before_from) === 0) { // If we're returning full result sets (as opposed probably to just joining so we can use translate_field_ref)
                            $original = 't_' . $field_stripped . '.text_original AS t_' . $field_stripped . '__text_original';
                            $parsed = 't_' . $field_stripped . '.text_parsed AS t_' . $field_stripped . '__text_parsed';

                            $query = $before_from . ',' . $original . ',' . $parsed . substr($query, $from_pos);

                            $lang_strings_expecting[] = array($field, 't_' . $field_stripped . '__text_original', 't_' . $field_stripped . '__text_parsed');
                        }
                    }
                }
            } else {
                foreach ($lang_fields as $field => $field_type) {
                    if (strpos($field_type, '__COMCODE') !== false) {
                        $_query = strtoupper($query);
                        $from_pos = strpos($_query, ' FROM ');
                        if (($from_pos !== false) && (strpos(substr($_query, 0, $from_pos), '(SELECT') !== false)) {
                            $from_pos = strrpos($_query, ' FROM ');
                        }
                        $before_from = substr($query, 0, $from_pos);

                        if (preg_match('#(COUNT|SUM|AVG|MIN|MAX)\(#', $before_from) === 0) { // If we're returning full result sets (as opposed probably to just joining so we can use translate_field_ref)
                            $source_user = $field . '__source_user';
                            $parsed = $field . '__text_parsed';

                            $query = $before_from . ',' . $source_user . ',' . $parsed . substr($query, $from_pos);
                        }
                    }
                }
            }
        }

        if ($start < 0) {
            $start = 0;
        }
        if ($max < 0) {
            $max = 1;
        }

        if ($QUERY_LOG) {
            $before = microtime(true);
        }
        $sub = substr($query, 0, 6); // NB: We don't get 7, because it's time-consuming to check for space/tab/new-lines after 'SELECT', so we'll make the correct assumption SELECT is not a stem of any other keyword
        if ($sub === 'SELECT' || $sub === 'select' || $sub === '(SELEC' || $sub === '(selec') {
            $connection = &$this->connection_read;
        } else {
            $connection = &$this->connection_write;
        }
        if ((is_array($connection)) && (count($connection) > 4)) { // Okay, we can't be lazy anymore
            $connection = call_user_func_array(array($this->static_ob, 'db_get_connection'), $connection);
            _general_db_init();
        }

        // Special handling for searches, which are slow and specific - we want to recognise if previous active searches were the same and kill them (as this would have been a double form submit)
        if (($this->dedupe_mode) && (substr(get_db_type(), 0, 5) === 'mysql')) {
            $query .= ''; // Identify query to session, for accurate de-duping

            $real_query = $query;
            if (($max !== null) && ($start !== null)) {
                $real_query .= ' LIMIT ' . strval($start) . ',' . strval($max);
            } elseif ($max !== null) {
                $real_query .= ' LIMIT ' . strval($max);
            } elseif ($start !== null) {
                $real_query .= ' LIMIT ' . strval($start) . ',30000000';
            }

            $ret = $this->static_ob->db_query('SHOW FULL PROCESSLIST', $connection, null, null, true);
            if (is_array($ret)) {
                foreach ($ret as $process) {
                    if ($process['Info'] === $real_query) {
                        $this->static_ob->db_query('KILL ' . strval($process['Id']), $connection, null, null, true);
                    }
                }
            }
        }

        // Run hooks, if any exist
        if ($UPON_QUERY_HOOKS_CACHE === null) {
            if ((!running_script('restore')) && (function_exists('find_all_hooks')) && (!isset($GLOBALS['DOING_USERS_INIT']))) {
                $UPON_QUERY_HOOKS_CACHE = array();
                $hooks = find_all_hooks('systems', 'upon_query');
                foreach ($hooks as $hook => $hook_dir) {
                    require_code('hooks/systems/upon_query/' . filter_naughty_harsh($hook), false, $hook_dir == 'sources_custom');
                    $UPON_QUERY_HOOKS_CACHE[$hook] = object_factory('Hook_upon_query_' . filter_naughty_harsh($hook), true);
                }
            }
        }
        if ($UPON_QUERY_HOOKS_CACHE !== null) {
            foreach ($UPON_QUERY_HOOKS_CACHE as $ob) {
                if (($ob !== null) && (method_exists($ob, 'run_pre'))) {
                    $ob->run_pre($this, $query, $max, $start, $fail_ok, $get_insert_id);
                }
            }
        }

        // Run/log query
        $ret = $this->static_ob->db_query($query, $connection, $max, $start, $fail_ok, $get_insert_id, false, $save_as_volatile);
        if ($QUERY_LOG) {
            $after = microtime(true);
            $text = (!is_null($max)) ? ($query . ' (' . (is_null($start) ? '0' : strval($start)) . '-' . strval((is_null($start) ? 0 : $start) + $max) . ')') : $query;
            $out = array('time' => ($after - $before), 'text' => $text, 'rows' => is_array($ret) ? count($ret) : null);
            $QUERY_LIST[] = $out;
        }
       

        // Run hooks, if any exist
        if ($UPON_QUERY_HOOKS_CACHE !== null) {
            foreach ($UPON_QUERY_HOOKS_CACHE as $ob) {
                if (($ob !== null) && (method_exists($ob, 'run_post'))) {
                    $ob->run_post($this, $query, $max, $start, $fail_ok, $get_insert_id, $ret);
                }
            }
        }

        if ($ret !== null) {
            foreach ($lang_strings_expecting as $bits) {
                list($field, $original, $parsed) = $bits;

                if ((isset($ret[300])) && (strpos($query, 'theme_images') === false) && (strpos($query, 'group_category_access') === false) && (strpos($query, 'group_privileges') === false) && (strpos($query, 'config') === false)) {
                    cms_profile_start_for('_query:MANY_RESULTS_ALERT');
                    cms_profile_end_for('_query:MANY_RESULTS_ALERT', $query);
                }

                if (multi_lang_content()) {
                    // Copy results to lang cache, but only if not null AND unset to avoid any confusion
                    foreach ($ret as $i => $row) {
                        if (!isset($row[$field])) {
                            continue; // Probably dereferenced to text_original in WHERE, but not selected
                        }

                        $entry = $row[preg_replace('#^.*\.#', '', $field)];

                        if (($row[$original] !== null) && (count($this->text_lookup_original_cache) <= 1000)) {
                            $this->text_lookup_original_cache[$entry] = $row[$original];
                        }
                        if (($row[$parsed] !== null) && (count($this->text_lookup_cache) <= 1000)) {
                            $this->text_lookup_cache[$entry] = $row[$parsed];
                        }

                        unset($ret[$i][$original]);
                        unset($ret[$i][$parsed]);
                    }
                }
            }
        }

        return $ret;
    }

   
    public function query_update($table, $update_map, $where_map = null, $end = '', $max = null, $start = null, $num_touched = false, $fail_ok = false)
    {
        $where = '';
        $update = '';

        $value = mixed();

        if ($where_map !== null) {
            foreach ($where_map as $key => $value) {
                if ($where !== '') {
                    $where .= ' AND ';
                }

                if (is_float($value)) {
                    $where .= $key . '=' . float_to_raw_string($value, 10);
                } elseif (is_integer($value)) {
                    $where .= $key . '=' . strval($value);
                } elseif (($key === 'begin_num') || ($key === 'end_num')) {
                    $where .= $key . '=' . $value; // FUDGE: for all our known large unsigned integers
                } else {
                    if ($value === null) {
                        $where .= $key . ' IS NULL';
                    } else {
                        if (($value === '') && ($this->static_ob->db_empty_is_null())) {
                            $value = ' ';
                        }
                        $where .= db_string_equal_to($key, $value);
                    }
                }
            }
        }

        foreach ($update_map as $key => $value) {
            if (($value === STRING_MAGIC_NULL) || ($value === INTEGER_MAGIC_NULL)) {
                continue;
            }
            if ($update !== '') {
                $update .= ', ';
            }

            if ($value === null) {
                $update .= $key . '=NULL';
            } else {
                if (is_float($value)) {
                    $update .= $key . '=' . float_to_raw_string($value, 10);
                } elseif (is_integer($value)) {
                    $update .= $key . '=' . strval($value);
                } elseif (($key === 'begin_num') || ($key === 'end_num')) {
                    $where .= $key . '=' . $value; // FUDGE: for all our known large unsigned integers
                } else {
                    $update .= $key . '=\'' . $this->static_ob->db_escape_string($value) . '\'';
                }
            }
        }
        if ($update === '') {
            return null;
        }

        if ($where === '') {
            return $this->_query('UPDATE ' . $this->table_prefix . $table . ' SET ' . $update . ' ' . $end, $max, $start, $fail_ok, $num_touched);
        } else {
            return $this->_query('UPDATE ' . $this->table_prefix . $table . ' SET ' . $update . ' WHERE (' . $where . ') ' . $end, $max, $start, $fail_ok, $num_touched);
        }
    }

   
    public function query_delete($table, $where_map = null, $end = '', $max = null, $start = null, $fail_ok = false)
    {
        if ($where_map === null) {
            if (($end === '') && (is_null($max)) && (is_null($start)) && (db_supports_truncate_table($GLOBALS['SITE_DB']->connection_read))) {
                $this->_query('TRUNCATE ' . $this->table_prefix . $table, null, null, $fail_ok);
            } else {
                $this->_query('DELETE FROM ' . $this->table_prefix . $table . ' ' . $end, $max, $start, $fail_ok);
            }
            return;
        }

        $where = '';

        foreach ($where_map as $key => $value) {
            if ($where !== '') {
                $where .= ' AND ';
            }

            if (is_float($value)) {
                $where .= $key . '=' . float_to_raw_string($value, 10);
            } elseif (is_integer($value)) {
                $where .= $key . '=' . strval($value);
            } elseif (($key === 'begin_num') || ($key === 'end_num')) {
                $where .= $key . '=' . $value; // FUDGE: for all our known large unsigned integers
            } else {
                if ($value === null) {
                    $where .= $key . ' IS NULL';
                } else {
                    if (($value === '') && ($this->static_ob->db_empty_is_null())) {
                        $where .= $key . ' IS NULL'; // $value = ' ';
                    } else {
                        $where .= db_string_equal_to($key, $value);
                    }
                }
            }
        }

        $query = 'DELETE FROM ' . $this->table_prefix . $table . ' WHERE (' . $where . ') ' . $end;
        $this->_query($query, $max, $start, $fail_ok);
    }

   
    public function delete_index_if_exists($table_name, $index_name)
    {
        require_code('database_helper');
        _helper_delete_index_if_exists($this, $table_name, $index_name);
    }

   
    public function drop_table_if_exists($table)
    {
        require_code('database_helper');
        _helper_drop_table_if_exists($this, $table);
    }

   
    public function rename_table($old, $new)
    {
        require_code('database_helper');
        _helper_rename_table($this, $old, $new);
    }

   
    public function add_table_field($table_name, $name, $_type, $default = null)
    {
        require_code('database_helper');
        _helper_add_table_field($this, $table_name, $name, $_type, $default);
    }

   
    public function alter_table_field($table_name, $name, $_type, $new_name = null)
    {
        require_code('database_helper');
        _helper_alter_table_field($this, $table_name, $name, $_type, $new_name);
    }

   
    public function change_primary_key($table_name, $new_key)
    {
        require_code('database_helper');
        _helper_change_primary_key($this, $table_name, $new_key);
    }

   
    public function add_auto_key($table_name, $field_name = 'id')
    {
        require_code('database_helper');
        _helper_add_auto_key($this, $table_name, $field_name);
    }

   
    public function promote_text_field_to_comcode($table_name, $name, $key = 'id', $level = 2, $in_assembly = false)
    {
        require_code('database_helper');
        _helper_promote_text_field_to_comcode($this, $table_name, $name, $key, $level, $in_assembly);
    }

   
    public function delete_table_field($table_name, $name)
    {
        require_code('database_helper');
        _helper_delete_table_field($this, $table_name, $name);
    }

   
    public function refresh_field_definition($type)
    {
        require_code('database_helper');
        _helper_refresh_field_definition($this, $type);
    }

   
    public function table_is_locked($table)
    {
        if (in_array($table, array('stats', 'banner_clicks', 'member_tracking', 'usersonline_track', 'download_logging'))) {
            return false; // Actually, we have delayed insert for these so locking is not an issue
        }

        if (substr(get_db_type(), 0, 5) != 'mysql' || get_value('innodb') === '1') {
            return false;
        }

        static $cache = array();
        if (isset($cache[$table])) {
            return $cache[$table];
        }

        $tries = 0;
        do {
            if ((substr($table, 0, 2) == 'f_') && ($table != 'f_welcome_emails')) {
                $db_name = get_db_forums();
                $db = $GLOBALS['FORUM_DB'];
            } else {
                $db_name = get_db_site();
                $db = $GLOBALS['SITE_DB'];
            }
            $locks = $db->query('SHOW OPEN TABLES FROM ' . $db_name . ' WHERE `Table`=\'' . db_escape_string($db->get_table_prefix() . $table) . '\' AND In_use>=1', null, null, true);
            if (is_null($locks)) {
                return false; // MySQL version older than 5.0 (e.g. 4.1.x)
            }
            $locked = count($locks) >= 1;
            $tries++;
            if ($locked) {
                if (php_function_allowed('usleep')) {
                    usleep(50000); // 50ms wait
                }
            }
        } while (($locked) && ($tries < 5));

        $cache[$table] = $locked;
        return $locked;
    }
}

 
Online now: No Back to the top

Post

Important!
Posted
Rating:
#6181
Avatar
Site director
admin is in the usergroup ‘Administrators’

Automated fix message

Terry said

Some sort of error. It's not a big issue, but it would be good to hear any ideas about what this could be caused from, if anyone has any ideas.

Search content - Witches Chat

and

Search content - Witches Chat

Yields a Bailing Out error

I have it narrowed down a bit. It only happens when searching for the term "club" or "clubs" or if you search for anything, if the Clubs box is ticked to search the Clubs, it bails.

I'm also not clear on what defines a Club as compared to a Forum for a special Usergroup. When a Club is created, it creates a special Usergroup and a special Forum, is that correct?

 
This issue has now been filed on the tracker as issue #4010, with a fix.
Important!

Post

Posted
Rating:
#6182
Avatar
Site director
Chris Graham is in the usergroup ‘Administrators’
(We communicated over email about this)

Ok I fixed it on your site :).

It was actually nothing to do with database.php.

In addition to the main fix above, I also found another small issue and fixed it on your site:
0004011: Club search results ugly - Composr CMS feature tracker


Become a fan of Composr on Facebook or add me as a friend. Add me on on Twitter. Follow me on Minds (where I am most active). Support me on Patreon

Was I helpful?
  • If not, please let us know how we can do better (please try and propose any bigger ideas in such a way that they are fundable and scalable).
  • If so, please let others know about Composr whenever you see the opportunity or support me on Patreon.
  • If my reply is too Vulcan or expressed too much in business-strategy terms, and not particularly personal, I apologise. As a company & project maintainer, time is very limited to me, so usually when I write a reply I try and make it generic advice to all readers. I'm also naturally a joined-up thinker, so I always express my thoughts in combined business and technical terms. I recognise not everyone likes that, don't let my Vulcan-thinking stop you enjoying Composr on fun personal projects.
  • If my response can inspire a community tutorial, that's a great way of giving back to the project as a user.
Online now: No Back to the top

Post

Posted
Rating:
#6220
Avatar
Standard member
Terry is in the usergroup ‘Fan in action’
Thank you, man :)

You're a unique human being to care as much as you do about people's stuff.

The recent update went fine, too.
Online now: No Back to the top
1 guest and 0 members have just viewed this.
Back to Top