$sql_extra=" AND pgrp.gname LIKE ".protect_sprintf("'%".dbesc($search)."%'")."";
// sql_extra2 is typically used when we don't have a local_channel - so we are not search abook_alias
$sql_extra2=" AND ( xchan_name LIKE ".protect_sprintf("'%".dbesc($search)."%'")." OR xchan_addr LIKE ".protect_sprintf("'%".dbesc(punify($search)).((strpos($search,'@')===false)?"%@%'":"%'")).") ";
// This horrible mess is needed because position also returns 0 if nothing is found.
// Would be MUCH easier if it instead returned a very large value
// Otherwise we could just
// order by LEAST(POSITION($search IN xchan_name),POSITION($search IN xchan_addr)).
$order_extra2="CASE WHEN xchan_name LIKE "
.protect_sprintf("'%".dbesc($search)."%'")
." then POSITION('".protect_sprintf(dbesc($search))
."' IN xchan_name) else position('".protect_sprintf(dbesc(punify($search)))."' IN xchan_addr) end, ";
$sql_extra3="AND ( xchan_addr like ".protect_sprintf("'%".dbesc(punify($search))."%'")." OR xchan_name like ".protect_sprintf("'%".dbesc($search)."%'")." OR abook_alias like ".protect_sprintf("'%".dbesc($search)."%'")." ) ";
$sql_extra4="AND ( xchan_name LIKE ".protect_sprintf("'%".dbesc($search)."%'")." OR xchan_addr LIKE ".protect_sprintf("'%".dbesc(punify($search)).((strpos($search,'@')===false)?"%@%'":"%'"))." OR abook_alias LIKE ".protect_sprintf("'%".dbesc($search)."%'").") ";
// Getting info from the abook is better for local users because it contains info about permissions
if(local_channel()){
// add connections
$r=q(
"SELECT abook_id as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, xchan_type, abook_flags, abook_self
"SELECT xchan_hash as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, 0 as abook_flags, 0 as abook_self
$r2=q("SELECT xchan_hash as id, xchan_hash as hash, xchan_name as name, xchan_photo_s as micro, xchan_url as url, xchan_addr as nick, 0 as abook_flags, 0 as abook_self
"SELECT xchan_hash as hash, xchan_name as name, xchan_addr as nick, xchan_photo_s as micro, xchan_url as url
FROMabookleftjoinxchanonabook_xchan=xchan_hash
WHEREabook_channel=%d
andxchan_deleted=0
$sql_extra3
ORDERBYxchan_nameASC",
intval(local_channel())
);
if($z){
foreach($zas$zz){
if(in_array($zz['hash'],$permitted)){
$r[]=$zz;
}
}
}
}elseif($type=='a'){
$r=q(
"SELECT abook_id as id, xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM abook left join xchan on abook_xchan = xchan_hash
WHEREabook_channel=%d
andxchan_deleted=0
$sql_extra3
ORDERBYxchan_nameASC",
intval(local_channel())
);
}elseif($type=='z'){
$r=q(
"SELECT xchan_name as name, xchan_hash as hash, xchan_addr as nick, xchan_photo_s as micro, xchan_network as network, xchan_url as url, xchan_addr as attag FROM xchan left join abook on xchan_hash = abook_xchan