-
acalc_grams
()
--calculate the unigrams and bigrams (time consuming)
--for each tag group e.g. the environment, environment, Environment
--from the serialised article data
--bigrams have a 0 window size (no words allowed in between)
--for a given tag group id
declare
iTagGroupId alias for $1;
rcd record;
iBigramId integer;
begin
delete from ttaggroup_bigram where taggroupid = iTagGroupId;
delete from ttaggroup_unigram where taggroupid = iTagGroupId;
delete from ttaggroup_taggroup where taggroupid = iTagGroupId;
--unigrams
insert into ttaggroup_unigram(taggroupid, wordid, count)
select iTagGroupId, tw.wordid, count(*)
from ttag tt
inner join tarticle_tag tat on tt.tagid = tat.tagid and tt.taggroupid = iTagGroupId
inner join tarticle ta on ta.articleid = tat.articleid and not ta.externalsourceid = 5 --not schnews
inner join tarticle_word taw on ta.articleid = taw.articleid
inner join tword tw on taw.wordid = tw.wordid and tw.stopword = false
group by tw.wordid
having count(*) > 1
order by count(*) desc
limit 100;
--bigrams
for rcd in select taw1.wordid as word1, taw2.wordid as word2, count(*)
from tarticle ta
inner join tarticle_tag tat on ta.articleid = tat.articleid and not ta.externalsourceid = 5 --not schnews
inner join ttag tct on tct.tagid = tat.tagid and tct.taggroupid = iTagGroupId
inner join tarticle_word taw1 on ta.articleid = taw1.articleid
inner join tword tw1 on taw1.wordid = tw1.wordid and tw1.stopword = false
inner join tarticle_word taw2 on ta.articleid = taw2.articleid and taw2.position = taw1.position + 1
inner join tword tw2 on taw2.wordid = tw2.wordid and tw2.stopword = false
group by taw1.wordid, taw2.wordid
having count(*) > 1
order by count(*) desc
limit 100
loop
--add the bigram if it is not already there
--and reference it
select into iBigramId bigramid from tbigram where word1 = rcd.word1 and word2 = rcd.word2;
if not found then
insert into tbigram(word1, word2) values(rcd.word1, rcd.word2);
iBigramId := currval('seqbigramid');
end if;
insert into ttaggroup_bigram(taggroupid, bigramid, count) values(iTagGroupId, iBigramId, rcd.count);
end loop;
--associated tag groups
--tag groups that appear in the same articles as this group
insert into ttaggroup_taggroup(taggroupid, associatedtaggroupid, count)
select iTagGroupId, tti.taggroupid, count(*)
from ttag ttf
inner join tarticle_tag tatf on ttf.tagid = tatf.tagid and ttf.taggroupid = iTagGroupId
inner join tarticle ta on tatf.articleid = ta.articleid and not ta.externalsourceid = 5 --not schnews
inner join tarticle_tag tati on ta.articleid = tati.articleid
inner join ttag tti on tati.tagid = tti.tagid
group by tti.taggroupid
having count(*) > 1
order by count(*) desc
limit 100;
return 0;
end;
-
acounts
()
declare
sql text;
rcd record;
yc ytdetails%ROWTYPE;
begin
select into sql aggConCat('select ''' || relname || ''' as name, count(*), max(' || pa.attname || '), min(' || pa.attname || ') from ' || relname || ' union all ')
from pg_class pc
inner join pg_attribute pa on pc.oid = pa.attrelid and pa.attnum = 1 and pa.atttypid = 23
where relnamespace = 2200 and relkind = 'r'
and not substring(pa.attname from 1 for 1) = '.';
sql := substring(sql from 0 for char_length(sql) - 10);
for rcd in execute sql loop
yc.name := rcd.name;
yc.count := rcd.count;
yc.max := rcd.max;
yc.min := rcd.min;
return next yc;
end loop;
return;
end;
-
adecodeentities
()
--3 level & just in case there are  
--conversion of > and < have been removed because of the conflict with HTML
select
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace( replace(replace(
$1, '&', '&'),
'&', '&'),
'&', '&'),
' ', ' '),
'Э', ' '), --?
'n', 'n'),
'u', 'u'),
'‚', '‚'),
'…', '…'),
'Š', 'Š'),
'Ž', 'Ž'),
'‘', '‘'),
'’', '’'),
'“', '“'),
'”', '”'),
'–', '–'),
'—', '—'),
'™', '™'),
'£', '£'),
'¥', '¥'),
'­', ''),
'°', '°'),
'´', '´'),
'Ø', 'Ø'),
'á', 'á'),
'è', 'è'),
'é', 'é'),
'ë', 'ë'),
'ï', 'ï'),
'ñ', 'ñ'),
'彭', ' '), --?
'č', 'c'),
'ő', 'o'),
'"', '"'),
'ŵ', 'w'),
''', ''''),
'-', '-'),
'&#60;', '<'),
'&#61472;', ' '), --?
'&#64;', '@'),
'&#65533;', ' '), --?
'&#710;', 'ˆ'),
'&#8209;', '-'),
'&#8211;', '–'),
'&#8212;', '—'),
'&#8216;', '‘'),
'&#8217;', '’'),
'&#8220;', '“'),
'&#8221;', '”'),
'&#8226;', '•'),
'&#8230;', '…'),
'&#8232;', ' '), --?
'&#8356;', '£'),
'&#8364;', '€'),
'&#8482;', '™'),
'&#9;', ' '),
'&A;', ' '), --??
'&aacute;', 'á'),
'&Aacute;', 'Á'),
'&acirc;', 'â'),
'&acute;', '´'),
'&agrave;', 'à'),
'&apos;', ''''),
'&aring;', 'å'),
'&atilde;', 'ã'),
'&auml;', 'ä'),
'&beta;', 'ß'),
'&bull;', '•'),
'&ccedil;', 'ç'),
'&copy;', '©'),
'&D;', ' '), --??
'&deg;', '°'),
'&Eacute;', 'É'),
'&eacute;', 'é'),
'&ecirc;', 'ê'),
'&egrave;', 'è'),
'&euml;', 'ë'),
'&euro;', '€'),
'&frac12;', '½'),
'&G;', ' '), --??
--'&gt;', '>'),
'&hellip;', '…'),
'&iacute;', 'í'),
'&icirc;', 'î'),
'&iuml;', 'ï'),
'&L;', ' '), --??
'&lsquo;', '‘'),
--'&lt;', '<'),
'&mdash;', '—'),
'&micro;', 'µ'),
'&middot;', '·'),
'&ndash;', '–'),
'&ntilde;', 'ñ'),
'&oacute;', 'ó'),
'&Oacute;', 'Ó'),
'&ocirc;', 'ô'),
'&ordm;', 'º'),
'&oslash;', 'ø'),
'&Oslash;', 'Ø'),
'&Otilde;', 'Õ'),
'&ouml;', 'ö'),
'&Ouml;', 'Ö'),
'&plusmn;', '±'),
'&pound;', '£'),
'&reg;', '®'),
'&rsquo;', '’'),
'&sect;', '§'),
'&shy;', ''),
'&shyp;', ' '), --??
'&sup2;', '²'),
'&T;', ' '), --??
'&trade;', '™'),
'&uacute;', 'ú'),
'&ucirc;', 'û'),
'&ugrave;', 'ù'),
'&uuml;', 'ü'),
'&Uuml;', 'Ü'),
'&#x60;', '`'),
'&#x63;', 'c'),
'&#x6E;', 'n'),
'&#x91;', '‘'),
'&#x92;', '’'),
'&#x96;', '–'),
'&#xa3;', '£'),
'&#xa7;', '§'),
'&#xab;', '«'),
'&#xac;', '¬'),
'&#xad;', ''),
'&#xb4;', '´'),
'&#xe1;', 'á'),
'&#xe2;', 'â'),
'&#xe4;', 'ä'),
'&#xe7;', 'ç'),
'&#xe9;', 'é'),
'&#xed;', 'í'),
'&#xef;', 'ï'),
'&#xf4;', 'ô'),
'&#xf6;', 'ö'),
'&#xfc;', 'ü')
-
adelete_feederentries
()
--entities (cascade delete clears up references)
delete from tentity where feederid = $1;
--articles (cascade delete clears up references)
delete from tarticle where feederid = $1;
--clean up tags (only referenced from articles and tagfilters)
delete from ttag where not exists (
select * from tarticle_tag where tagid = ttag.tagid --will be empty now because of previous article clear up
)
and not exists (
select * from txtagfilter where tagid = ttag.tagid
);
--clean up qualifiersets (valid QSs are either entities, auto-tagfilters or tags)
--auto-tagfilters use tags now so we only have to check entities and tags
delete from tqualifierset
where not exists (
select * from tentity_qualifierset where qualifiersetid = tqualifierset.qualifiersetid
)
and not exists (
select * from ttag where tagqualifiersetid = tqualifierset.qualifiersetid
);
select 0;
-
aggConCat_StateChange
()
declare
begin
return ($1 || $2);
end;
-
aggconcat
()
aggregate_dummy
-
anyof
()
declare
sKey alias for $1;
sKeys alias for $2;
iKey integer;
iKeys integer;
bMatch boolean;
begin
if version_major() >= 7.4 then
bMatch := (sKey = any (sKeys));
else
bMatch := false;
iKeys := array_upper($2, 1);
if not iKeys is null then
for iKey in 1..iKeys loop
if sKey = sKeys[iKey] then
bMatch := true;
exit;
end if;
end loop;
end if;
end if;
return bMatch;
end;
-
aresetsequences
()
declare
sql text;
begin
select into sql aggConCat('select setval(''' || substring(adsrc from 10 for char_length(adsrc) - 17) || ''', (select coalesce(max(' || pa.attname || '), 1) + 1 from ' || pc.relname || ')) union all ')
from pg_attrdef ad
inner join pg_class pc on ad.adrelid = pc.oid
inner join pg_attribute pa on ad.adrelid = pa.attrelid and ad.adnum = pa.attnum
where substring(adsrc from 1 for 7) = 'nextval';
sql := substring(sql from 0 for char_length(sql) - 10);
execute sql;
return 0;
end;
-
array_append
()
declare
aTexts alias for $1;
aNewTexts alias for $2;
iLenNew integer;
iLenOld integer;
sNewArray text := '{';
sElement text;
begin
iLenOld := array_upper(aTexts, 1);
iLenNew := array_upper(aNewTexts, 1);
if not iLenOld is null then
for i in 1..iLenOld loop
sElement := aTexts[i];
if not sElement is Null then
sNewArray := sNewArray || sElement;
if not i = iLenOld then sNewArray := sNewArray || ','; end if;
end if;
end loop;
end if;
if not iLenOld is null and not iLenNew is null then sNewArray := sNewArray || ','; end if;
if not iLenNew is null then
for i in 1..iLenNew loop
sElement := aNewTexts[i];
if not sElement is Null then
sNewArray := sNewArray || sElement;
if not i = iLenNew then sNewArray := sNewArray || ','; end if;
end if;
end loop;
end if;
sNewArray := sNewArray || '}';
return sNewArray;
end;
-
array_append
()
declare
aTexts alias for $1;
aNewTexts alias for $2;
iLen integer;
sNewArray text:='{';
sElement text;
begin
iLen := array_upper(aTexts, 1);
if not iLen is null then
for i in 1..iLen loop
sElement := aTexts[i];
if not sElement is Null then
sNewArray := sNewArray || sElement;
if not i = iLen then sNewArray := sNewArray || ',';
end if;
end loop;
end if;
iLen := array_upper(aNewTexts, 1);
if not iLen is null then
for i in 1..iLen loop
sElement := aNewTexts[i];
if not sElement is Null then
sNewArray := sNewArray || sElement;
if not i = iLen then sNewArray := sNewArray || ',';
end if;
end loop;
end if;
sNewArray := sNewArray || '}';
return sNewArray;
end;
-
array_fromtext
()
begin
return array_fromtext($1, 2); --default to {a,b,c} mode
end;
-
array_fromtext
()
declare
sText alias for $1;
iMode alias for $2;
aTexts text;
begin
if iMode = 1 then
--from spaces (escape the special array characters first)
aTexts := regexp_replace(sText, '[^\\]([,}{])', '\\\\1');
aTexts := unormalise_whitespace(aTexts);
aTexts := regexp_replace(aTexts, ' ', ',');
aTexts := '{' || aTexts || '}';
elsif iMode = 2 then
--1 dimensional from array string {'b','a', ...}
aTexts := sText;
elsif iMode = 3 then
--pulls out words only. Ignores grammar and numbers
--except the full-top: everything needs to pay attention to a sentence end
--e.g. Me in Rio. Tinto the dog played ball != Rio Tinto
--from spaces
--aTexts := regexp_replace(sText, '''', '');
--aTexts := regexp_replace(sText, '-', ' ');
aTexts := regexp_replace(sText, '[^A-Za-z0-9 .'']', ' ');
aTexts := regexp_replace(aTexts, '\\.', ' . '); --make sure that full-stops get separated out
aTexts := unormalise_whitespace(aTexts);
aTexts := regexp_replace(aTexts, ' ', ',');
aTexts := '{' || aTexts || '}';
end if;
return aTexts;
end;
-
array_totext
()
declare
begin
return array_totext($1, 2); --default to {a,b,c} mode
end;
-
array_totext
()
declare
aTexts alias for $1;
iMode alias for $2;
sText text:='';
iLength int4;
begin
if iMode=1 then
--with spaces
for i in 1..array_upper(aTexts, 1) loop
sText:=sText || aTexts[i] || ' ';
end loop;
iLength:=char_length(sText);
if iLength!=0 then
sText:=substring(sText from 1 for iLength-1);
end if;
elsif iMode=2 then
--array string mode
sText := '{';
for i in 1..array_upper(aTexts, 1) loop
sText := sText || replace(replace(aTexts[i], '\'', '\\\''), ',', '\,') || ',';
end loop;
iLength := char_length(sText);
if iLength != 0 then
sText := substring(sText from 1 for iLength-1);
end if;
sText := sText || '}';
end if;
return sText;
end;
-
lower
()
select array_fromtext(lower(array_totext($1)))
-
opCompIntegerText
()
declare
begin
return $1::text = $2;
end;
-
opConcat
()
declare
begin
return $1 || case $2 when true then 'true' else 'false' end;
end;
-
opConcat
()
declare
begin
return $1 || array_totext($2, 2);
end;
-
padd_alias
()
declare
iFeederId alias for $1;
sAlias alias for $2;
iEntityID alias for $3;
sNormalised text;
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
begin
sNormalised := unormalise_entityname(sAlias);
--check that this entity doesn't already have this alias
if not exists(select * from tentity_qualifierset where entityid = iEntityID
and qualifiersetid in(
select uexists_qualifierset from uexists_qualifierset(sNormalised)
))
then
--alias gets its own (non-unique) qualifierset
select into iQualifierSetId uadd_qualifierset(iFeederId, sAlias);
insert into tentity_qualifierset(entityid, qualifiersetid) values(iEntityId, iQualifierSetId);
end if;
return iQualifierSetId;
end;
-
padd_article
(
23, 23, 25, 25, 25, 25, 1007
)
declare
iFeederID alias for $1;
iExternalSourceID alias for $2;
sURL alias for $3;
sTitle alias for $4;
sBody alias for $5;
sOrigonal alias for $6;
iEntityIDs alias for $7;
iArticleID tarticle.articleid%TYPE;
iEntityID tentity.entityid%TYPE;
iVersion tarticle.version%TYPE;
sMD5 tarticle.md5%TYPE;
iLen integer;
sNewBody text;
sNewTitle text;
begin
--articleid PK
--md5 for a given source is unique (2 sources can report the same thing)
--not that url is the relative href. Combine it with the externalsourceid for a unique universal locator
sMD5 := md5(sBody);
--check uniqueness
select into iArticleID articleid from tarticle
where externalsourceid = iExternalSourceID
and md5 = sMD5;
if not found then --this source has not reported this article yet
--look for the url to see if this is a new version
select into iVersion max(version)+1 from tarticle
where externalsourceid = iExternalSourceID
and url = sURL;
if iVersion is null then iVersion := 1; end if; --not found, so create the first version
--extra check that HTML entities are decoded from the feeder
sNewBody := regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(
sBody, '&amp;', '&'),
'&#039;', ''''),
'&nbsp;', ' '),
'&eacute;', 'é'),
'&quot;', '"'),
'&raquo;|&laquo;|&ldquo;|&rdquo;', '"'
);
sNewTitle := regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(
sTitle, '&amp;', '&'),
'&#039;', ''''),
'&nbsp;', ' '),
'&eacute;', 'é'),
'&quot;', '"'),
'&raquo;|&laquo;|&ldquo;|&rdquo;', '"'
);
insert into tarticle(feederid, version, externalsourceid, url, title, body, origonal, md5)
values(iFeederID, iVersion, iExternalSourceID, sURL, sNewTitle, sNewBody, sOrigonal, sMD5);
select into iArticleID currval('seqarticleid'::text);
--entity relationships
iLen := array_upper(iEntityIDs, 1);
for i in 1..iLen loop
iEntityID := iEntityIDs[i];
if not iEntityID is Null then
if not exists(select * from tentity_article where entityid = iEntityID and articleid = iArticleID) then
insert into tentity_article(entityid, articleid) values(iEntityID, iArticleID);
end if;
end if;
end loop;
--auto-tags (this is a new page so there are no tags as yet)
insert into tarticle_tag(feederid, articleid, tagid)
select distinct iFeederID, iArticleID, tagid
from txtagfilter
where sNewBody ~ filter
and (exceptions = '' or sNewBody !~ exceptions)
and enable;
select into iLen userialise_article(iFeederID, iArticleID);
end if;
return iArticleID;
end;
-
padd_article
(
23, 23, 25, 25, 25, 25, 1007, 25, 1009
)
declare
iFeederID alias for $1;
sDescription alias for $8;
sTags alias for $9;
iArticleID tarticle.articleid%TYPE;
iSummaryId tsummary.summaryid%TYPE;
sNewDescription text;
begin
--this will return the existing article id if it is already in there (by md5)
--thus new/updated description will get added/updated even if the article already exists
select into iArticleID padd_article($1, $2, $3, $4, $5, $6, $7);
--extra check that HTML entities are decoded from the feeder
sNewDescription := regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(
sDescription, '&amp;', '&'),
'&#039;', ''''),
'&nbsp;', ' '),
'&eacute;', 'é'),
'&quot;', '"'),
'&raquo;|&laquo;|&ldquo;|&rdquo;', '"'
);
--description
if not sNewDescription is null then
select into iSummaryId padd_summary(iFeederId, iArticleID, '', sNewDescription);
end if;
--tags, uadd_tag() will ensure uniqueness
if not sTags is null then
perform uadd_tags(iFeederId, iArticleID, sTags, 'K'); --keywords from the document
end if;
return iArticleID;
end;
-
padd_company
()
select padd_company($1, $2, true)
-
padd_company
()
declare
iFeederId alias for $1;
sName alias for $2;
bAddAutoAliases alias for $3;
sNormalised text;
iEntityId tentity.entityid%TYPE;
cModeration char(1);
rcd record;
begin
--do not add the company if an exact match exists
sNormalised := unormalise_companyname(sName);
if not exists (select * from uexists_company_nameoralias(sNormalised)) then
--however, if there are doubts then add the company as requireing moderation
--A = awaiting moderation
--M = moderated
cModeration := 'M';
if exists (select * from uexists_company_uniquematches(sNormalised)) then cModeration = 'A';
elsif exists (select * from uexists_company_fromaliases(sNormalised)) then cModeration = 'A';
end if;
select into iEntityId uadd_entity(iFeederId, 1, sNormalised, cModeration);
insert into tlcompany(entityid) values(iEntityId);
if bAddAutoAliases then
--add all unique name and acronym aliases
for rcd in select uautocompanyaliases as alias from uautocompanyaliases(sNormalised) loop
--do not add the alias if it already exists for another company (first come first served)
if not exists (select * from tlcompany tc inner join tentity_qualifierset eq on tc.entityid = eq.entityid
where qualifiersetid in(select uexists_qualifierset from uexists_qualifierset(rcd.alias))) then
perform padd_alias(iFeederId, rcd.alias, iEntityId);
end if;
end loop;
end if;
end if;
return iEntityId;
end;
-
padd_country
()
declare
iFeederId alias for $1;
sName alias for $2;
iEntityId tentity.entityid%TYPE;
begin
if not exists (select * from uexists_country(sName)) then
iEntityId := uadd_entity(iFeederId, 1, sName, 'M');
insert into tlcountry(entityid) values(iEntityId);
end if;
return iEntityId;
end;
-
padd_externalsource
()
declare
iFeederId alias for $1;
sDomain alias for $2;
sNormalised text;
iExternalsourceId integer;
begin
--only add it if it doesnt alreay exist
sNormalised := unormalise_externalsource(sDomain);
if not exists (select * from uexists_externalsource(sNormalised)) then
insert into texternalsource(domain, enabled) values(sNormalised, false);
iExternalsourceId := currval('seqexternalsourceid');
end if;
return iExternalsourceId;
end;
-
padd_person
()
declare
iFeederId alias for $1;
sName alias for $2;
sFullName alias for $3;
iEntityId tentity.entityid%TYPE;
begin
if not exists (select * from uexists_person(sName)) then
iEntityId := uadd_entity(iFeederId, 1, sName, 'M');
insert into tlperson(entityid) values(iEntityId);
if not sFullName = '' then perform padd_alias(iFeederId, sFullName, iEntityId); end if;
end if;
return iEntityId;
end;
-
padd_product
()
select padd_product($1, $2, $3, true)
-
padd_product
()
declare
iFeederId alias for $1;
sProductName alias for $2;
iMainCompanyId alias for $3;
cModeration alias for $4;
iEntityId tentity.entityid%TYPE;
iProductId tlproduct.productid%TYPE;
begin
if not exists(select * from uexists_product(sProductName, iMainCompanyId)) then
--create the entity (Moderated)
iEntityId := uadd_entity(iFeederId, 1, sProductName, cModeration);
--create the product with its main company relation
insert into tlproduct(entityid, maincompanyid) values(iEntityId, iMainCompanyId);
iProductId := currval('seqproductid');
--O is the main owning company relationship
insert into tcompany_product(companyid, productid, relationship) values(iMainCompanyId, iProductId, 'O');
end if;
return iEntityId;
end;
-
padd_product
()
declare
iFeederId alias for $1;
sProductName alias for $2;
sCompanyName alias for $3;
bAddAutoAliases alias for $4;
sNormalised text;
iEntityId tentity.entityid%TYPE;
iCount integer;
iCompanyId tlcompany.companyid%TYPE;
cModeration char(1);
rcd record;
begin
--product is added in Awaiting Moderation mode if we are not sure if the company is correct
--we can be sure that the company is correct if a uexists_company_*(...) returns only 1 match
--otherwise we add the company :)
sNormalised := unormalise_companyname(sCompanyName);
--check for exact singular (cause they are unique) match on company name
select into iEntityId, iCount min(uexists_company_nameoralias), count(*) from uexists_company_nameoralias(sNormalised);
if not iEntityId is null then
select into iCompanyId companyid from tlcompany where entityid = iEntityId;
iEntityId := padd_product(iFeederId, sProductName, iCompanyId, case iCount when 1 then 'M' else 'A' end);
else
--no exact singular match, check for unique part match
select into iEntityId, iCount min(uexists_company_uniquematches), count(*) from uexists_company_uniquematches(sNormalised);
if not iEntityId is null then
select into iCompanyId companyid from tlcompany where entityid = iEntityId;
iEntityId := padd_product(iFeederId, sProductName, iCompanyId, case iCount when 1 then 'M' else 'A' end);
else
--no exact singular match or unique part, check aliases
select into iEntityId, iCount min(uexists_company_fromaliases), count(*) from uexists_company_fromaliases(sNormalised);
if not iEntityId is null then
select into iCompanyId companyid from tlcompany where entityid = iEntityId;
iEntityId := padd_product(iFeederId, sProductName, iCompanyId, case iCount when 1 then 'M' else 'A' end);
else
--no matches on anything, add a new company!
iEntityId := uadd_entity(iFeederId, 1, sNormalised, 'M');
insert into tlcompany(entityid) values(iEntityId);
iCompanyId := currval('seqcompanyid');
if bAddAutoAliases then
for rcd in select uautocompanyaliases as alias from uautocompanyaliases(sNormalised) loop
perform padd_alias(iFeederId, rcd.alias, iEntityId);
end loop;
end if;
iEntityId := padd_product(iFeederId, sProductName, iCompanyId, 'M');
end if;
end if;
end if;
return iEntityId; --(product entity id)
end;
-
padd_producttype
()
declare
iFeederId alias for $1;
sProductTypeName alias for $2;
iEntityId tentity.entityid%TYPE;
iProductTypeId tlproducttype.producttypeid%TYPE;
begin
iEntityId := uadd_entity(iFeederId, 1, sProductTypeName);
insert into tlproducttype(entityid) values(iEntityId);
iProductTypeId := currval('seqproducttypeid');
return iEntityId; --(product entity id)
end;
-
padd_summary
()
declare
iFeederId alias for $1;
iArticleId alias for $2;
sTitle alias for $3;
sBody alias for $4;
iSummaryId tsummary.summaryid%TYPE;
sMD5 text;
begin
sMD5 := md5(sBody);
select into iSummaryId summaryid from tsummary where articleid = iArticleId and md5 = sMD5;
if not found then
insert into tsummary(articleid, title, body, feederid, md5)
values(iArticleId, sTitle, sBody, iFeederId, md5(sBody));
select into iSummaryId currval('seqsummaryid');
end if;
return iSummaryId;
end;
-
padd_user
(
25, 25, 25, 25, 25, 25, 1042, 25, 25, 23, 23, 23, 16, 16, 25, 23, 25, 1000, 25, 1000, 25, 25, 25, 25
)
insert into tuser(
firstname,
middlename,
lastname,
username,
encryptedpassword,
emailaddress,
gender,
profession,
affiliations,
ethnic_group,
income_group,
age_group,
subscribe_events,
subscribe_news,
why_do_you_ethically_consume,
purchase_research,
purchase_research_other,
about_you_not_stated,
about_you_fairtrade,
about_you_freerange,
about_you_organic,
about_you_local_produce,
about_you_vegetairian_vegan,
about_you_cyclist,
about_you_dont_use_airplanes,
about_you_other,
buy_online_not_stated,
buy_online_flights,
buy_online_groceries,
buy_online_financial_products,
buy_online_insurance,
buy_online_holiday_accomodation,
buy_online_clothes,
buy_online_electronics,
buy_online_media,
buy_online_other,
what_tools,
what_ideas,
what_skills
)
values($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18[1], $18[2], $18[3], $18[4], $18[5], $18[6], $18[7], $18[8], $19, $20[1], $20[2], $20[3], $20[4], $20[5], $20[6], $20[7], $20[8], $20[9], $21, $22, $23, $24);
select currval('sequserid')::integer;
-
padd_word
()
select padd_word($1, $2, null::text[], null::integer[], null::integer[], false)
-
padd_word
()
select padd_word($1, $2, array_fromtext('{' || $3 || '}'), null::integer[], null::integer[], false)
-
padd_word
(
23, 25, 1009, 1007, 1007, 16
)
declare
iFeederId alias for $1;
sWord alias for $2;
aDefinitions alias for $3;
aSenses alias for $4;
aCommonalities alias for $5;
bStopword alias for $6;
iLenDefs integer;
iLenComs integer;
iLenSenses integer;
iSense integer;
sDefinition text;
iCommonality integer;
sLower text;
iWordId tword.wordid%TYPE;
begin
--duplicate words will cause a unique key failure
--all words are lower case (enforced by a check constraint)
sLower := lower(sWord);
iWordId := uexists_word(sLower);
if iWordId is null then
insert into tword(feederid, word, stopword) values(iFeederId, sLower, bStopword);
iWordId := currval('seqwordid');
--add definitions
iLenDefs := array_upper(aDefinitions, 1);
iLenComs := array_upper(aCommonalities, 1);
iLenSenses := array_upper(aSenses, 1);
if not iLenDefs is null then
for i in 1..iLenDefs loop
sDefinition := aDefinitions[i];
if not sDefinition is null then
if i <= iLenComs then iCommonality := aCommonalities[i]; else iCommonality := 0; end if; --commonality 0 indicates not set
if i <= iLenSenses then iSense := aSenses[i]; else iSense := 0; end if; --senseid 0 indicates unknown (primary key)
insert into twordnet(wordid, senseid, definition, commonality, feederid)
values(iWordId, iSense, sDefinition, iCommonality, iFeederId);
end if;
end loop;
end if;
end if;
return iWordId;
end;
-
pexternalsources
()
select externalsourceid, "domain", startpage, area, rootpagetitle, externalsourcetypeid
from texternalsource
where enabled = true
-
pmd5s
()
select md5 from tarticle
-
ppp_bikesonatrain_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_bikesonatrain_docontactus
()
select ppp_easyethical_docontactus($1, $2, $3, $4, $5, $6)
-
ppp_bikesonatrain_dojoinemaillist
()
select ppp_easyethical_dojoinemaillist($1, $2, $3, $4, $5);
-
ppp_carrotmobuk_account_index
(
25, 25, 23, 23, 23, 25, 16, 16, 16, 16, 25, 25, 25, 25
)
select ppp_easyethical_account_index($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
-
ppp_carrotmobuk_account_login
()
select ppp_easyethical_account_login($1, $2, $3, $4, $5, $6)
-
ppp_carrotmobuk_account_logout
()
select ppp_easyethical_account_logout($1, $2, $3)
-
ppp_carrotmobuk_account_register
(
25, 25, 23, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(location analysis is always put first by the system although it appears elsewhere in the form)
iGoogleStatus alias for $4;
iPointCount alias for $5;
sFirstPoint alias for $6;
--form parameters in order
sEmailAddress alias for $7; --cannot be the screen name
sUserName alias for $8; --often the screen name, so cannot be the email address
iUsernameGenerator alias for $9; --0 - use the username, 1 means use the sUsername as a stem for an auto-username (user should be informed via email of this username), 2 - use email 1st part with auto-generator
sPassword alias for $10;
iPasswordGenerator alias for $11; --0 - use the password, 1 generate password
sArea alias for $12; --input to fuel the location analysis
sLocationDetails alias for $13; --often filled out on second validation if there are options
sSubmit alias for $14; --standard submit button to indicate whether form data has been sent or not
sXML text;
iUserId tuser.userid%TYPE;
iLatestUserId tuser.userid%TYPE;
sFirstname text;
sMiddlename text;
sLastName text;
begin
sFirstname := 'anonymous';
sMiddlename := '';
sLastName := '';
iLatestUserId := nextval('sequserid');
--attempt registration
sXML := ppp_easyethical_account_register(sSession, sSchema, iVersion, true, '', iGoogleStatus, iPointCount, sFirstPoint,
sFirstname, sMiddlename, sLastName,
sEmailAddress, sUserName, iUsernameGenerator, sPassword, iPasswordGenerator,
sArea, sLocationDetails, '', '', sSubmit);
--auto login
iUserId := currval('sequserid');
if not iLatestUserId = iUserId then
perform usession_login(sSession, sUserName, sPassword);
update tuser set system = 'CM' where userid = iUserId;
end if;
return sXML;
end;
-
ppp_carrotmobuk_account_verify
()
select ppp_easyethical_account_verify($1, $2, $3, $4)
-
ppp_carrotmobuk_cms_addedit
(
25, 25, 23, 25, 25, 25, 25, 25
)
select ppp_easyethical_cms_addedit($1, $2, $3, $4, $5, $6, $7, $8);
-
ppp_carrotmobuk_cms_managepages
(
25, 25, 23, 25, 25, 25, 25, 25
)
select ppp_easyethical_cms_managepages($1, $2, $3, $4, $5, $6, $7, $8)
-
ppp_carrotmobuk_cms_templates_basic
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select uxml_cms_url($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
-
ppp_carrotmobuk_docontactus
()
select ppp_easyethical_docontactus($1, $2, $3, $4, $5, $6)
-
ppp_carrotmobuk_documentation_all
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sPageName alias for $4;
sPageNameFull text[];
sXML text;
rcd record;
begin
sPageNameFull := '{carrotmobuk_howto_' || sPageName || '}';
sXML := '<root>' || uxml_cms_values(sSessionId, sSchema, iVersion, sPageNameFull) || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_documentation_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
begin
sXML := '<root>' || uxml_cms_values(sSessionId, sSchema, iVersion, '{carrotmobuk_help}') || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_dojoinemaillist
()
select ppp_easyethical_dojoinemaillist($1, $2, $3, $4, $5);
-
ppp_carrotmobuk_index
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
iUserId tuser.userid%TYPE;
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
rcd record;
begin
--distance calcs if logged in
select into iUserId, iLongitude, iLatitude u.userid, u.longitude, u.latitude
from tsession s
inner join tuser u on s.userid = u.userid
where s.sessionstring = sSession;
sXML := '<root>';
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[carrot mobings</rss:title>
<rss:description><![CDATA[upcoming mobings</rss:description>
<rss:relativelinkroot><![CDATA[/mob/</rss:relativelinkroot>
</rss:details>
<rss:items>
<mobings>';
for rcd in select cm.carrotmobid, cm.name, cm.description, cm.image, cm.createdate, cm.mobdate, cm.userid,
cm.location, cm.longitude, cm.latitude,
count(cme.entityid)
from tcarrotmob cm
left outer join tcarrotmob_entity cme on cm.carrotmobid = cme.carrotmobid
--where cm.mobdate > now() - '1 day'::interval
group by cm.carrotmobid, cm.name, cm.description, cm.image, cm.createdate, cm.mobdate, cm.userid,
cm.location, cm.longitude, cm.latitude
order by cm.mobdate
limit 5
loop
sXML := sXML || '<carrotmob id="' || rcd.carrotmobid || '" entitycount="' || rcd.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</rss:title>
<rss:id><![CDATA[' || uxml_escapefor_cdata(rcd.carrotmobid) || '</rss:id>
' || uxml_user(rcd.userid) || '
<daysaway>' || rcd.mobdate::date - now()::date || '</daysaway>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate)) || '</createdate>
<rss:description>' || uxml_parsexml(rcd.description) || '</rss:description>
<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</rss:pubdate>
<mobdate><![CDATA[' || uxml_escapefor_cdata(coalesce(uformatdate(rcd.mobdate, 2), '')) || '</mobdate>
<location><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.location, '')) || '</location>
<point logitude="' || coalesce(rcd.longitude, 0) || '" latitude="' || coalesce(rcd.latitude, 0) || '"/>
<image><![CDATA[' || uxml_escapefor_cdata(rcd.image) || '</image>';
if not iUserId is null then
sXML := sXML || '<distance>' || coalesce(udistance(rcd.longitude, rcd.latitude, iLongitude, iLatitude)::text, '(no user location details)') || '</distance>';
end if;
sXML := sXML || '</carrotmob>';
end loop;
sXML := sXML || '</mobings></rss:items></rss:feed></root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_addedit
(
25, 25, 23, 23, 23, 25, 25, 16, 23, 23, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(location analysis is always put first by the system although it appears elsewhere in the form)
iGoogleStatus alias for $4;
iPointCount alias for $5;
sFirstPoint alias for $6;
sTitle alias for $7;
bPrivate alias for $8;
iBusinessType alias for $9;
iMobType alias for $10;
sMobDate alias for $11;
sOpenDate alias for $12;
sImage alias for $13;
sArea alias for $14; --area here because the location appears under it at the bottom of the simplt inputs
sLocationDetails alias for $15; --location validates area so appears after always
sDescription alias for $16;
sSubmit alias for $17;
bSubmission boolean;
bOk boolean;
sFinalLocationDetails text;
iUserId tuser.userid%TYPE;
iLongitude tcarrotmob.longitude%TYPE;
iLatitude tcarrotmob.latitude%TYPE;
sLocation tcarrotmob.location%TYPE;
dMobDate tcarrotmob.mobdate%TYPE;
dOpenDate tcarrotmob.opendate%TYPE;
sXML text;
sFormXML text;
sSuccessXML text;
begin
iUserId := usession_userid(sSession);
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sFormXML := '';
sSuccessXML := '';
sFormXML := '<form_requirements submission="' || bSubmission || '">';
--simple first jobs (some hidden)
sFormXML := sFormXML || '<title required=".+" maxlength="200" help="(max 200 characters)"><value><![CDATA[' || sTitle || '</value></title>';
sFormXML := sFormXML || '<private hide4now="1" type="checkbox"><value><![CDATA[' || bPrivate || '</value></private>';
sFormXML := sFormXML || '<businesstype hide4now="1"><value><![CDATA[' || iBusinessType || '</value></businesstype>';
sFormXML := sFormXML || '<mobtype hide4now="1"><value><![CDATA[' || iMobType || '</value></mobtype>';
--mobdate
sFormXML := sFormXML || '<mobdate caption="mob date (approx)" type="date" required=".+">
<value><![CDATA[' || sMobDate || '</value>';
if bSubmission then
if sMobDate = '' then
bOk := false;
sFormXML := sFormXML || '<validation_error><![CDATA[mobdate required</validation_error>';
else
dMobDate := uto_timestamp(sMobDate || ' GMT', 'DD/Mon/YYYY');
if dMobDate is null then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[invalid date</validation_error>'; end if;
end if;
end if;
sFormXML := sFormXML || '</mobdate>';
--open date
sFormXML := sFormXML || '<opendate type="date" hide4now="1" required=".+">
<value><![CDATA[' || sMobDate || '</value>';
if bSubmission then
dOpenDate := now();
if not sOpenDate = '' then
dOpenDate := uto_timestamp(sOpenDate || ' GMT', 'DD/Mon/YYYY');
if dOpenDate is null then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[invalid date</validation_error>'; end if;
end if;
end if;
sFormXML := sFormXML || '</opendate>';
sFormXML := sFormXML || '<image type="image" disable4now="1"><value><![CDATA[' || sImage || '</value></image>';
--geo (optional)
--user enters search location term in the area and then selects a location (2 part forced validation failure sequence)
sFormXML := sFormXML || '<area required=".+" default="London, Greater London" help="examples: N22 6QP, Brixton, London, City road, Hyde Park (all locations postpended with UK)">
<value><![CDATA[' || uxml_escapefor_cdata(sArea) || '</value>
</area>';
--if an area has been entered but a location is not selected then we have a validation issue
--if there is no area or location then the user has opted to not include it
sFormXML := sFormXML || '<location>
<value><![CDATA[' || uxml_escapefor_cdata(sLocationDetails) || '</value>';
if bSubmission then
sFinalLocationDetails := sLocationDetails;
if not sArea = '' and sLocationDetails = '' then --optional
if iPointCount = 0 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[location not found</validation_error>'; end if;
if iPointCount = 1 then sFinalLocationDetails := sFirstPoint; end if;
if iPointCount > 1 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[please select a location</validation_error>'; end if;
end if;
end if;
sFormXML := sFormXML || '</location>';
sFormXML := sFormXML || '<description required=".+" type="HTMLEditor"><value><![CDATA[' || sDescription || '</value></description>';
sFormXML := sFormXML || '</form_requirements>';
if bSubmission and bOk then
sSuccessXML := '<success>';
sFormXML := '';
--geo (optional)
if not sFinalLocationDetails is null and not sFinalLocationDetails = '' then
iLongitude := substring(sFinalLocationDetails from '[-.0-9]+');
iLatitude := substring(sFinalLocationDetails from '[-.0-9]+ *, *([-.0-9]+)');
sLocation := substring(sFinalLocationDetails from '[-.0-9]+ *, *[-.0-9]+ *, *0 (.*)');
end if;
--add new mob
insert into tcarrotmob(name, area, private, businesstype, mobtype, mobdate, opendate, image, description, userid, longitude, latitude, location)
values(sTitle, sLocation, bPrivate, iBusinessType, iMobType, dMobDate, dOpenDate, sImage, sDescription, iUserId, iLongitude, iLatitude, sLocation);
--send user to their own mob
insert into tcarrotmob_user(carrotmobid, userid)
values(currval('seqcarrotmobid'), iUserId);
--return success (username and email unique already checked in this transaction)
sSuccessXML := sSuccessXML || '</success>';
end if;
sXML := '<root>' || sSuccessXML || sFormXML || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_all
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCarrotMob alias for $4;
sXML text;
iUserId tuser.userid%TYPE;
sName text;
iCount integer;
iCarrotMobId integer;
rcd record;
begin
sXML := '<root>';
iUserId := usession_userid(sSession);
--figure out the name of the company(s), may be an id
if sCarrotMob ~ '^[0-9]+$' then
select into iCount, iCarrotMobId 1, tc.carrotmobid
from tcarrotmob tc
where tc.carrotmobid = sCarrotMob;
if iCount is null then iCount := 0; end if; --not a valid company id
else
select into iCount, iCarrotMobId distinct count(distinct uexists_carrotmob), min(tc.carrotmobid)
from uexists_carrotmob(sCarrotMob)
inner join tcarrotmob tc on tc.carrotmobid = uexists_carrotmob;
end if;
--if there is only one then directly return information for that one
if iCount = 0 then
--no results
sXML := sXML || '<notfound/>';
elsif iCount = 1 then
--search resolves to exactly one company so return its summary details
select into sName, sXML cm.name, sXML || '<carrotmob id="' || cm.carrotmobid || '">
<name><![CDATA[' || uxml_escapefor_cdata(cm.name) || '</name>
' || uxml_user(cm.userid) || '
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(cm.createdate)) || '</createdate>
<description>' || uxml_parsexml(cm.description) || '</description>
<mobdate><![CDATA[' || uxml_escapefor_cdata(coalesce(uformatdate(cm.mobdate, 2), '')) || '</mobdate>
<location><![CDATA[' || uxml_escapefor_cdata(coalesce(cm.location, '')) || '</location>
<point longitude="' || coalesce(cm.longitude, 0) || '" latitude="' || coalesce(cm.latitude, 0) || '" zoom="' || coalesce(cm.zoom, 0) || '"/>
<image><![CDATA[' || uxml_escapefor_cdata(cm.image) || '</image>'
from tcarrotmob cm
where cm.carrotmobid = iCarrotMobId;
--people
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[carrot mob of ' || uxml_escapefor_cdata(cm.name) || '</rss:title>
<rss:description><![CDATA[people involved in this carrot mobing</rss:description>
<rss:relativelinkroot><![CDATA[/account/</rss:relativelinkroot>
</rss:details>
<rss:items>
<people>'
from tcarrotmob cm
where cm.carrotmobid = iCarrotMobId;
for rcd in select u.userid, u.username, u.firstname, u.lastname, cu.shout, u.avatar
from tcarrotmob_user cu
inner join tuser u on cu.userid = u.userid
where cu.carrotmobid = iCarrotMobId
--order by u.username --temporarily disaled because exaggerating counts
loop
sXML := sXML || '<user id="' || rcd.userid || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.firstname || ' ' || rcd.lastname) || '</rss:title>
<rss:description><![CDATA[' || uxml_escapefor_cdata(rcd.shout) || '</rss:description>
<username><![CDATA[' || uxml_escapefor_cdata(rcd.username) || '</username>
<firstname><![CDATA[' || uxml_escapefor_cdata(rcd.firstname) || '</firstname>
<lastname><![CDATA[' || uxml_escapefor_cdata(rcd.lastname) || '</lastname>
<avatar><![CDATA[' || uxml_escapefor_cdata(rcd.avatar) || '</avatar>
</user>';
end loop;
sXML := sXML || '</people></rss:items></rss:feed>';
--entities
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[carrot mob of ' || uxml_escapefor_cdata(sName) || '</rss:title>
<rss:description><![CDATA[companies involved in this carrot mobing</rss:description>
<rss:relativelinkroot><![CDATA[/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<entities>';
for rcd in select e.entityid, qs.phrase, cme.perc_revenue, cme.agreement,
cme.image, cme.interview, cme.blog,
(select count(*) from tcarrotmob_vote where carrotmobid = cme.carrotmobid and entityid = cme.entityid) as votes,
not tv.userid is null as voted
from tcarrotmob_entity cme
inner join tentity e on cme.entityid = e.entityid and cme.carrotmobid = iCarrotMobId
inner join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
left outer join tcarrotmob_vote tv on cme.carrotmobid = tv.carrotmobid and cme.entityid = tv.entityid and tv.userid = iUserId
order by qs.phrase
loop
sXML := sXML || '<entity id="' || rcd.entityid || '" perc_revenue="' || rcd.perc_revenue || '" votes="' || rcd.votes || '" voted="' || rcd.voted || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</rss:title>
<rss:description><![CDATA[' || uxml_escapefor_cdata(rcd.agreement) || '</rss:description>
<perc_revenue><![CDATA[' || uxml_escapefor_cdata(rcd.perc_revenue) || '</perc_revenue>
<image><![CDATA[' || uxml_escapefor_cdata(rcd.image) || '</image>
<interview><![CDATA[' || uxml_escapefor_cdata(rcd.interview) || '</interview>
<blog>' || uxml_parsexml(rcd.blog) || '</blog>
</entity>';
end loop;
sXML := sXML || '</entities></rss:items></rss:feed>';
else
--search could be any one of a number of companies
sXML := sXML || '<manyfound>';
sXML := sXML || '</manyfound>';
end if;
sXML := sXML || '</carrotmob></root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_dodelete
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCarrotMobId alias for $4;
begin
delete from tcarrotmob where carrotmobid = iCarrotMobId;
return '<root/>';
end;
-
ppp_carrotmobuk_mob_doleavemob
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCarrotMobId alias for $4;
sXML text;
iUserId tuser.userid%TYPE;
begin
sXML := '<root>';
iUserId := usession_userid(sSession);
if not iUserId is null then
delete from tcarrotmob_user where carrotmobid = iCarrotMobId and userid = iUserId;
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_dovote
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCarrotMobId alias for $4;
iEntityId alias for $5;
iUserId tuser.userid%TYPE;
begin
iUserId := usession_userid(sSession);
if not iUserId is null then
delete from tcarrotmob_vote where carrotmobid = iCarrotMobId and userid = iUserId;
insert into tcarrotmob_vote(carrotmobid, entityid, userid) values(iCarrotMobId, iEntityId, iUserId);
end if;
return '<root/>';
end;
-
ppp_carrotmobuk_mob_index
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
iUserId tuser.userid%TYPE;
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
rcd record;
begin
iUserId := usession_userid(sSession);
--works with logged in and not
sXML := '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[carrot mobings</rss:title>
<rss:description><![CDATA[upcoming mobings</rss:description>
<rss:relativelinkroot><![CDATA[/mob/</rss:relativelinkroot>
</rss:details>
<rss:items>
<mobings>';
for rcd in select cm.carrotmobid, cm.name, cm.description, cm.image, cm.createdate, cm.mobdate, cm.userid,
cm.location, cm.longitude as cm_longitude, cm.latitude as cm_latitude,
u.userid, u.longitude as u_longitude, u.latitude as u_latitude,
udistance(cm.longitude, cm.latitude, u.longitude, u.latitude) as distance,
(select count(*) from tcarrotmob_entity where carrotmobid = cm.carrotmobid) as entity_count,
(select count(*) from tcarrotmob_user where carrotmobid = cm.carrotmobid) as people_count,
not cu.userid is null as joined
from tcarrotmob cm
left outer join tuser u on u.userid = iUserId --always include the user if logged in
left outer join tcarrotmob_user cu on cm.carrotmobid = cu.carrotmobid and cu.userid = u.userid --include only if joined the CM
order by distance
loop
sXML := sXML || '<carrotmob id="' || rcd.carrotmobid || '" entitycount="' || rcd.entity_count || '" peoplecount="' || rcd.people_count || '" joined="' || rcd.joined || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</rss:title>
<rss:id><![CDATA[' || rcd.carrotmobid || '</rss:id>
' || uxml_user(rcd.userid) || '
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate)) || '</createdate>
<rss:description>' || uxml_parsexml(rcd.description) || '</rss:description>
<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</rss:pubdate>
<mobdate><![CDATA[' || uxml_escapefor_cdata(coalesce(uformatdate(rcd.mobdate, 2), '')) || '</mobdate>
<location><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.location, '')) || '</location>
<point logitude="' || coalesce(rcd.cm_longitude, '') || '" latitude="' || coalesce(rcd.cm_latitude, '') || '"/>
<image><![CDATA[' || uxml_escapefor_cdata(rcd.image) || '</image>';
if not rcd.distance is null then sXML := sXML || '<distance>' || rcd.distance || '</distance>'; end if;
sXML := sXML || '</carrotmob>';
end loop;
sXML := sXML || '</mobings></rss:items></rss:feed></root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_overallcompanyreview
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCarrotMobId alias for $4;
sXML text;
begin
sXML := '<root>';
select into sXML sXML || '<overallcompanyreview>' || overallcompanyreview || '</overallcompanyreview>'
from tcarrotmob where carrotmobid = iCarrotMobId;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_mob_rsvp
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCarrotMobId alias for $4;
sXML text;
iUserId tuser.userid%TYPE;
begin
sXML := '<root>';
iUserId := usession_userid(sSession);
if not iUserId is null then
if not exists(select * from tcarrotmob_user where carrotmobid = iCarrotMobId and userid = iUserId) then
insert into tcarrotmob_user(carrotmobid, userid) values(iCarrotMobId, iUserId);
end if;
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_carrotmobuk_session
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSiteroot alias for $4;
sUserAgent alias for $5;
iSessionId integer;
bExists boolean;
iUserId integer;
iCompanyId integer;
iEntityId integer;
sXML text;
begin
bExists := usession_exists(sSessionId);
iSessionId := usession_autocreate(sSessionId, sSiteroot, sUserAgent); --will auto-create linked to the domain if necessary
select into sXML '<session
id="' || sessionid || '"
string="' || sessionstring || '"
new="' || (not bExists) || '"
autosaveentities="' || autosaveentities || '"
autosavearticles="' || autosavearticles || '">'
from tsession where sessionid = iSessionId;
sXML := sXML || '<authentication>';
iUserId := usession_userid(sSessionId);
if iUserId is null then
sXML := sXML || '<nouser/>';
else
sXML := sXML || uxml_user(iUserId);
end if;
sXML := sXML || '</authentication>';
sXML:= sXML || '</session>';
return sXML;
end;
-
ppp_easyethical_aboutus
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
begin
sXML := '<root>' || uxml_cms_values(sSessionId, sSchema, iVersion, '{easyethical_aboutus}') || '</root>';
return sXML;
end;
-
ppp_easyethical_account_blog_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
begin
sXML := '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[personal blog</rss:title>
<rss:description><![CDATA[personal blog</rss:description>
<rss:relativelinkroot><![CDATA[/account/blog/</rss:relativelinkroot>
</rss:details>
<rss:items>
<posts>';
for rcd in select uxml_blogpost($1, $2, $3, blogpostid)
from tblogpost
where userid = usession_userid(sSessionId)
order by blogpostid desc
loop
sXML := sXML || rcd.uxml_blogpost;
end loop;
sXML := sXML || '</posts>
</rss:items>
</rss:feed>
</root>';
return sXML;
end;
-
ppp_easyethical_account_contributions
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iUserId integer;
sTitle text;
sXML text;
rcd record;
begin
sXML := '<root>';
iUserId := usession_userid(sSessionId);
if not iUserId is null then
select into sXML sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[contributions from ' || uxml_escapefor_cdata(firstname) || '</rss:title>
<rss:description><![CDATA[article summaries as they happen</rss:description>
<rss:relativelinkroot><![CDATA[/account/contributions?id=</rss:relativelinkroot>
</rss:details>
<rss:items>
<summaries>'
from tuser where userid = iUserId;
for rcd in select ts.summaryid, ts.articleid, ts.title, ts.body, ts.createdate,
ta.title as articletitle
from tsummary ts
inner join tarticle ta on ts.articleid = ta.articleid
where ts.userid = iUserId
order by articleid
loop
sTitle := rcd.title;
if sTitle is null or sTitle = '' then sTitle := 'summary'; end if;
sXML := sXML || '<summary id="' || rcd.summaryid || '" articleid="' || rcd.articleid || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(sTitle) || '</rss:title>
<rss:pubdate><![CDATA[' || uformatdate(rcd.createdate, 2) || '</rss:pubdate>
<date><![CDATA[' || uformatdate(rcd.createdate) || '</date>
<articletitle><![CDATA[' || uxml_escapefor_cdata(rcd.articletitle) || '</articletitle>
<rss:body><![CDATA[' || uxml_escapefor_cdata(rcd.body) || '</rss:body>
</summary>';
end loop;
sXML := sXML || '</summaries>
</rss:items>
</rss:feed>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_dodelete_all_contributions
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
iUserId tuser.userid%TYPE;
begin
sXML := '<root>';
--login
iUserId := usession_userid(sSession);
--return success
if not iUserId is null then
delete from tsummary where userid = iUserId;
sXML := sXML || '<success/>';
else
sXML := sXML || '<loginfailed/>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_dosetstatus
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sStatus alias for $4;
sXML text;
iUserId tuser.userid%TYPE;
begin
sXML := '<root>';
iUserId := usession_userid(sSession);
if not iUserId is null then
insert into tstatus(userid, status) values(iUserId, sStatus);
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_index
(
25, 25, 23, 23, 23, 25, 16, 16, 16, 16, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iGoogleStatus alias for $4;
iPointCount alias for $5;
sFirstPoint alias for $6;
bSyncWithTwitter alias for $7;
bSyncWithFacebook alias for $8;
bAllowFollowers alias for $9;
bPublicStatus alias for $10;
sAvatar alias for $11;
sArea alias for $12;
sLocationDetails alias for $13;
sSubmit alias for $14;
--geo
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
sLocation tuser.location%TYPE;
--original values
sOriginalAvatar tuser.avatar%TYPE;
sOriginalArea tuser.area%TYPE;
sOriginalLocation tuser.location%TYPE;
bSubmission boolean;
bOk boolean;
sEmailAddressRequired text;
sFinalLocationDetails text;
sXML text;
sFormXML text;
sSuccessXML text;
iUserId tuser.userid%TYPE;
begin
iUserId := usession_userid(sSession);
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sFormXML := '';
sSuccessXML := '';
if iUserId is null then --we can only do this if we have a user
sXML := '<nouser/>';
else
--origonal values (update form)
select into sOriginalAvatar, sOriginalArea, sOriginalLocation
avatar, area, location
from tuser where userid = iUserId;
sFormXML := '<form_requirements submission="' || bSubmission || '">';
sFormXML := sFormXML || '<syncwithtwitter>
<value><![CDATA[' || case bSubmission when true then bSyncWithTwitter else bSyncWithTwitter end || '</value>
<original><![CDATA[' || bSyncWithTwitter || '</original>
</syncwithtwitter>';
sFormXML := sFormXML || '<syncwithfacebook>
<value><![CDATA[' || case bSubmission when true then bSyncWithFacebook else bSyncWithFacebook end || '</value>
<original><![CDATA[' || bSyncWithFacebook || '</original>
</syncwithfacebook>';
sFormXML := sFormXML || '<allowfollowers>
<value><![CDATA[' || case bSubmission when true then bAllowFollowers else bAllowFollowers end || '</value>
<original><![CDATA[' || bAllowFollowers || '</original>
</allowfollowers>';
sFormXML := sFormXML || '<publicstatus>
<value><![CDATA[' || case bSubmission when true then bPublicStatus else bPublicStatus end || '</value>
<original><![CDATA[' || bPublicStatus || '</original>
</publicstatus>';
sFormXML := sFormXML || '<avatar>
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sAvatar else sOriginalAvatar end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalAvatar) || '</original>
</avatar>';
--geo (optional)
--user enters search location term in the area and then selects a location (2 part forced validation failure sequence)
sFormXML := sFormXML || '<area default="London, Greater London" help="examples: N22 6QP, Brixton, London, City road, Hyde Park (all locations postpended with UK)">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sArea else sOriginalArea end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalArea) || '</original>
</area>';
--if an area has been entered but a location is not selected then we have a validation issue
--if there is no area or location then the user has opted to not include it
sFormXML := sFormXML || '<location>
<value><![CDATA[' || uxml_escapefor_cdata(sLocationDetails) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalLocation) || '</original>';
if bSubmission then
sFinalLocationDetails := sLocationDetails;
if not sArea = '' and sLocationDetails = '' then --optional
if iPointCount = 0 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[location not found</validation_error>'; end if;
if iPointCount = 1 then sFinalLocationDetails := sFirstPoint; end if;
if iPointCount > 1 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[please select a location</validation_error>'; end if;
end if;
end if;
sFormXML := sFormXML || '</location>';
sFormXML := sFormXML || '</form_requirements>';
end if;
if bSubmission and bOk then
sSuccessXML := '<success>';
--geo (optional)
if not sFinalLocationDetails is null and not sFinalLocationDetails = '' then
iLongitude := substring(sFinalLocationDetails from '[-.0-9]+');
iLatitude := substring(sFinalLocationDetails from '[-.0-9]+ *, *([-.0-9]+)');
sLocation := substring(sFinalLocationDetails from '[-.0-9]+ *, *[-.0-9]+ *, *0 (.*)');
update tuser set longitude = iLongitude,
latitude = iLatitude,
location = sLocation,
area = sLocation --store the location selected in the area
where userid = iUserId;
end if;
--update the account
update tuser set avatar = sAvatar
where userid = iUserId;
--return success (username and email unique already checked in this transaction)
sSuccessXML := sSuccessXML || uxml_user(iUserId);
sSuccessXML := sSuccessXML || '</success>';
end if;
sXML := '<root>' || sSuccessXML || sFormXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_knowledge
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCutOff alias for $4;
sOrder alias for $5;
iUserId integer;
sTitle text;
sXML text;
rcd record;
begin
sXML := '<root>';
iUserId := usession_userid(sSessionId);
if not iUserId is null then
select into sXML sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[knowledge of ' || uxml_escapefor_cdata(firstname) || '</rss:title>
<rss:description><![CDATA[what this person knows about in the system</rss:description>
<rss:relativelinkroot><![CDATA[/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<theknowledge>'
from tuser where userid = iUserId;
for rcd in select vkr.entityid, qs.phrase as name,
vkr.maxcreatedate as reading_start, vkr.count, vkr.groupcount, vkr.rank,
vkr.count * 100 / vkr.groupcount as perc
from vknowledge_rank vkr
inner join tentity e on vkr.entityid = e.entityid
inner join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
where vkr.userid = iUserId
and case sCutOff
when 'all' then true
when '> rank 10' then (vkr.rank < 10)
when '> 1 article read' then (vkr.count > 1)
when '> 10 articles read' then (vkr.count > 10)
else (vkr.count * 100 / vkr.groupcount >=1) --> 1% articles read
end
order by case sOrder
when 'name' then 256 - ascii(qs.phrase)
when 'rank' then vkr.rank
when 'number articles read' then count
else vkr.count * 100 / vkr.groupcount --% articles read
end desc
loop
sXML := sXML || '<company id="' || rcd.entityid || '">
<knowledge count="' || rcd.count || '" groupcount="' || rcd.groupcount || '" rank="' || rcd.rank || '"/>
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</rss:title>
<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.reading_start, 2)) || '</rss:pubdate>
<reading_start><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.reading_start)) || '</reading_start>
</company>';
end loop;
sXML := sXML || '</theknowledge>
</rss:items>
</rss:feed>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_login
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sUsername alias for $4;
sPassword alias for $5;
sSubmit alias for $6;
sXML text;
iUserId tuser.userid%TYPE;
bSubmission boolean;
bOk boolean;
begin
bSubmission := not sSubmit = '';
bOk := true; --validation errors?
sXML := '<root>
<form_requirements submission="' || bSubmission || '" submit="login">';
--try login (check all credentials here)
if bSubmission then
iUserId := usession_login(sSession, sUsername, sPassword);
if iUserId is null then
bOk := false;
sXML := sXML || '<validation_error>login failed</validation_error>';
end if;
end if;
sXML := sXML || '<username required=".+">
<value><![CDATA[' || uxml_escapefor_cdata(sUsername) || '</value>
</username>
<password required=".+">
<value><![CDATA[' || uxml_escapefor_cdata(sPassword) || '</value>
</password>
</form_requirements>
</root>';
if bSubmission and bOk then
sXML := '<root>' || uxml_user(iUserId) || '</root>';
end if;
return sXML;
end;
-
ppp_easyethical_account_logout
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
begin
perform usession_logout(sSession);
return '<root/>';
end;
-
ppp_easyethical_account_register
(
25, 25, 23, 16, 25, 23, 23, 25, 25, 25, 25, 25, 25, 23, 25, 23, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(recaptcha analysis is always put first by the system although it appears elsewhere in the form)
bRecaptchaOk alias for $4; --can be faked to true by wrapper proc
sRecaptchaError alias for $5;
--(location analysis is always put first by the system although it appears elsewhere in the form)
iGoogleStatus alias for $6;
iPointCount alias for $7;
sFirstPoint alias for $8;
--form parameters in order
sFirstName alias for $9;
sMiddleName alias for $10;
sLastName alias for $11;
sEmailAddress alias for $12; --cannot be the screen name
sUserName alias for $13; --often the screen name, so cannot be the email address
iUsernameGenerator alias for $14; --0 - use the username, 1 means use the sUsername as a stem for an auto-username (user should be informed via email of this username), 2 - use email 1st part with auto-generator
sPassword alias for $15;
iPasswordGenerator alias for $16; --0 - use the password, 1 generate password
sArea alias for $17; --input to fuel the location analysis
sLocationDetails alias for $18; --often filled out on second validation if there are options
sRecaptchaRequest alias for $19;
sRecaptchaResponse alias for $20;
sSubmit alias for $21; --standard submit button to indicate whether form data has been sent or not
--inputs generated from the sLocationDetails parsing (a,b,c d)
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
sLocation tuser.location%TYPE;
bSubmission boolean;
bOk boolean;
sFinalLocationDetails text;
sEmailAddressRequired text;
sStem text;
sFinalUsername text;
sXML text;
iUserId tuser.userid%TYPE;
begin
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sXML := '<form_requirements submission="' || bSubmission || '">';
--######################################## form fields ##############################################
--with optional validation
--in order
sXML := sXML || '<firstname><value><![CDATA[' || uxml_escapefor_cdata(sFirstName) || '</value></firstname>'; --optional
sXML := sXML || '<middlename><value><![CDATA[' || uxml_escapefor_cdata(sMiddleName) || '</value></middlename>'; --optional
sXML := sXML || '<lastname><value><![CDATA[' || uxml_escapefor_cdata(sLastName) || '</value></lastname>'; --optional
--email address
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sXML := sXML || '<emailaddress caption="email address" required="' || sEmailAddressRequired || '" help="will be kept private" validation_error="email address not the right format, e.g. a@b.com">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sEmailAddress) || '</value>';
if bSubmission then
if not sEmailAddress ~ sEmailAddressRequired then bOk := false; sXML := sXML || '<validation_error><![CDATA[email address not the right format, e.g. a@b.com</validation_error>'; end if;
if exists(select * from tuser where emailaddress = lower(sEmailAddress)) then bOk := false; sXML := sXML || '<validation_error><![CDATA[email address already exists</validation_error>'; end if;
end if;
sXML := sXML || '</emailaddress>';
--username
sXML := sXML || '<username required=".+" help="will appear on the site">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sUserName) || '</value>';
if bSubmission then
if iUsernameGenerator = 0 then
--use the username field as is
if not sUserName ~ '.+' then bOk := false; sXML := sXML || '<validation_error><![CDATA[username required</validation_error>'; end if;
if exists(select * from tuser where username = sUserName) then bOk := false; sXML := sXML || '<validation_error><![CDATA[username already exists</validation_error>'; end if;
sFinalUsername := sUserName;
elsif iUsernameGenerator = 1 then
--use the username field as a stem for a generated username
sStem := sUserName;
sFinalUsername := unext_username(sStem);
elsif iUsernameGenerator = 2 then
--generate a username from the email address
sStem := substring(sEmailAddress from '[^@]+');
sFinalUsername := unext_username(sStem);
end if;
end if;
sXML := sXML || '</username>';
sXML := sXML || '<username_generator hide="1"><value><![CDATA[' || iUsernameGenerator || '</value></username_generator>';
--password
sXML := sXML || '<password required=".+">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sPassword) || '</value>';
if bSubmission and not sPassword ~ '.+' then bOk := false; sXML := sXML || '<validation_error><![CDATA[password required</validation_error>'; end if;
sXML := sXML || '</password>';
sXML := sXML || '<password_generator hide="1"><value><![CDATA[' || iPasswordGenerator || '</value></password_generator>';
--geo (optional)
--user enters search location term in the area and then selects a location (2 part forced validation failure sequence)
sXML := sXML || '<area default="London, Greater London" help="examples: N22 6QP, Brixton, London, City road, Hyde Park (all locations postpended with UK)" keep="1">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sArea) || '</value>';
sXML := sXML || '</area>';
--if an area has been entered but a location is not selected then we have a validation issue
--if there is no area or location then the user has opted to not include it
sXML := sXML || '<location>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sLocationDetails) || '</value>';
if bSubmission and iGoogleStatus = 200 then
sFinalLocationDetails := sLocationDetails;
if not sArea = '' and sLocationDetails = '' then --optional
if iPointCount = 0 then bOk := false; sXML := sXML || '<validation_error><![CDATA[location not found</validation_error>'; end if;
if iPointCount = 1 then sFinalLocationDetails := sFirstPoint; end if;
if iPointCount > 1 then bOk := false; sXML := sXML || '<validation_error><![CDATA[please select a location</validation_error>'; end if;
end if;
end if;
sXML := sXML || '</location>';
--recaptcha (recaptcha analysis is always put first by the system although it appears elsewhere in the form)
sXML := sXML || '<recaptcha>';
if bSubmission and not bRecaptchaOk then bOk := false; sXML := sXML || '<validation_error><![CDATA[recaptcha did not match</validation_error>'; end if;
sXML := sXML || '</recaptcha>';
sXML := sXML || '</form_requirements>';
--######################################## action ##############################################
if bSubmission and bOk then
sXML := '<success>';
--geo
if not sFinalLocationDetails = '' then
iLongitude := substring(sFinalLocationDetails from '[-.0-9]+');
iLatitude := substring(sFinalLocationDetails from '[-.0-9]+ *, *([-.0-9]+)');
sLocation := substring(sFinalLocationDetails from '[-.0-9]+ *, *[-.0-9]+ *, *0 (.*)');
end if;
--create the account
iUserId := uadd_user(sFirstName, sMiddleName, sLastName, sFinalUsername, sPassword, sEmailAddress, sSession, iLongitude, iLatitude, sLocation);
--return success (username and email unique already checked in this transaction)
sXML := sXML || uxml_user(iUserId);
--details for sending the email (not fields exactly: goes through an additional XSLT)
--user is advised of their username, password and verification code in the email
sXML := sXML || '<sendmail:email>
<sendmail:to><![CDATA[' || sFirstName || ' ' || sLastName || ' <' || uxml_escapefor_cdata(sEmailAddress) || '></sendmail:to>
<sendmail:guid><![CDATA[' || uxml_escapefor_cdata(sSession) || '</sendmail:guid>
<sendmail:username><![CDATA[' || uxml_escapefor_cdata(sFinalUsername) || '</sendmail:username>
<sendmail:password><![CDATA[' || uxml_escapefor_cdata(sPassword) || '</sendmail:password>
</sendmail:email>';
sXML := sXML || '</success>';
end if;
sXML := '<root>' || sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_account_verify
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sVerificationId alias for $4;
sXML text;
iUserId tuser.userid%TYPE;
iSessionId tsession.sessionid%TYPE;
begin
sXML := '<root>';
--maybe manual
if sVerificationId = '' then
sXML := sXML || '<verificationrequired/>';
else
--look for verification key
select into iUserId userid from tuser where verificationid = sVerificationId;
if not iUserId is null then
--verify the account
update tuser set verified = true where userid = iUserId;
--get / create current session
iSessionId := usession_id(sSession);
--log in with current session
update tsession set userid = iUserId where sessionid = iSessionId;
--return user details
sXML := sXML || uxml_user(iUserId);
else
sXML := sXML || '<verificationfailed/>';
end if;
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_activity_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iLimit alias for $4;
sXML text;
iLimitStatuses integer;
rcd record;
rcdE record;
begin
if iLimit = 0 then iLimitStatuses := 20; else iLimitStatuses := iLimit; end if;
sXML := '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[site activity</rss:title>
<rss:description><![CDATA[what people are currently doing on the site</rss:description>
<rss:relativelinkroot><![CDATA[/account/</rss:relativelinkroot>
</rss:details>
<rss:items>
<sessions>';
for rcd in select ls.userid, ls.sessionid, ls.lastactiondate,
tu.firstname, tu.lastname, tu.avatar,
lst.statusid, lst.status, lst.entityid,
la.articleid, la.title, e.entityid as wrtentityid, qs.phrase as wrtentityname
from vlastsession ls
inner join tuser tu on ls.userid = tu.userid
left outer join vlaststatus lst on ls.userid = lst.userid
left outer join vlastarticle la on ls.userid = la.userid
left outer join tentity e on la.entityid = e.entityid
left outer join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
order by ls.lastactiondate desc
limit iLimitStatuses
loop
sXML := sXML || '<session id="' || rcd.sessionid || '">
<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.lastactiondate, 2)) || '</rss:pubdate>
<rss:title><![CDATA[' || uxml_escapefor_cdata(uxml_escapefor_cdata(rcd.firstname || ' ' || rcd.lastname)) || '</rss:title>
<rss:description><![CDATA[' || uxml_escapefor_cdata(uxml_escapefor_cdata(rcd.status)) || '</rss:description>
<user id="' || rcd.userid || '">
<avatar><![CDATA[' || uxml_escapefor_cdata(rcd.avatar) || '</avatar>
<firstname><![CDATA[' || uxml_escapefor_cdata(rcd.firstname) || '</firstname>
<lastname><![CDATA[' || uxml_escapefor_cdata(rcd.lastname) || '</lastname>
</user>';
if not rcd.statusid is null then
sXML := sXML || '<status id="' || rcd.statusid || '"><![CDATA[' || uxml_escapefor_cdata(rcd.status) || '</status>';
end if;
sXML := sXML || '<lastactiondate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.lastactiondate)) || '</lastactiondate>';
if not rcd.articleid is null then
sXML := sXML || '<article id="' || rcd.articleid || '">
<title><![CDATA[' || uxml_escapefor_cdata(rcd.title) || '</title>';
if not rcd.wrtentityid is null then
sXML := sXML || '<company id="' || rcd.wrtentityid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.wrtentityname) || '</name>
</company>';
end if;
sXML := sXML || '<entities>';
for rcdE in select te.entityid, qs.phrase as name
from tentity_article ea
inner join tentity te on ea.entityid = te.entityid
inner join tlcompany tc on te.entityid = tc.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where ea.articleid = rcd.articleid
loop
sXML := sXML || '<company id="' || rcdE.entityid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcdE.name) || '</name>
</company>';
end loop;
sXML := sXML || '</entities>
</article>';
end if;
sXML := sXML || '</session>';
end loop;
sXML := sXML || '</sessions>
</rss:items>
</rss:feed>
</root>';
return sXML;
end;
-
ppp_easyethical_admin_users
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSystem alias for $4;
sEmailAddress alias for $5;
sSubmit alias for $6;
sXML text;
bSubmission boolean;
sSystemToUse char(2);
rcd record;
begin
sXML := '<root>';
bSubmission := not sSubmit = '';
if sSystem = '' then sSystemToUse = 'EE'; else sSystemToUse = sSystem; end if;
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator for this screen</security_denied></root>'; end if;
--user management
if bSubmission then
if sSubmit = 'delete user' then delete from tuser where emailaddress = sEmailAddress; end if;
if sSubmit = 'delete subscriber' then delete from temaillist where emailaddress = sEmailAddress and listid = sSystemToUse; end if;
end if;
--users
sXML := sXML || '<users>';
for rcd in select tu.userid, tu.firstname, tu.middlename, tu.lastname, tu.username, tu.emailaddress, tu.createdate, tu.verified,
tu.lastlogin, tu.businessownerid
from tuser tu
where system = sSystemToUse and not type9c = 'BUS'
order by tu.username
loop
sXML := sXML || '<user id="' || rcd.userid || '" businessownerid="' || coalesce(rcd.businessownerid, 0) || '">
<firstname><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.firstname, '')) || '</firstname>
<middlename><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.middlename, '')) || '</middlename>
<lastname><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.lastname, '')) || '</lastname>
<username><![CDATA[' || uxml_escapefor_cdata(rcd.username) || '</username>
<emailaddress verified="' || rcd.verified || '"><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.emailaddress, '')) || '</emailaddress>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</createdate>
<lastlogin><![CDATA[' || uxml_escapefor_cdata(coalesce(uformatdate(rcd.lastlogin, 1), '')) || '</lastlogin>
</user>';
end loop;
sXML := sXML || '</users>';
--emaillist
sXML := sXML || '<emaillist>';
for rcd in select el.emailaddress, el.createdate
from temaillist el
where listid = sSystemToUse
order by el.emailaddress
loop
sXML := sXML || '<subscriber>
<emailaddress><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.emailaddress, '')) || '</emailaddress>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</createdate>
</subscriber>';
end loop;
sXML := sXML || '</emaillist>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_analysis_doc
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sDoc alias for $4;
sXml text;
rQS record;
iEntityId integer;
iLastEntityId integer;
begin
sXML := '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[analysis of text</rss:title>
<rss:description><![CDATA[changes to the text, new companies as there are reported</rss:description>
<rss:relativelinkroot><![CDATA[/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<entities>';
iLastEntityId := 0;
--select all the qualifiersets from uanalysedoc()
--these are only entity QSs, as uanalysedoc() restricts to entities
for rQS in select distinct eq.entityid, eq.qualifiersetid, qs.phrase,
t1.companyid, t2.countryid, t3.personid, t4.productid, t5.producttypeid
from uanalysedoc(sDoc)
inner join tentity_qualifierset eq on uanalysedoc = eq.qualifiersetid
inner join tqualifierset qs on eq.qualifiersetid = qs.qualifiersetid
left outer join tlcompany t1 on eq.entityid = t1.entityid
left outer join tlcountry t2 on eq.entityid = t2.entityid
left outer join tlperson t3 on eq.entityid = t3.entityid
left outer join tlproduct t4 on eq.entityid = t4.entityid
left outer join tlproducttype t5 on eq.entityid = t5.entityid
order by eq.entityid, eq.qualifiersetid
loop
--common entity data
iEntityId := rQS.entityid;
if not iEntityId = iLastEntityId then
--entity type specific data
if not iLastEntityId = 0 then sXML := sXML || '</entity>'; end if;
sXML := sXML || '<entity id="' || iEntityId || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rQS.phrase) || '</rss:title>';
if not rQS.companyid is null then
sXML := sXML || uxml_company(sSessionId, sSchema, iVersion, rQS.companyid, 0, 10);
elsif not rQS.countryid is null then
sXML := sXML || uxml_country(sSessionId, sSchema, iVersion, rQS.countryid, 10);
elsif not rQS.personid is null then
sXML := sXML || uxml_person( sSessionId, sSchema, iVersion, rQS.personid, 10);
elsif not rQS.productid is null and char_length(rQS.phrase) > 2 and not rQS.phrase ~ '^[0-9]+$' then
sXML := sXML || uxml_product( sSessionId, sSchema, iVersion, rQS.productid, 10);
elsif not rQS.producttypeid is null then
end if;
iLastEntityId := iEntityId;
end if;
sXML := sXML || '<qs id="' || rQS.qualifiersetid || '"><![CDATA[' || uxml_escapefor_cdata(rQS.phrase) || '</qs>';
end loop;
if not iLastEntityId = 0 then sXML := sXML || '</entity>'; end if;
sXML := sXML || '</entities>
</rss:items>
</rss:feed>
</root>';
return sXML;
end;
-
ppp_easyethical_analysis_url
()
/*
$4 = url
$5 = doc words
*/
select ppp_easyethical_analysis_doc($1, $2, $3, $5)
-
ppp_easyethical_article_add_summary
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
sXML text;
rcd record;
begin
sXML := '<root>';
--summaries
sXML := sXML || '<summaries>';
if exists(select * from vsummary where articleid = iArticleId) then
select into sXML sXML || '<summary id="' || summaryid || '">
<title><![CDATA[' || uxml_escapefor_cdata(title) || '</title>
<body><![CDATA[' || uxml_escapefor_cdata(body) || '</body>
</summary>'
from vsummary
where articleid = iArticleId;
end if;
sXML := sXML || '</summaries>';
--quotes
sXML := sXML || '<quotes>';
for rcd in select aq.quoteid, aq.quote
from tarticle_quote aq
where aq.articleid = iArticleId
order by aq.quoteid
loop
sXML := sXML || '<quote id="' || rcd.quoteid || '"><![CDATA[' || uxml_escapefor_cdata(rcd.quote) || '</quote>';
end loop;
sXML := sXML || '</quotes>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_article_all
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
iEntityId alias for $5;
sXML text;
bTruncated bool;
iUserId tuser.userid%TYPE;
iSessionId tsession.sessionid%TYPE;
bAutoSaveEntities tsession.autosaveentities%TYPE;
bAutoSaveArticles tsession.autosavearticles%TYPE;
sEntityName text;
sSentence text;
sTitle text;
sBody text;
sSummaryTitle text;
sFirstPara text;
s45 text;
rcd record;
begin
sXML := '<root>';
--session information
iSessionId := usession_id(sSession);
select into iUserId, bAutoSaveEntities, bAutoSaveArticles
userid, autosaveentities, autosavearticles
from tsession where sessionid = iSessionId;
--register this reading against the user (if logged in)
if not iUserId is null then
insert into tknowledge_article(userid, articleid, sessionid, entityid)
values(iUserId, iArticleId, iSessionId, case iEntityId when 0 then null else iEntityId end);
end if;
--register the companies in this article into the session entity list (even if not logged in)
if bAutoSaveEntities = true then
insert into tsession_entity(sessionid, entityid, addsource, rank)
select iSessionId, ea.entityid, 'R', nextval('seqrank')
from tentity_article ea
where ea.articleid = iArticleId
and not exists (select * from tsession_entity se where se.sessionid = iSessionId and se.entityid = ea.entityid);
end if;
--mark the primary company
if not iEntityId = 0 then
update tsession_entity set addsource = 'P' where sessionid = iSessionId and entityid = iEntityId;
if not found then
insert into tsession_entity(sessionid, entityid, addsource) values(iSessionId, iEntityId, 'P');
end if;
end if;
--place this article into the session briefcase
if bAutoSaveArticles and not exists(select * from tsession_briefcase where sessionid = iSessionId and articleid = iArticleId) then
insert into tsession_briefcase(sessionid, articleid)
values(iSessionId, iArticleId);
end if;
--next unread article for this company
--select articleid from tarticle ta where iEntityId
--details of the article
select into sTitle, sBody, sFirstPara, sXML ta.title, ta.body, ufirstpara(ta.body),
sXML || '<article id="' || ta.articleid || '">
<title><![CDATA[' || uxml_escapefor_cdata(ta.title) || '</title>
<url><![CDATA[' || uxml_escapefor_cdata(ta.url) || '</url>
<source id="' || tx.externalsourceid || '"><![CDATA[' || uxml_escapefor_cdata(tx.domain) || '</source>'
from tarticle ta inner join texternalsource tx on ta.externalsourceid = tx.externalsourceid
where ta.articleid = iArticleId;
if not iEntityId = 0 then
sEntityName := uentityname(iEntityId);
sXML := sXML || '<company id="' || iEntityId || '">
<name><![CDATA[' || uxml_escapefor_cdata(sEntityName) || '</name>
</company>';
end if;
--first paragraph
s45 := ufirst45words(sFirstPara);
if not (s45 is null or char_length(s45) = 0) then
bTruncated := not (s45 = sFirstPara);
sXML := sXML || '<firstpara truncated="' || bTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</firstpara>';
end if;
--summaries
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[summaries of article ' || sTitle || '</rss:title>
<rss:description><![CDATA[article summaries as they happen</rss:description>
<rss:relativelinkroot><![CDATA[/article/</rss:relativelinkroot>
</rss:details>
<rss:items>
<summaries>';
for rcd in select ts.summaryid, ts.title, ts.body, ts.createdate,
tu.userid, tu.firstname, tu.lastname, tu.avatar
from tsummary ts
left outer join tuser tu on ts.userid = tu.userid
where ts.articleid = iArticleId
order by ts.summaryid desc
loop
sSummaryTitle := rcd.title;
if sSummaryTitle = '' then sSummaryTitle := 'summary'; end if;
sXML := sXML || '<summary id="' || rcd.summaryid || '">';
iUserId := rcd.userid;
if not iUserId is null then
sXML := sXML || '<user id="' || rcd.userid || '">
<firstname><![CDATA[' || uxml_escapefor_cdata(rcd.firstname) || '</firstname>
<lastname><![CDATA[' || uxml_escapefor_cdata(rcd.lastname) || '</lastname>
<avatar><![CDATA[' || uxml_escapefor_cdata(rcd.avatar) || '</avatar>
</user>';
end if;
--<rss:description truncated="' || false || '"><![CDATA[' || uxml_escapefor_cdata(rcd.body) || '</rss:description>
sXML := sXML || '<date>' || uformatdate(rcd.createdate, 1) || '</date>
<rss:pubdate>' || uformatdate(rcd.createdate, 2) || '</rss:pubdate>
<rss:title><![CDATA[' || uxml_escapefor_cdata(sSummaryTitle) || '</rss:title>
<rss:description truncated="' || false || '">' || rcd.body || '</rss:description>
</summary>';
end loop;
sXML := sXML || '</summaries>
</rss:items>
</rss:feed>';
--entities
sXML := sXML || '<entities>';
for rcd in select e.entityid, qs.phrase as name,
vkr.count, vkr.groupcount, vkr.rank as knowledgerank
from tentity_article ea
inner join tentity e on ea.entityid = e.entityid
inner join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
left outer join vknowledge_rank vkr on e.entityid = vkr.entityid and vkr.userid = iUserId
where ea.articleid = iArticleId
loop
sXML := sXML || '<company id="' || rcd.entityid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
<knowledge count="' || coalesce(rcd.count, 0) || '" groupcount="' || coalesce(rcd.groupcount, 0) || '" rank="' || coalesce(rcd.knowledgerank, 0) || '"/>
</company>';
end loop;
sXML := sXML || '</entities>';
--tags
sXML := sXML || '<tags>';
for rcd in select tt.tagid, qs.phrase as tag, tt.tagtype
from tarticle_tag at
inner join ttag tt on at.tagid = tt.tagid
inner join tqualifierset qs on tt.tagqualifiersetid = qs.qualifiersetid
where at.articleid = iArticleId
order by qs.phrase
loop
sXML := sXML || '<tag id="' || rcd.tagid || '" type="' || rcd.tagtype || '"><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</tag>';
end loop;
sXML := sXML || '</tags>';
--sentences
if not iEntityId = 0 then
sXML := sXML || '<sentences>';
sSentence := uxml_escapefor_cdata(substring(sBody from '[^.!?:<>]*' || sEntityName || '[^.!?:<>]*'));
if not sSentence is null and not sSentence = '' then
sXML := sXML || '<sentence><![CDATA[' || sSentence || '</sentence>';
end if;
sXML := sXML || '</sentences>';
end if;
--quotes
sXML := sXML || '<quotes>';
for rcd in select aq.quoteid, aq.quote
from tarticle_quote aq
where aq.articleid = iArticleId
order by aq.quoteid
loop
sXML := sXML || '<quote id="' || rcd.quoteid || '"><![CDATA[' || uxml_escapefor_cdata(rcd.quote) || '</quote>';
end loop;
sXML := sXML || '</quotes>';
sXML := sXML || '<criteria/>';
sXML := sXML || '<forum/>';
sXML := sXML || '<rate/>';
sXML := sXML || '<otherdocs/>';
sXML := sXML || '</article>';
--get the session entity list etc. (also when not logged in)
sXML := sXML || uxml_session(sSession, sSchema, iVersion);
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_article_doadd_summary
(
25, 25, 23, 23, 23, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
iEntityId alias for $5;
sTitle alias for $6;
sBody alias for $7;
sXML text;
iUserId tuser.userid%TYPE;
begin
iUserId := usession_userid(sSession);
if not iUserId is null then
insert into tsummary(articleid, title, body, userid, md5)
values(iArticleId, sTitle, sBody, iUserId, md5(sBody));
end if;
return '<root/>';
end;
-
ppp_easyethical_article_doaddquote
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
sQuote alias for $5;
sXML text;
begin
sXML := '<root>';
insert into tarticle_quote(articleid, quote) values(iArticleId, sQuote);
sXML := sXML || '<quote>
<id>' || currval('seqquoteid') || '</id>
<text><![CDATA[' || uxml_escapefor_cdata(sQuote) || '</text>
</quote>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_article_doremovequote
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iQuoteId alias for $4;
sXML text;
begin
sXML := '<root>';
delete from tarticle_quote where quoteid = iQuoteId;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_barcode_all
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sBarcode alias for $4;
sGS1Result alias for $5;
sGS1CompanyName alias for $6;
sXML text;
iEntityId tentity.entityid%TYPE;
rcd record;
begin
for rcd in select uexists_company as entityid, uentity_phrase(uexists_company) as name from uexists_company(sGS1CompanyName, true, true) loop
iEntityId := rcd.entityid;
end loop;
sXML := '<root>
<lookup result="' || sGS1Result || '">
<barcode><![CDATA[' || uxml_escapefor_cdata(sBarcode) || '</barcode>
<company>
<name><![CDATA[' || uxml_escapefor_cdata(sGS1CompanyName) || '</name>';
if not iEntityId is null then sXML := sXML || '<EEID>' || iEntityId || '</EEID>'; end if;
sXML := sXML || '</company>
</lookup>
</root>';
return sXML;
end;
-
ppp_easyethical_blog_all
()
select '<root>' || uxml_blogpost($1, $2, $3, 1, $4) || '</root>';
-
ppp_easyethical_blog_index
()
select '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[' || uxml_escapefor_cdata(name) || '</rss:title>
<rss:description><![CDATA[' || uxml_escapefor_cdata(description) || '</rss:description>
<rss:relativelinkroot><![CDATA[/blog/</rss:relativelinkroot>
</rss:details>
<rss:items>
<posts>' || uxml_blogtitles($1, $2, $3, 1, blogcategoryid) || '</posts>
</rss:items>
</rss:feed>
</root>'
from tblogcategory where blogcategoryid = 1;
-
ppp_easyethical_cms_addedit
(
25, 25, 23, 25, 25, 25, 25, 25
)
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCMSId alias for $4; --0 indicates that the entry is a new one (do not retrieve)
sKey alias for $5; --only used during create operations
sParentPage alias for $6; --only used during create operations (optional)
sValue alias for $7;
sSubmit alias for $8;
sOriginalKey tcms.cmskey%TYPE;
sOriginalValue tcmsvalue.value%TYPE;
sOriginalParentPage tcms.parentpage%TYPE;
iID tcms.cmsid%TYPE;
bEdit boolean;
bSubmission boolean;
bOk boolean;
sXML text;
iUserId tuser.userid%TYPE;
begin
--standard add, edit, verify read/write proc
bEdit := not sCMSId = '';
bSubmission := not sSubmit = '';
bOk := true; --validation errors?
--edit mode - get original values
if bEdit then
select into sOriginalKey, sOriginalValue, sOriginalParentPage c.cmskey, cv.value, c.parentpage
from tcms c
inner join tcmsvalue cv on c.cmsid = cv.cmsid
where c.cmsid= sCMSId
order by version desc
limit 1;
else
sOriginalKey := sKey;
sOriginalParentPage := sParentPage;
sOriginalValue := sValue;
end if;
--######################################## form fields ##############################################
--with optional validation
--in order
sXML := '<root><form_requirements submission="' || bSubmission || '">';
sXML := sXML || '<cmsid hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(sCMSId) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sCMSId) || '</original>
</cmsid>';
sXML := sXML || '<cmskey hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(sKey) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(coalesce(sOriginalKey, '')) || '</original>
</cmskey>';
sXML := sXML || '<parentpage hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(sParentPage) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(coalesce(sOriginalParentPage, '')) || '</original>
</parentpage>'; --optional
sXML := sXML || '<value type="editor" fckheight="400" fckcss="' || coalesce(sOriginalParentPage, '') || '.css">
<value><![CDATA[' || uxml_parsexml(sValue) || '</value>
<original><![CDATA[' || uxml_parsexml(coalesce(sOriginalValue, '')) || '</original>
</value>';
sXML := sXML || '</form_requirements></root>';
--######################################## submission ##############################################
if bSubmission and bOk then
if bEdit then
--we have a cmsid
iID := ucms_addversion(sSessionId, sSchema, iVersion, sCMSId::integer, sValue, sParentPage);
else
--we have no cmsid, so add a new entry
iID := ucms_add(sSessionId, sSchema, iVersion, sKey, sValue, sParentPage);
end if;
--output
select into sOriginalKey, sOriginalValue, sOriginalParentPage c.cmskey, cv.value, c.parentpage
from tcms c
inner join tcmsvalue cv on c.cmsid = cv.cmsid
where c.cmsid= iID
order by version desc
limit 1;
sXML := '<root><success>
<cmsid><![CDATA[' || uxml_escapefor_cdata(iID::text) || '</cmsid>
<cmskey><![CDATA[' || uxml_escapefor_cdata(sOriginalKey) || '</cmskey>
<parentpage><![CDATA[' || uxml_escapefor_cdata(sOriginalParentPage) || '</parentpage>
<value><![CDATA[' || uxml_parsexml(sOriginalValue) || '</value>
</success></root>';
end if;
return sXML;
end;
-
ppp_easyethical_cms_managepages
(
25, 25, 23, 25, 25, 25, 25, 25
)
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCMSId alias for $4;
sSubmit alias for $5;
sXML text;
begin
sXML := '<root>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_cms_templates_basic
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select uxml_cms_url($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
-
ppp_easyethical_company_all
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCompany alias for $4; --this may be an id if it is numeric (entirely)
sExternalSource alias for $5;
iLimitDocs alias for $6;
iLimitDocsR integer;
sXML text;
iCount integer;
iCompanyId tlcompany.companyid%TYPE;
iExternalSourceId texternalsource.externalsourceid%TYPE;
rcd record;
begin
sXML := '<root>';
--figure out the name of the company(s), may be an id
if sCompany ~ '^[0-9]+$' then
select into iCount, iCompanyId 1, tc.companyid
from tlcompany tc
where tc.entityid = sCompany;
if iCount is null then iCount := 0; end if; --not a valid company id
else
select into iCount, iCompanyId distinct count(distinct uexists_company), min(tc.companyid)
from uexists_company(sCompany, true, true)
inner join tlcompany tc on tc.entityid = uexists_company;
end if;
--if there is only one then directly return information for that one
if iCount = 0 then
--no results
sXML := sXML || '<notfound/>';
elsif iCount = 1 then
--examine the externalsource id sent through
--using the same finding method as with the company string
iExternalSourceId := 0;
if not sExternalSource = '' then --blank is not sent through
if sExternalSource ~ '^[0-9]+$' then
select into iCount, iExternalSourceId 1, tx.externalsourceid
from texternalsource tx where tx.externalsourceid = sExternalSource;
if iCount is null then iCount := 0; end if; --not a valid company id
else
select into iCount, iExternalSourceId count(*), min(tx.externalsourceid)
from uexists_externalsource(sExternalSource)
inner join texternalsource tx on uexists_externalsource = tx.externalsourceid;
end if;
if iCount = 0 then
sXML := sXML || '<externalsourcenotfound/>';
iExternalSourceId := 0;
elsif iCount = 1 then
select into sXML sXML || '<externalsource id="' || tx.externalsourceid || '">
<domain><![CDATA[' || uxml_escapefor_cdata(tx.domain) || '</domain>
<rootpagetitle><![CDATA[' || uxml_escapefor_cdata(tx.rootpagetitle) || '</rootpagetitle>
</externalsource>'
from texternalsource tx where tx.externalsourceid = iExternalSourceId;
else
sXML := sXML || '<externalsourcemanyfound>';
for rcd in select tx.externalsourceid, tx.domain, tx.rootpagetitle
from uexists_externalsource(sExternalSource)
inner join texternalsource tx on uexists_externalsource = tx.externalsourceid
loop
sXML := sXML || '<externalsource id="' || rcd.externalsourceid || '">
<domain><![CDATA[' || uxml_escapefor_cdata(rcd.domain) || '</domain>
<rootpagetitle><![CDATA[' || uxml_escapefor_cdata(rcd.rootpagetitle) || '</rootpagetitle>
</externalsource>';
end loop;
sXML := sXML || '</externalsourcemanyfound>';
iExternalSourceId := 0;
end if;
end if;
--search resolves to exactly one company so return its summary details
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
sXML := sXML || uxml_company(sSession, sSchema, iVersion, iCompanyId, iExternalSourceId, iLimitDocsR);
else
--search could be any one of a number of companies
sXML := sXML || '<manyfound>';
for rcd in select uexists_company as companyid
from uexists_company(sCompany, true, true)
inner join tlcompany tc on tc.entityid = uexists_company
loop
sXML := sXML || uxml_company(sSession, sSchema, iVersion, rcd.companyid, 10);
end loop;
sXML := sXML || '</manyfound>';
end if;
--get the session entity list etc. (also when not logged in)
sXML := sXML || uxml_session(sSession, sSchema, iVersion);
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_company_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
cLetter alias for $4;
iTopCompanies alias for $5;
iTopCompaniesLimit integer;
sXML text;
rcd_letter record;
rcd_company record;
begin
sXML := '<root>';
if cLetter = '' then
--------------------------------------------------------------------------- all letters ---------------------------------------------------------------------------
if iTopCompanies = 0 then
iTopCompaniesLimit = 100;
else
iTopCompaniesLimit = iTopCompanies;
end if;
--lettgroups 0,1,2,3,a,b,c,d,e,...
sXML := sXML || '<letters>';
for rcd_letter in select distinct upper(substring(qs.phrase from 1 for 1)) as letter
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
order by upper(substring(qs.phrase from 1 for 1))
loop
sXML := sXML || '<letter><![CDATA[' || uxml_escapefor_cdata(rcd_letter.letter) || '</letter>';
end loop;
sXML := sXML || '</letters>';
--top 100 companies
sXML := sXML || '<rss:feed><rss:details>
<rss:title><![CDATA[top 100 companies by activity</rss:title>
<rss:description><![CDATA[ordered by the amount of discussion and documents happening about them</rss:description>
<rss:relativelinkroot><![CDATA[/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<companies>';
for rcd_company in select tc.entityid, tc.companyid, qs.phrase as name, count(*) as count
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tentity_article tae on tc.entityid = tae.entityid
group by tc.entityid, tc.companyid, qs.phrase
order by count(*) desc
limit iTopCompaniesLimit
loop
sXML := sXML || '<company id="' || rcd_company.companyid || '" entityid="' || rcd_company.entityid || '" count="' || rcd_company.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd_company.name) || '</rss:title>
<rss:description><![CDATA[' || rcd_company.count || ' documents about this company</rss:description>
</company>';
end loop;
sXML := sXML || '</companies></rss:items></rss:feed>';
else
--------------------------------------------------------------------------- one letter ---------------------------------------------------------------------------
sXML := sXML || '<letter><![CDATA[' || uxml_escapefor_cdata(upper(cLetter)) || '</letter>';
sXML := sXML || '<companies>';
for rcd_company in select tc.entityid, qs.phrase as name, count(*) as count
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tentity_article tae on tc.entityid = tae.entityid
where upper(substring(qs.phrase from 1 for 1)) = upper(cLetter)
group by tc.entityid, qs.phrase
order by qs.phrase
loop
sXML := sXML || '<company id="' || rcd_company.entityid || '" entityid="' || rcd_company.entityid || '" count="' || rcd_company.count || '"><rss:title><![CDATA[' || uxml_escapefor_cdata(rcd_company.name) || '</rss:title></company>';
end loop;
sXML := sXML || '</companies>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_company_search
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sTerm alias for $4;
begin
return '</root>';
end;
-
ppp_easyethical_conference_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
begin
sXML := '<root><people>';
--Annesley
sXML := sXML || '<person>
<name><![CDATA[Annesley Newholm</name>
<location><![CDATA[London, UK</location>
<areas>
<area><![CDATA[Technical</area>
</areas>
<skype><![CDATA[anewholm</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-1-easyethical/</podcast>
<email><![CDATA[annesley.newholm@gmail.com</email>
<website><![CDATA[EasyEthical.org</website>
</person>';
--Jonathan
sXML := sXML || '<person>
<name><![CDATA[Jonathan Melhuish</name>
<location><![CDATA[London, UK</location>
<areas>
<area><![CDATA[Concepts</area>
<area><![CDATA[Artificial Intelligence</area>
</areas>
<skype><![CDATA[orangejon</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-1-easyethical/</podcast>
<email><![CDATA[mail@orangejon.com</email>
<website><![CDATA[EasyEthical.org</website>
</person>';
--Terry
sXML := sXML || '<person>
<name><![CDATA[Terry Newholm</name>
<location><![CDATA[London, UK</location>
<areas>
<area><![CDATA[Consumer Theory</area>
</areas>
<skype><![CDATA[anewholm</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-3-terry-newholm/</podcast>
<email><![CDATA[annesley.newholm@gmail.com</email>
<website><![CDATA[EasyEthical.org</website>
</person>';
--Wesa
sXML := sXML || '<person>
<name><![CDATA[Wesa Aapro</name>
<location><![CDATA[Finland</location>
<areas>
<area><![CDATA[Technical</area>
<area><![CDATA[Data design</area>
</areas>
<skype><![CDATA[kaveri2</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-2-consumer-gadget/</podcast>
<email><![CDATA[wesa.aapro@gmail.com</email>
<website><![CDATA[consumergadget.org</website>
</person>';
--Clay
sXML := sXML || '<person>
<name><![CDATA[Clay Ward</name>
<location><![CDATA[Boston, US</location>
<areas>
<area><![CDATA[Technical</area>
<area><![CDATA[Data design</area>
</areas>
<skype><![CDATA[cwallardo</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/12/interview-7-buy-it-like-you-mean-it/</podcast>
<email><![CDATA[clay@bilumi.org</email>
<website><![CDATA[bilumi.org</website>
</person>';
--B Dolan
sXML := sXML || '<person>
<name><![CDATA[B Dolan</name>
<location><![CDATA[New York, US</location>
<areas>
<area><![CDATA[Technical</area>
<area><![CDATA[Data design</area>
<area><![CDATA[Marketing</area>
</areas>
<email><![CDATA[beedolan@gmail.com</email>
<website><![CDATA[knowmore.org</website>
</person>';
--Stephane
sXML := sXML || '<person>
<name><![CDATA[Stephane de Messieres</name>
<location><![CDATA[US</location>
<areas>
<area><![CDATA[Data design</area>
</areas>
<skype><![CDATA[sdemessieres</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-6-stephane-de-messieres/</podcast>
<email><![CDATA[sdemessieres@citizensmarket.org</email>
<website><![CDATA[citizensmarket.org</website>
</person>';
--Oliver
sXML := sXML || '<person>
<name><![CDATA[Oliver</name>
<location><![CDATA[London, UK</location>
<areas>
</areas>
<skype><![CDATA[oliversylvester-bradley</skype>
<email><![CDATA[osb@defactodesign</email>
<website><![CDATA[Extraethical.com</website>
</person>';
--Nate
sXML := sXML || '<person>
<name><![CDATA[Nate Greenslit</name>
<location><![CDATA[USA</location>
<areas>
<area><![CDATA[Consumer theory</area>
</areas>
<skype><![CDATA[all.too.human</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-4-nate-greenslit/</podcast>
<email><![CDATA[npg@MIT.EDU</email>
<website><![CDATA[web.media.mit.edu/~npg/</website>
</person>';
--Rob
sXML := sXML || '<person>
<name><![CDATA[Rob Harrison</name>
<location><![CDATA[Manchester, UK</location>
<areas>
<area><![CDATA[Consumer theory</area>
</areas>
<skype><![CDATA[rob.harrison99</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/11/interview-5-ethical-consumer/</podcast>
<email><![CDATA[rob@ethicalconsumer.org</email>
<website><![CDATA[ethicalconsumer.org</website>
</person>';
--Ellis
sXML := sXML || '<person>
<name><![CDATA[Ellis Jones</name>
<location><![CDATA[California, USA</location>
<areas>
</areas>
<skype><![CDATA[sodoctorjones</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/12/interview-10-better-world-shopper/</podcast>
<email><![CDATA[so.doctor.jones@gmail.com</email>
<website><![CDATA[betterworldshopper.com</website>
</person>';
--Jake de Grazia
sXML := sXML || '<person>
<name><![CDATA[Jake De Grazia</name>
<location><![CDATA[USA</location>
<areas>
</areas>
<skype><![CDATA[jdegrazia</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/12/interview-9-carrotproject/</podcast>
<email><![CDATA[jdegrazia@gmail.com</email>
<website><![CDATA[moreperfectmarket.com</website>
</person>';
--George Polisner
sXML := sXML || '<person>
<name><![CDATA[George Polisner</name>
<location><![CDATA[USA</location>
<areas>
</areas>
<skype><![CDATA[gpolisne</skype>
<email><![CDATA[george.polisner@alonovo.com</email>
<website><![CDATA[alonovo.com</website>
</person>';
--Dara O'Rourke
sXML := sXML || '<person>
<name><![CDATA[Dara O''Rourke</name>
<location><![CDATA[USA</location>
<areas>
</areas>
<skype><![CDATA[daraorourke</skype>
<podcast><![CDATA[http://jonathanmelhuish.com/2008/12/interview-8-goodguide/</podcast>
<email><![CDATA[jodie@taoit.com</email>
<website><![CDATA[goodguide.com</website>
</person>';
--Dorethea Kliene
sXML := sXML || '<person>
<name><![CDATA[Dorethea Kliene</name>
<location><![CDATA[Reading, UK</location>
<areas>
</areas>
<skype><![CDATA[dorothea2150</skype>
<email><![CDATA[dorothea.kleine@rhul.ac.uk</email>
<website><![CDATA[www.gg.rhul.ac.uk/Kleine/index.html</website>
</person>';
--GBenga Kogbe
sXML := sXML || '<person>
<name><![CDATA[GBenga Kogbe</name>
<location><![CDATA[London, UK</location>
<areas>
<area><![CDATA[Commercialisation</area>
</areas>
<email><![CDATA[okogbe@gmail.com</email>
</person>';
--Al Tepper
sXML := sXML || '<person>
<name><![CDATA[Al Tepper</name>
<location><![CDATA[London, UK</location>
<areas>
</areas>
<podcast><![CDATA[http://jonathanmelhuish.com/2009/06/interview-12-al-tepper/</podcast>
<email><![CDATA[al@naturalcollection.com</email>
</person>';
--John Tepper Marlin
sXML := sXML || '<person>
<name><![CDATA[John Tepper Marlin</name>
<location><![CDATA[New York, USA</location>
<areas>
</areas>
<podcast><![CDATA[http://jonathanmelhuish.com/2009/01/interview-11-shopping-for-a-better-world/</podcast>
<website><![CDATA[www.shoppingforabetterworld.com/</website>
<email><![CDATA[jmarlin@stern.nyu.edu</email>
</person>';
sXML := sXML || '</people>
</root>';
return sXML;
end;
-
ppp_easyethical_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sEmailAddress alias for $4;
sSubject alias for $5;
sBody alias for $6;
sXML text;
sEmailAddressRequired text;
iUserId tuser.userid%TYPE;
sUserEmailAddress tuser.emailaddress%TYPE;
begin
sXML := '<root>';
--user details
iUserId := usession_userid(sSession);
if not iUserId is null then select into sUserEmailAddress emailaddress from tuser where userid = iUserId; end if;
sXML := sXML || '<form_requirements submit="send email" action="/docontactus">';
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sXML := sXML || '<emailaddress class="input_medium" required="' || sEmailAddressRequired || '" caption="from (email address)">
<value><![CDATA[</value>
<original><![CDATA[' || uxml_escapefor_cdata(coalesce(sUserEmailAddress, '')) || '</original>
</emailaddress>'; --optional
sXML := sXML || '<subject class="input_large">
<value><![CDATA[' || uxml_escapefor_cdata(sSubject) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sSubject) || '</original>
</subject>'; --optional
sXML := sXML || '<body type="textarea" class="textarea_medium">
<value><![CDATA[' || uxml_escapefor_cdata(sBody) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sBody) || '</original>
</body>'; --optional
sXML := sXML || '</form_requirements>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_developer_blog_all
()
select '<root>' || uxml_blogpost($1, $2, $3, 1, $4) || '</root>';
-
ppp_easyethical_developer_blog_index
()
select '<root>
<rss:feed>
<rss:details>
<rss:title><![CDATA[' || uxml_escapefor_cdata(name) || '</rss:title>
<rss:description><![CDATA[' || uxml_escapefor_cdata(description) || '</rss:description>
<rss:relativelinkroot><![CDATA[/developer/blog/</rss:relativelinkroot>
</rss:details>
<rss:items>
<posts>' || uxml_blogtitles($1, $2, $3, 1, blogcategoryid) || '</posts>
</rss:items>
</rss:feed>
</root>'
from tblogcategory where blogcategoryid = 2;
-
ppp_easyethical_developer_database
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
sTableName text;
sLastTableName text;
rcd record;
begin
sXML := '<root>';
--######################################## tables ########################################
sXML := sXML || '<tables>';
for rcd in select pc.oid, pc.relname, pa.attnum as order, pa.attname, pa.atttypid, pa.attlen, pa.attnotnull
from pg_class pc
inner join pg_attribute pa on pa.attrelid = pc.oid
where pc.relnamespace = 2200 and pc.relkind = 'r' and pa.attstattarget = -1
order by pc.relname, pa.attname
loop
sTableName := rcd.relname;
if not sTableName = sLastTableName or sLastTableName is null then
if not sLastTableName is null then sXML := sXML || '</columns></table>'; end if;
sXML := sXML || '<table id="' || rcd.oid || '"><name><![CDATA[' || uxml_escapefor_cdata(rcd.relname) || '</name><columns>';
sLastTableName := sTableName;
end if;
sXML := sXML || '<column order="' || coalesce(rcd.order, 0) || '" type="' || coalesce(rcd.atttypid, 0) || '" len="' || coalesce(rcd.attlen, 0) || '" notnull="' || coalesce(rcd.attnotnull, false) || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.attname) || '</name>
</column>';
end loop;
sXML := sXML || '</columns></table></tables>';
--######################################## procs ########################################
sXML := sXML || '<procs>';
sXML := sXML || '<ppp>
<type>public xml - xsl - website system procedures</type>
<description>These procs generate the XML for their related XSL webpages with the same path</description>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 1 for 4) = 'ppp_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</ppp>';
sXML := sXML || '<padd>
<type>public and private procs that allow external apps to add content into the system</type>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 2 for 4) = 'add_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</padd>';
sXML := sXML || '<uxml>
<type>private procs that assemble XML for an object in the system</type>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 1 for 5) = 'uxml_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</uxml>';
sXML := sXML || '<uexists>
<type>internal checking to see if an item already exists</type>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 1 for 8) = 'uexists_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</uexists>';
sXML := sXML || '<unormalise>
<type>normalisation of strings</type>
<description>removal of extra whitespace, grammar or removal of common terms in object names</description>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 1 for 11) = 'unormalise_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</unormalise>';
sXML := sXML || '<usession>
<type>session handling</type>
<description>this system handles session in the database, not at the webserver level</description>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200 and substring(proname from 1 for 9) = 'usession_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</usession>';
sXML := sXML || '<other>
<type>misc</type>';
for rcd in select pp.oid, proname, description, proargtypes
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200
and not substring(proname from 1 for 9) = 'usession_'
and not substring(proname from 1 for 11) = 'unormalise_'
and not substring(proname from 1 for 4) = 'ppp_'
and not substring(proname from 2 for 4) = 'add_'
and not substring(proname from 1 for 5) = 'uxml_'
and not substring(proname from 1 for 8) = 'uexists_'
order by proname
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
</proc>';
end loop;
sXML := sXML || '</other>';
sXML := sXML || '</procs>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_developer_fullschema
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
sTableName text;
sLastTableName text;
rcd record;
begin
sXML := '<root>';
--######################################## tables ########################################
sXML := sXML || '<tables>';
for rcd in select pc.oid, pc.relname, pa.attnum as order, pa.attname, pa.atttypid, pa.attlen, pa.attnotnull
from pg_class pc
inner join pg_attribute pa on pa.attrelid = pc.oid
where pc.relnamespace = 2200 and pc.relkind = 'r' and pa.attstattarget = -1
order by pc.relname, pa.attname
loop
sTableName := rcd.relname;
if not sTableName = sLastTableName or sLastTableName is null then
if not sLastTableName is null then sXML := sXML || '</columns></table>'; end if;
sXML := sXML || '<table id="' || rcd.oid || '"><name><![CDATA[' || uxml_escapefor_cdata(rcd.relname) || '</name><columns>';
sLastTableName := sTableName;
end if;
sXML := sXML || '<column order="' || coalesce(rcd.order, 0) || '" type="' || coalesce(rcd.atttypid, 0) || '" len="' || coalesce(rcd.attlen, 0) || '" notnull="' || coalesce(rcd.attnotnull, false) || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.attname) || '</name>
</column>';
end loop;
sXML := sXML || '</columns></table></tables>';
--######################################## DRI ########################################
sXML := sXML || '<dri>';
for rcd in select pc.oid, pc.relname
from pg_class pc
where pc.relnamespace = 2200 and pc.relkind = 'i'
order by pc.relname
loop
sXML := sXML || '<item id="' || coalesce(rcd.oid, 0) || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.relname) || '</name>
</item>';
end loop;
sXML := sXML || '</dri>';
--######################################## procs ########################################
sXML := sXML || '<procs>';
for rcd in select pp.oid, proname, description, proargtypes, pronargs, prosrc
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pronamespace = 2200
order by proname, pronargs, proargtypes
loop
sXML := sXML || '<proc id="' || rcd.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.proname) || '</name>
<args>';
for i in 0..rcd.pronargs-1 loop
sXML := sXML || '<arg type="' || coalesce(rcd.proargtypes[i], 0) || '" />';
end loop;
sXML := sXML || '</args>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>
<src><![CDATA[' || uxml_escapefor_cdata(rcd.prosrc) || '</src>
</proc>';
end loop;
sXML := sXML || '</procs>';
--######################################## row counts ########################################
sXML := sXML || '<rowcounts>';
for rcd in select * from acounts() order by name
loop
sXML := sXML || '<table count="' || coalesce(rcd.count, 0) || '" min="' || coalesce(rcd.min, 0) || '" max="' || coalesce(rcd.max, 0) || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
</table>';
end loop;
sXML := sXML || '</rowcounts>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_developer_proc
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iOID alias for $4;
sXML text;
rcd record;
begin
select into sXML '<root><proc id="' || pp.oid || '">
<name><![CDATA[' || uxml_escapefor_cdata(proname) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(description) || '</description>
<src><![CDATA[' || uxml_escapefor_cdata(prosrc) || '</src>
</proc></root>'
from pg_proc pp
left outer join pg_description pd on pp.oid = pd.objoid
where pp.oid = iOID;
return sXML;
end;
-
ppp_easyethical_doadvancedsearch
(
25, 25, 23, 25, 25, 25, 25, 23, 25, 25, 25, 25, 25, 25, 25
)
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSearch1 alias for $4;
sSearch2 alias for $5;
sSearch3 alias for $6;
sBarcode alias for $7;
iBarcodeSearchResult alias for $8;
sBarcodeCompany alias for $9;
sBarcodeResultant alias for $10;
sBarcodeAddress alias for $11;
sBarcodeContact alias for $12;
sBarcodeEmail alias for $13;
sBarcodePhone alias for $14;
sBarcodeFax alias for $15;
sXML text;
rcd record;
begin
return ppp_easyethical_company_all(sSessionId, sSchema, iVersion, sBarcodeCompany, '', 0);
end;
-
ppp_easyethical_docontactus
(
25, 25, 23, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sFromEmail alias for $4;
sSubject alias for $5;
sHTMLBody alias for $6;
sSubmit alias for $7;
sXML text;
iUserId tuser.userid%TYPE;
begin
if not sSubmit = 'send email' then return '<error>form submission security failure</error>'; end if;
sXML := '<root>';
--return success
sXML := sXML || '<success/>';
iUserId := usession_userid(sSession);
if not iUserId is null then
sXML := sXML || uxml_user(iUserId);
end if;
--email
sXML := sXML || '<sendmail:email>
<sendmail:from><![CDATA[' || uxml_escapefor_cdata(sFromEmail) || '</sendmail:from>
<sendmail:subject><![CDATA[' || uxml_escapefor_cdata(sSubject) || '</sendmail:subject>
<sendmail:html>' || uxml_parsexml(sHTMLBody) || '</sendmail:html>
<sendmail:text>' || uxml_parsexmltotext(sHTMLBody) || '</sendmail:text>
</sendmail:email>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_dojoinemaillist
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sListID alias for $4;
sEmailAddress alias for $5;
iResult integer;
sXML text;
begin
sXML := '<root>';
--return success
sXML := sXML || '<success/>';
select into iResult uadd_to_emaillist(sListID, sEmailAddress);
--email to me
sXML := sXML || '<sendmail:email>
<sendmail:from><![CDATA[' || uxml_escapefor_cdata(sEmailAddress) || '</sendmail:from>
<sendmail:subject><![CDATA[' || uxml_escapefor_cdata(sListID) || '</sendmail:subject>
<sendmail:html>emaillist</sendmail:html>
<sendmail:text>emaillist</sendmail:text>
</sendmail:email>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
begin
return '<root/>';
end;
-
ppp_easyethical_rank_doaddarticle
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
iEntityId alias for $5;
sXML text;
iSessionId integer;
bAutoSaveEntities boolean;
bAutoSaveArticles boolean;
begin
sXML := '<root>';
iSessionId := usession_id(sSession);
select into bAutoSaveEntities, bAutoSaveArticles
autosaveentities, autosavearticles
from tsession where sessionid = iSessionId;
if not iArticleId = 0 and not exists (select * from tsession_briefcase where sessionid = iSessionId and articleid = iArticleId) then
--add article
insert into tsession_briefcase(sessionid, articleid, addsource) values(iSessionId, iArticleId, 'M');
--primary company
if not iEntityId = 0 then
update tsession_entity set addsource = 'P' where sessionid = iSessionId and entityid = iEntityId;
if not found then
insert into tsession_entity(sessionid, entityid, addsource) values(iSessionId, iEntityId, 'P');
end if;
end if;
--add related entity(s) from article
if bAutoSaveEntities then
insert into tsession_entity(sessionid, entityid, addsource)
select iSessionId, ea.entityid, 'R'
from tentity_article ea
where ea.articleid = iArticleId
and not exists (select * from tsession_entity se where se.sessionid = iSessionId and se.entityid = ea.entityid);
end if;
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_rank_doremovearticle
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iArticleId alias for $4;
sXML text;
iSessionId integer;
begin
sXML := '<root>';
iSessionId := usession_id(sSession);
delete from tsession_briefcase where sessionid = iSessionId and articleid = iArticleId;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_rank_doremoveentity
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iEntityId alias for $4;
sXML text;
iSessionId integer;
begin
sXML := '<root>';
iSessionId := usession_id(sSession);
delete from tsession_entity where sessionid = iSessionId and entityid = iEntityId;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_rank_dosaveoptions
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
bAutoSaveArticles alias for $4;
bAutoSaveEntities alias for $5;
sXML text;
iSessionId integer;
begin
sXML := '<root>';
iSessionId := usession_id(sSession);
update tsession set autosaveentities = bAutoSaveEntities, autosavearticles = bAutoSaveArticles where sessionid = iSessionId;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_rank_index
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sForceSession alias for $4;
sXML text;
iSessionId tsession.sessionid%TYPE;
iEntityId tentity.entityid%TYPE;
rcd record;
rcda record;
s45 text;
sFirstPara text;
bTruncated boolean;
begin
if sForceSession = '' then iSessionId := usession_id(sSession); else iSessionId := usession_id(sForceSession); end if;
sXML := '<root>';
--companies that have appeared in the documents that the user has read about
sXML := sXML || '<entities>';
for rcd in select se.entityid, se.rank as companyrank, se.addsource, se.touched,
qs.phrase as name,
vkr.count, vkr.groupcount, vkr.rank as knowledgerank
from tsession ts
inner join tsession_entity se on ts.sessionid = se.sessionid
inner join tentity e on se.entityid = e.entityid
inner join tlcompany tc on e.entityid = tc.entityid
inner join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
left outer join vknowledge_rank vkr on e.entityid = vkr.entityid and vkr.userid = ts.userid
where se.sessionid = iSessionId
order by se.addsource, se.rank asc
loop
iEntityId := rcd.entityid;
sXML := sXML || '<company
id="' || iEntityId || '"
rank="' || rcd.companyrank || '"
addsource="' || rcd.addsource || '"
touched="' || rcd.touched || '"
>';
sXML := sXML || '<knowledge count="' || coalesce(rcd.count, 0) || '" groupcount="' || coalesce(rcd.groupcount, 0) || '" rank="' || coalesce(rcd.knowledgerank, 0) || '"/>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>';
--the articles read wrt this entity
sXML := sXML || '<articles>';
for rcda in select ta.articleid, ta.title, ta.body,
(select body from tsummary ts where ts.articleid = ta.articleid
order by summaryid desc
limit 1
) as summary
from tsession_briefcase sb
inner join tarticle ta on sb.articleid = ta.articleid
inner join tentity_article ea on ta.articleid = ea.articleid
where sb.sessionid = iSessionId
and ea.entityid = iEntityId
loop
sXML := sXML || '<article id="' || rcda.articleid || '">
<title><![CDATA[' || uxml_escapefor_cdata(rcda.title) || '</title>';
--choose an appropriate summary
if not rcda.summary is null then
--first summary
--s45 := ufirst200words(rcda.summary);
s45 := rcda.summary;
if not (s45 is null or char_length(s45) = 0) then
bTruncated := not (s45 = rcda.summary);
--sXML := sXML || '<summary truncated="' || bTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</summary>';
sXML := sXML || '<summary truncated="' || bTruncated || '">' || s45 || '</summary>';
end if;
else
--first paragraph
sFirstPara := ufirstpara(rcda.body);
s45 := ufirst45words(sFirstPara);
if not (s45 is null or char_length(s45) = 0) then
bTruncated := not (s45 = sFirstPara);
sXML := sXML || '<summary truncated="' || bTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</summary>';
end if;
end if;
sXML := sXML || '</article>';
end loop;
sXML := sXML || '</articles></company>';
end loop;
sXML := sXML || '</entities>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_session
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSiteroot alias for $4;
sUserAgent alias for $5;
iSessionId integer;
iUserId integer;
sXML text;
bExists boolean;
begin
bExists := usession_exists(sSessionId);
iSessionId := usession_autocreate(sSessionId, sSiteroot, sUserAgent); --will auto-create linked to the domain if necessary
select into sXML '<session
id="' || sessionid || '"
string="' || sessionstring || '"
new="' || (not bExists) || '"
autosaveentities="' || autosaveentities || '"
autosavearticles="' || autosavearticles || '">'
from tsession where sessionid = iSessionId;
sXML := sXML || '<authentication>';
iUserId := usession_userid(sSessionId);
if iUserId is null then
sXML := sXML || '<nouser/>';
else
sXML := sXML || uxml_user(iUserId);
end if;
sXML := sXML || '</authentication>';
sXML:= sXML || '</session>';
return sXML;
end;
-
ppp_easyethical_source_all
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSource alias for $4; --this may be an id if it is numeric (entirely)
iLimitDocs alias for $5;
iLimitDocsR integer;
sXML text;
iCount integer;
iSourceId texternalsource.externalsourceid%TYPE;
rcd record;
begin
sXML := '<root>';
--figure out the name of the source, may be an id
if sSource ~ '^[0-9]+$' then
select into iCount, iSourceId 1, tx.externalsourceid
from texternalsource tx
where tx.externalsourceid = sSource;
if iCount is null then iCount := 0; end if; --not a valid source id
else
select into iCount, iSourceId distinct count(distinct uexists_externalsource), min(tx.externalsourceid)
from uexists_externalsource(sSource)
inner join texternalsource tx on tx.externalsourceid = uexists_externalsource;
end if;
--if there is only one then directly return information for that one
if iCount = 0 then
--no results
sXML := sXML || '<notfound/>';
elsif iCount = 1 then
--search resolves to exactly one company so return its summary details
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
sXML := sXML || uxml_externalsource(sSessionId, sSchema, iVersion, iSourceId, iLimitDocsR);
else
--search could be any one of a number of companies
sXML := sXML || '<manyfound>';
for rcd in select tx.externalsourceid, tx.rootpagetitle, tx.domain,
(select count(*) from tarticle where externalsourceid = tx.externalsourceid) as articlecount
from texternalsource tx
inner join uexists_externalsource(sSource) on tx.externalsourceid = uexists_externalsource
order by tx.rootpagetitle
loop
sXML := sXML || '<externalsource id="' || rcd.externalsourceid || '"
articlecount="' || rcd.articlecount || '"
>
<rootpagetitle><![CDATA[' || uxml_escapefor_cdata(rcd.rootpagetitle) || '</rootpagetitle>
<domain><![CDATA[' || uxml_escapefor_cdata(rcd.domain) || '</domain>
</externalsource>';
end loop;
sXML := sXML || '</manyfound>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_source_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
cLetter alias for $4;
iTopCompanies alias for $5;
iTopCompaniesLimit integer;
sXML text;
rcd_letter record;
rcd_company record;
begin
sXML := '<root>';
if cLetter = '' then
--------------------------------------------------------------------------- all letters ---------------------------------------------------------------------------
if iTopCompanies = 0 then
iTopCompaniesLimit = 100;
else
iTopCompaniesLimit = iTopCompanies;
end if;
--lettgroups 0,1,2,3,a,b,c,d,e,...
sXML := sXML || '<letters>';
for rcd_letter in select distinct upper(substring(rootpagetitle from 1 for 1)) as letter
from texternalsource tc
order by upper(substring(rootpagetitle from 1 for 1))
loop
sXML := sXML || '<letter><![CDATA[' || uxml_escapefor_cdata(rcd_letter.letter) || '</letter>';
end loop;
sXML := sXML || '</letters>';
--sources
sXML := sXML || '<rss:feed><rss:details>
<rss:title><![CDATA[sources</rss:title>
<rss:description><![CDATA[sources</rss:description>
<rss:relativelinkroot><![CDATA[/source/</rss:relativelinkroot>
</rss:details>
<rss:items>
<sources>';
for rcd_company in select tc.externalsourceid, domain, rootpagetitle, count(*) as count
from texternalsource tc
inner join tarticle tae on tc.externalsourceid = tae.externalsourceid
group by tc.externalsourceid, domain, rootpagetitle
order by count(*) desc
limit iTopCompaniesLimit
loop
sXML := sXML || '<source id="' || rcd_company.externalsourceid || '" count="' || rcd_company.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd_company.rootpagetitle) || '</rss:title>
<domain><![CDATA[' || uxml_escapefor_cdata(rcd_company.domain) || '</domain>
<rss:description><![CDATA[' || rcd_company.count || ' articles from this source</rss:description>
</source>';
end loop;
sXML := sXML || '</sources></rss:items></rss:feed>';
else
--------------------------------------------------------------------------- one letter ---------------------------------------------------------------------------
sXML := sXML || '<letter><![CDATA[' || uxml_escapefor_cdata(upper(cLetter)) || '</letter>';
sXML := sXML || '<sources>';
for rcd_company in select tc.externalsourceid, domain, rootpagetitle, count(*) as count
from texternalsource tc
inner join tarticle tae on tc.externalsourceid = tae.externalsourceid
where upper(substring(rootpagetitle from 1 for 1)) = upper(cLetter)
group by tc.externalsourceid, domain, rootpagetitle
order by rootpagetitle
loop
sXML := sXML || '<source id="' || rcd_company.externalsourceid || '" count="' || rcd_company.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd_company.rootpagetitle) || '</rss:title>
<domain><![CDATA[' || uxml_escapefor_cdata(rcd_company.domain) || '</domain>
</source>';
end loop;
sXML := sXML || '</sources>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_taggroup_all
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sTagGroup alias for $4; --this may be an id if it is numeric (entirely)
iTagGroupId integer;
iCount integer;
sXML text;
rcd record;
begin
sXML := '<root>';
--figure out the name of the source, may be an id
if sTagGroup ~ '^[0-9]+$' then
select into iCount, iTagGroupId 1, tg.taggroupid
from ttaggroup tg
where tg.taggroupid = sTagGroup;
if iCount is null then iCount := 0; end if; --not a valid source id
else
select into iCount, iTagGroupId distinct count(distinct uexists_taggroup), min(tg.taggroupid)
from uexists_taggroup(sTagGroup)
inner join ttaggroup tg on tg.taggroupid = uexists_taggroup;
end if;
--if there is only one then directly return information for that one
if iCount = 0 then
--no results
sXML := sXML || '<notfound/>';
elsif iCount = 1 then
--search resolves to exactly one company so return its summary details
sXML := sXML || uxml_taggroup(sSessionId, sSchema, iVersion, iTagGroupId);
else
--search could be any one of a number of companies
sXML := sXML || '<manyfound>';
for rcd in select tg.taggroupid, tg.tag, count(*) as articlecount,
from tarticle_tag tat
inner join ttag tt on tat.tagid = tt.tagid
inner join ttaggroup tg on tt.taggroupid = tg.taggroupid
inner join uexists_taggroup(sTagGroup) on tg.taggroupid = uexists_taggroup
group by tg.taggroupid, tg.tag
order by tg.tag
loop
sXML := sXML || '<taggroup id="' || rcd.taggroupid || '"
articlecount="' || rcd.articlecount || '"
>
<tag><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</tag>
</taggroup>';
end loop;
sXML := sXML || '</manyfound>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_easyethical_taggroup_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
begin
sXML := '<root><taggroups>';
for rcd in select tg.taggroupid, tg.tag, count(*)
from tarticle_tag tat
inner join ttag tt on tat.tagid = tt.tagid
inner join ttaggroup tg on tt.taggroupid = tg.taggroupid
group by tg.taggroupid, tg.tag
order by count(*) desc
loop
sXML := sXML || '<taggroup id="' || rcd.taggroupid || '" count="' || rcd.count || '">
<rss:title><![CDATA[' || rcd.tag || '</rss:title>
</taggroup>';
end loop;
sXML := sXML || '</taggroups></root>';
return sXML;
end;
-
ppp_societycard_account_login
()
select ppp_easyethical_account_login($1, $2, $3, $4, $5, $6)
-
ppp_societycard_account_loginas
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sUserId alias for $4;
begin
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator to print vouchers</security_denied></root>'; end if;
update tsession set userid = sUserId::integer where sessionstring = sSession;
return '<root/>';
end;
-
ppp_societycard_account_logout
()
select ppp_easyethical_account_logout($1, $2, $3)
-
ppp_societycard_account_movedbusiness
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sEntityId alias for $4;
sLat alias for $5;
sLng alias for $6;
iUserId tuser.userid%TYPE;
begin
iUserId := usession_userid(sSession);
if usession_isadmin(sSession) or exists(
select * from tuser tu
inner join tlcompany tc on tu.businessownerid = tc.companyid
where tu.userid = iUserId and tc.entityid = sEntityId::integer
) then
update tentity set latitude = sLat::float, longitude = sLng::float where entityid = sEntityId::integer;
end if;
return '<root><business id="' || sEntityId || '"/></root>';
end;
-
ppp_societycard_account_movedhouse
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sLat alias for $4;
sLng alias for $5;
begin
update tuser set latitude = sLat::float, longitude = sLng::float where userid = usession_userid(sSession);
return '<root/>';
end;
-
ppp_societycard_account_verify
()
select ppp_easyethical_account_verify($1, $2, $3, $4)
-
ppp_societycard_admin_businesses
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sContracts alias for $4;
aContracts text[];
bHasContract boolean;
sXML text;
rcd record;
rcd_com record;
iCompanyId integer;
begin
sXML := '<root>';
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator</security_denied></root>'; end if;
aContracts := sContracts;
--businesses
sXML := sXML || '<businesses>';
for rcd in select tc.companyid, te.entityid, te.subtype, qs.phrase, te.longitude, te.latitude, te.location, tc.voucherbookid, tu.userid, vi.*, tc.businesstypequalifier, tc.website, te.createdate,
(
select pc.name from tcompany_producttype cpt
inner join tproducttype_producttype_category ppc on cpt.producttypeid = ppc.producttypeid
inner join tlproducttype_category pc on ppc.producttype_categoryid = pc.producttype_categoryid
where cpt.companyid = tc.companyid
limit 1
) as tlc, tc.icon,
tu.flickr_photoid, tu.youtube_videoid,
tu.message_short, tu.message_medium, tu.message_long,
tu.emailaddress
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
inner join tuser tu on tc.companyid = tu.businessownerid
inner join vinvestmentprogress vi on tc.companyid = vi.companyid
where exists (select * from tcommitment where companyid = tc.companyid)
--or exists (select * from tinvestement where companyid = tc.companyid)
order by qs.phrase
loop
iCompanyId := rcd.companyid;
--contract?
bHasContract := false;
for i in 0..array_upper(aContracts, 1) loop
if aContracts[i] = rcd.phrase || '.pdf' then bHasContract := true; end if;
end loop;
sXML := sXML || '<business id="' || rcd.entityid || '" companyid="' || iCompanyId || '" userid="' || rcd.userid|| '" voucherbookid="' || coalesce(rcd.voucherbookid, 0) || '" subtype="' || coalesce(rcd.subtype, '') || '" contract="' || bHasContract || '">
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</createdate>
<businesstypequalifier><![CDATA[' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</businesstypequalifier>';
if not rcd.tlc is null then sXML := sXML || '<tlc><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.tlc, '')) || '</tlc>'; end if;
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
if not rcd.youtube_videoid is null and not rcd.youtube_videoid = '' then
sXML := sXML || '<video><![CDATA[' || uxml_escapefor_cdata(rcd.youtube_videoid) || '</video>';
end if;
if not rcd.flickr_photoid is null and not rcd.flickr_photoid = '{}' then
sXML := sXML || '<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[4]) || '</secret>
</photo>';
end if;
if not rcd.website is null and not rcd.website = '' then sXML := sXML || '<website><![CDATA[' || uxml_escapefor_cdata(rcd.website) || '</website>'; end if; --don't include node if not available
sXML := sXML || '<point latitude="' || rcd.latitude || '" longitude="' || rcd.longitude || '"><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</point>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
sXML := sXML || '<emailaddress><![CDATA[' || uxml_escapefor_cdata(rcd.emailaddress) || '</emailaddress>';
sXML := sXML || '<messages>'
|| coalesce('<short>' || uxml_parsexml(rcd.message_short) || '</short>', '')
|| coalesce('<medium>' || uxml_parsexml(rcd.message_medium) || '</medium>', '')
|| coalesce('<long>' || uxml_parsexml(rcd.message_long) || '</long>', '')
|| '</messages>';
--progress
sXML := sXML || '<progress target="' || rcd.target || '" startdate="' || rcd.startdate || '" invested="' || rcd.invested || '" recieved="' || rcd.recieved || '"/>';
--commitments
sXML := sXML || '<commitments>';
for rcd_com in select * from tcommitment com
where companyid = iCompanyId
order by commitmentid desc --latest first
loop
sXML := sXML ||
'<commitment id="' || rcd_com.commitmentid || '" percentage="' || rcd_com.percentage || '" target="' || coalesce(rcd_com.target, 0) || '">
<![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd_com.specific, '\n\r', ' ')), '') || '
</commitment>';
end loop;
sXML := sXML || '</commitments>';
--products and services
sXML := sXML || '<pnss>';
for rcd_com in select te.entityid, pt.producttypeid, qs.phrase, cpt."order", pt.icon
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where cpt.companyid = iCompanyId
order by cpt.createdate
loop
sXML := sXML || '<pns id="' || rcd_com.entityid || '" producttypeid="' || rcd_com.producttypeid || '" order="' || rcd_com.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.phrase) || '</name>';
if not rcd_com.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</pns>';
end loop;
sXML := sXML || '</pnss>';
sXML := sXML || '</business>';
end loop;
sXML := sXML || '</businesses>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_admin_users
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSystem alias for $4;
sEmailAddress alias for $5;
sSubmit alias for $6;
sXML text;
bSubmission boolean;
sSystemToUse char(2);
rcd record;
begin
sXML := '<root>';
bSubmission := not sSubmit = '';
if sSystem = '' then sSystemToUse = 'SC'; else sSystemToUse = sSystem; end if;
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator for this screen</security_denied></root>'; end if;
--user management
if bSubmission then
if sSubmit = 'delete user' then delete from tuser where emailaddress = sEmailAddress; end if;
if sSubmit = 'delete subscriber' then delete from temaillist where emailaddress = sEmailAddress and listid = sSystemToUse; end if;
end if;
--users
sXML := sXML || '<users>';
for rcd in select tu.userid, tu.firstname, tu.middlename, tu.lastname, tu.username, tu.emailaddress, tu.createdate, tu.verified,
tu.lastlogin, tu.businessownerid
from tuser tu
where system = sSystemToUse and not type9c = 'BUS'
order by tu.username
loop
sXML := sXML || '<user id="' || rcd.userid || '" businessownerid="' || coalesce(rcd.businessownerid, 0) || '">
<firstname><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.firstname, '')) || '</firstname>
<middlename><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.middlename, '')) || '</middlename>
<lastname><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.lastname, '')) || '</lastname>
<username><![CDATA[' || uxml_escapefor_cdata(rcd.username) || '</username>
<emailaddress verified="' || rcd.verified || '"><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.emailaddress, '')) || '</emailaddress>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</createdate>
<lastlogin><![CDATA[' || uxml_escapefor_cdata(coalesce(uformatdate(rcd.lastlogin, 1), '')) || '</lastlogin>
</user>';
end loop;
sXML := sXML || '</users>';
--emaillist
sXML := sXML || '<emaillist>';
for rcd in select el.emailaddress, el.name, el.notes, el.bounce, el.networking, el.area, el.source, el.createdate
from temaillist el
where listid = sSystemToUse
order by el.emailaddress
loop
sXML := sXML || '<subscriber bounce="' || rcd.bounce || '" networking="' || rcd.networking || '">
<emailaddress><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.emailaddress, '')) || '</emailaddress>
<name><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.name, '')) || '</name>
<source><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.source, '')) || '</source>
<area><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.area, '')) || '</area>
<notes><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.notes, '')) || '</notes>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</createdate>
</subscriber>';
end loop;
sXML := sXML || '</emaillist>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_admin_voucherbook
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sVoucherBookId alias for $4;
sVoucherId alias for $5;
sSubmit alias for $6;
bSubmission boolean;
sXML text;
rcd record;
begin
sXML := '<root>';
bSubmission := not sSubmit = '';
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator</security_denied></root>'; end if;
--voucher redemption
if bSubmission then
insert into ttransaction(transactionid) values(default);
insert into ttransaction_voucher(transactionid, voucherid) values(currval('seqtransactionid'), sVoucherId::integer);
end if;
--get vouchers
sXML := sXML || '<voucherbook>';
for rcd in select v.voucherid, v.value, v.code, not tv.voucherid is null as redeemed
from tvoucher v
left outer join ttransaction_voucher tv on tv.voucherid = v.voucherid
where v.voucherbookid = sVoucherBookId
order by v.voucherid
loop
sXML := sXML || '<voucher id="' || rcd.voucherid || '" redeemed="' || rcd.redeemed || '" value="' || rcd.value || '" code="' || rcd.code || '" />';
end loop;
sXML := sXML || '</voucherbook>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_admin_voucherbooks
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
begin
sXML := '<root>';
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator</security_denied></root>'; end if;
--get vouchers
for rcd in select vb.voucherbookid, vb.createdate, vb.notes, tc.companyid, te.entityid, qs.phrase,
count(v.voucherid) as vouchers_count, count(tv.voucherid) as vouchers_claimed,
sum(value) as voucherbook_value
from tvoucherbook vb
left outer join tvoucher v on vb.voucherbookid = v.voucherbookid
left outer join ttransaction_voucher tv on tv.voucherid = v.voucherid
left outer join tlcompany tc on vb.voucherbookid = tc.voucherbookid
left outer join tentity te on tc.entityid = te.entityid
left outer join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
group by vb.voucherbookid, vb.createdate, vb.notes, tc.companyid, te.entityid, qs.phrase
order by qs.phrase desc, vb.voucherbookid asc
loop
sXML := sXML || '<voucherbook id="' || rcd.voucherbookid || '" vouchers_count="' || rcd.vouchers_count || '" vouchers_claimed="' || rcd.vouchers_claimed || '"
voucherbook_value="' || coalesce(rcd.voucherbook_value, 0) || '" createdate="' || uformatdate(rcd.createdate, 2) || '">
<notes><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.notes, '')) || '</notes>';
if not rcd.companyid is null then sXML := sXML || '
<business id="' || coalesce(rcd.entityid, 0) || '" companyid="' || coalesce(rcd.companyid, 0) || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>
</business>';
end if;
sXML := sXML || '</voucherbook>';
end loop;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_adviser_account_register
(
25, 25, 23, 16, 25, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_societycard_includes_register($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, 'ADV', $25);
-
ppp_societycard_adviser_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_societycard_business_account_index
(
25, 25, 23, 23, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 16, 16, 16, 16, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iGoogleStatus alias for $4;
iPointCount alias for $5;
sFirstPoint alias for $6;
sflickr_name alias for $7;
sflickr_password alias for $8;
sflickr_set alias for $9;
sflickr_photoid alias for $10;
syoutube_name alias for $11;
syoutube_password alias for $12;
syoutube_playlist alias for $13;
syoutube_videoid alias for $14;
smessage_short alias for $15;
smessage_medium alias for $16;
smessage_long alias for $17;
bSyncWithTwitter alias for $18;
bSyncWithFacebook alias for $19;
bAllowFollowers alias for $20;
bPublicStatus alias for $21;
sAvatar alias for $22;
sArea alias for $23;
sLocationDetails alias for $24;
sSubmit alias for $25;
--geo
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
sLocation tuser.location%TYPE;
--original values
sOriginalflickr_name tuser.flickr_name%TYPE;
sOriginalflickr_password tuser.flickr_password%TYPE;
sOriginalflickr_set tuser.flickr_set%TYPE;
sOriginalflickr_photoid text;
sOriginalyoutube_name tuser.youtube_name%TYPE;
sOriginalyoutube_password tuser.youtube_password%TYPE;
sOriginalyoutube_playlist tuser.youtube_playlist%TYPE;
sOriginalyoutube_videoid tuser.youtube_videoid%TYPE;
sOriginalmessage_short tuser.message_short%TYPE;
sOriginalmessage_medium tuser.message_medium%TYPE;
sOriginalmessage_long tuser.message_long%TYPE;
/*
bSyncWithTwitter tuser.SyncWithTwitter%TYPE;
bSyncWithFacebook tuser.SyncWithTwitter%TYPE;
bAllowFollowers tuser.SyncWithTwitter%TYPE;
bPublicStatus tuser.SyncWithTwitter%TYPE;
*/
sOriginalAvatar tuser.avatar%TYPE;
sOriginalArea tuser.area%TYPE;
sOriginalLocation tuser.location%TYPE;
bSubmission boolean;
bOk boolean;
sEmailAddressRequired text;
sFinalLocationDetails text;
sflickr_photoid_resultant text[];
sXML text;
sFormXML text;
sSuccessXML text;
iUserId tuser.userid%TYPE;
begin
iUserId := usession_userid(sSession);
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sFormXML := '';
sSuccessXML := '';
if iUserId is null then --we can only do this if we have a user
sXML := '<nouser/>';
else
--origonal values (update form)
select into sOriginalflickr_name, sOriginalflickr_password, sOriginalflickr_set, sOriginalflickr_photoid,
sOriginalyoutube_name, sOriginalyoutube_password, sOriginalyoutube_playlist, sOriginalyoutube_videoid,
sOriginalmessage_short, sOriginalmessage_medium, sOriginalmessage_long,
sOriginalAvatar, sOriginalArea, sOriginalLocation
flickr_name, flickr_password, flickr_set, flickr_photoid,
youtube_name, youtube_password, youtube_playlist, youtube_videoid,
message_short, message_medium, message_long,
avatar, area, location
from tuser where userid = iUserId;
sFormXML := '<form_requirements submission="' || bSubmission || '">';
--picture, video and message settings
--Flickr
sFormXML := sFormXML || '<flickr_name default="[flickr account]">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sflickr_name else sOriginalflickr_name end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalflickr_name) || '</original>
</flickr_name>';
sFormXML := sFormXML || '<flickr_password default="[flickr password]" hide4now="1">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sflickr_password else sOriginalflickr_password end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalflickr_password) || '</original>
</flickr_password>';
sFormXML := sFormXML || '<flickr_set default="[flickr set name]" hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sflickr_set else sOriginalflickr_set end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalflickr_set) || '</original>
</flickr_set>';
sFormXML := sFormXML || '<flickr_photoid default="[flickr photo id]">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sflickr_photoid else sOriginalflickr_photoid end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalflickr_photoid) || '</original>
</flickr_photoid>';
if sflickr_photoid = '' then sflickr_photoid_resultant = null;
else sflickr_photoid_resultant = array_fromtext(sflickr_photoid); end if;
--YouTube
sFormXML := sFormXML || '<youtube_name default="[youtube account]">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then syoutube_name else sOriginalyoutube_name end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalyoutube_name) || '</original>
</youtube_name>';
sFormXML := sFormXML || '<youtube_password default="[youtube password]" hide4now="1">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then syoutube_password else sOriginalyoutube_password end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalyoutube_password) || '</original>
</youtube_password>';
sFormXML := sFormXML || '<youtube_playlist default="[youtube playlist]" hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then syoutube_playlist else sOriginalyoutube_playlist end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalyoutube_playlist) || '</original>
</youtube_playlist>';
sFormXML := sFormXML || '<youtube_videoid default="[youtube video id]" help="the alphanumeric string in the URL of the video page">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then syoutube_videoid else sOriginalyoutube_videoid end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalyoutube_videoid) || '</original>
</youtube_videoid>';
--Messages
sFormXML := sFormXML || '<message_short help="one sentence, about 20 words" caption="one-liner">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then smessage_short else sOriginalmessage_short end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalmessage_short) || '</original>
</message_short>';
sFormXML := sFormXML || '<message_medium type="editor" class="textarea_medium" help="a paragraph, about 5 lines or 100 words" caption="short message">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then smessage_medium else sOriginalmessage_medium end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalmessage_medium) || '</original>
</message_medium>';
sFormXML := sFormXML || '<message_long type="editor" class="textarea_medium" help="a side of A4, a webpage, 6 paragraphs or so" caption="long message">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then smessage_long else sOriginalmessage_long end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalmessage_long) || '</original>
</message_long>';
--profile settings
sFormXML := sFormXML || '<syncwithtwitter>
<value><![CDATA[' || case bSubmission when true then bSyncWithTwitter else bSyncWithTwitter end || '</value>
<original><![CDATA[' || bSyncWithTwitter || '</original>
</syncwithtwitter>';
sFormXML := sFormXML || '<syncwithfacebook>
<value><![CDATA[' || case bSubmission when true then bSyncWithFacebook else bSyncWithFacebook end || '</value>
<original><![CDATA[' || bSyncWithFacebook || '</original>
</syncwithfacebook>';
sFormXML := sFormXML || '<allowfollowers>
<value><![CDATA[' || case bSubmission when true then bAllowFollowers else bAllowFollowers end || '</value>
<original><![CDATA[' || bAllowFollowers || '</original>
</allowfollowers>';
sFormXML := sFormXML || '<publicstatus>
<value><![CDATA[' || case bSubmission when true then bPublicStatus else bPublicStatus end || '</value>
<original><![CDATA[' || bPublicStatus || '</original>
</publicstatus>';
sFormXML := sFormXML || '<avatar>
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sAvatar else sOriginalAvatar end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalAvatar) || '</original>
</avatar>';
--geo (optional)
--user enters search location term in the area and then selects a location (2 part forced validation failure sequence)
sFormXML := sFormXML || '<area default="London, Greater London" help="examples: N22 6QP, Brixton, London, City road, Hyde Park (all locations postpended with UK)">
<value><![CDATA[' || uxml_escapefor_cdata(case bSubmission when true then sArea else sOriginalArea end) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalArea) || '</original>
</area>';
--if an area has been entered but a location is not selected then we have a validation issue
--if there is no area or location then the user has opted to not include it
sFormXML := sFormXML || '<location>
<value><![CDATA[' || uxml_escapefor_cdata(sLocationDetails) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalLocation) || '</original>';
if bSubmission then
sFinalLocationDetails := sLocationDetails;
if not (sArea = '') then --optional
if sLocationDetails = '' then
if iPointCount = 0 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[location not found</validation_error>'; end if;
if iPointCount = 1 then sFinalLocationDetails := sFirstPoint; end if;
if iPointCount > 1 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[please select a location</validation_error>'; end if;
end if;
end if;
end if;
sFormXML := sFormXML || '</location>';
sFormXML := sFormXML || '</form_requirements>';
end if;
if bSubmission and bOk then
sSuccessXML := '<success>';
--geo (optional)
if not sFinalLocationDetails is null and not sFinalLocationDetails = '' then
iLongitude := substring(sFinalLocationDetails from '[-.0-9]+');
iLatitude := substring(sFinalLocationDetails from '[-.0-9]+ *, *([-.0-9]+)');
sLocation := substring(sFinalLocationDetails from '[-.0-9]+ *, *[-.0-9]+ *, *0 (.*)');
update tuser set longitude = iLongitude,
latitude = iLatitude,
location = sLocation,
area = sLocation --store the location selected in the area
where userid = iUserId;
end if;
--update the account
update tuser set
flickr_name = sflickr_name,
flickr_password = sflickr_password,
flickr_set = sflickr_set,
flickr_photoid = sflickr_photoid_resultant,
youtube_name = syoutube_name,
youtube_password = syoutube_password,
youtube_playlist = syoutube_playlist,
youtube_videoid = syoutube_videoid,
message_short = smessage_short,
message_medium = smessage_medium,
message_long = smessage_long,
avatar = sAvatar
where userid = iUserId;
--return success (username and email unique already checked in this transaction)
sSuccessXML := sSuccessXML || uxml_user(iUserId);
sSuccessXML := sSuccessXML || '</success>';
end if;
sXML := '<root>' || sSuccessXML || sFormXML || '</root>';
return sXML;
end;
-
ppp_societycard_business_account_register
(
25, 25, 23, 16, 25, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_societycard_includes_register($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, 'BUS', $25);
-
ppp_societycard_business_addeditcommitment
(
25, 25, 23, 25, 25, 23, 23, 25, 25, 25, 23, 16, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sPurpose alias for $4;
sSpecificItem alias for $5;
iPercentageRevenue alias for $6;
iInitialInvestement alias for $7;
sStartDate alias for $8;
sEndDefinition alias for $9;
sEndDate alias for $10;
iTarget alias for $11;
bTermsAndConditions alias for $12;
sSubmit alias for $13;
bSubmission boolean;
bOk boolean;
dStartDate tcommitment.startdate%TYPE;
dEndDate tcommitment.enddate%TYPE;
iUserId tuser.userid%TYPE;
iCompanyId tlcompany.companyid%TYPE;
iCommitmentId tcommitment.commitmentid%TYPE;
sXML text;
sFormXML text;
sSuccessXML text;
--standard validation regex
sOptional text;
sEmailAddressRequired text;
sNumeric text;
sEmailAddressOptional text;
sTelephoneOptional text;
sNumericOptional text;
sDateOptional text;
sDate text;
begin
iUserId := usession_userid(sSession);
select into iCompanyId businessownerid from tuser where userid = iUserId; --the current logged in user must be a business owner
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sFormXML := '';
sSuccessXML := '';
--standard validation regex
sOptional := '^$|';
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sNumeric := '^[0-9]+$';
sDate := '^[0-9][0-9]/[a-zA-Z]{3}/[0-9]{4}$';
sEmailAddressOptional := sOptional || sEmailAddressRequired;
sTelephoneOptional := sOptional || '^[+]?[0-9 ()]+$';
sNumericOptional := sOptional || '^[0-9]+$';
sDateOptional := sOptional || sDate;
sFormXML := '<form_requirements submission="' || bSubmission || '">';
if bSubmission and iCompanyId is null then
bOk := false;
sFormXML := sFormXML || '<validation_error><![CDATA[not business owner or not logged in</validation_error>';
end if;
--######################################## form fields ##############################################
--with optional validation
--in order
--purpose
sFormXML := sFormXML || '<purpose type="radio" required="^[SR]$">';
sFormXML := sFormXML || '<options>
<option code="R">report</option>
<option code="S">specific</option>
</options>';
sFormXML := sFormXML || '<value><![CDATA[' || uxml_escapefor_cdata(sPurpose) || '</value>';
if bSubmission and not sPurpose ~ '^[SR]$' then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[purpose required</validation_error>'; end if;
sFormXML := sFormXML || '</purpose>';
--specific (required when purpose = specific)
sFormXML := sFormXML || '<specific default="[details of the specific item]">';
sFormXML := sFormXML || '<value><![CDATA[' || uxml_escapefor_cdata(sSpecificItem) || '</value>';
if bSubmission and sPurpose = 'S' and not sSpecificItem ~ '.+' then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[specific item details required</validation_error>'; end if;
sFormXML := sFormXML || '</specific>';
--percentage revenue
sFormXML := sFormXML || '<percentage required="^[0-9]+$">';
sFormXML := sFormXML || '<value><![CDATA[' || uxml_escapefor_cdata(iPercentageRevenue) || '</value>';
sFormXML := sFormXML || '</percentage>';
--initial investment
sFormXML := sFormXML || '<initial required="' || sNumericOptional || '">';
if not iInitialInvestement = 0 then sFormXML := sFormXML || '<value><![CDATA[' || uxml_escapefor_cdata(iInitialInvestement) || '</value>'; end if;
if bSubmission and not iInitialInvestement ~ sNumericOptional then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[initial investment needs to be just numbers or blank</validation_error>'; end if;
sFormXML := sFormXML || '</initial>';
--start date
sFormXML := sFormXML || '<startdate required="' || sDateOptional || '" caption="start date" type="date">
<value><![CDATA[' || sStartDate || '</value>';
if bSubmission then
if sStartDate = '' then
if sEndDefinition ~ 'F' then
bOk := false;
sFormXML := sFormXML || '<validation_error><![CDATA[start date required for flashmob commitment type</validation_error>';
else
dStartDate := now();
end if;
else
dStartDate := uto_timestamp(sStartDate || ' GMT', 'DD/Mon/YYYY');
if dStartDate is null then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[invalid start date</validation_error>'; end if;
end if;
end if;
sFormXML := sFormXML || '</startdate>';
--end definition (flashmob, end date, target)
sFormXML := sFormXML || '<end required="^[FET]$">';
sFormXML := sFormXML || '<value><![CDATA[' || uxml_escapefor_cdata(sEndDefinition) || '</value>';
if bSubmission and not sEndDefinition ~ '^[FET]$' then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[end definition required</validation_error>'; end if;
sFormXML := sFormXML || '</end>';
--end date
sFormXML := sFormXML || '<enddate required="' || sDateOptional || '" caption="end date" type="date">
<value><![CDATA[' || sEndDate || '</value>';
if bSubmission then
if sEndDefinition = 'F' then
dEndDate := dStartDate;
else
if sEndDate = '' then
if sEndDefinition = 'E' then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[end date required for end date type commitments</validation_error>'; end if;
else
dEndDate := uto_timestamp(sEndDate || ' GMT', 'DD/Mon/YYYY');
if dEndDate is null then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[invalid end date</validation_error>'; end if;
end if;
end if;
end if;
sFormXML := sFormXML || '</enddate>';
--target
sFormXML := sFormXML || '<target required="' || sNumericOptional || '">';
if not iTarget = 0 then sFormXML := sFormXML || '<value><![CDATA[' || iTarget || '</value>'; end if;
if bSubmission and sEndDefinition = 'T' then
if iTarget = 0 then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[numeric target required for target type commitments</validation_error>'; end if;
end if;
sFormXML := sFormXML || '</target>';
--tncs
sFormXML := sFormXML || '<termsandconditions required="' || bTermsAndConditions || '">
<value><![CDATA[' || bTermsAndConditions || '</value>';
if bSubmission and bTermsAndConditions = false then
bOk := false;
sFormXML := sFormXML || '<validation_error><![CDATA[you must agree to the terms and conditions</validation_error>';
end if;
sFormXML := sFormXML || '</termsandconditions>';
sFormXML := sFormXML || '</form_requirements>';
if bSubmission and bOk then
sSuccessXML := '<success>';
sFormXML := '';
--add the commitment
iCommitmentId := uadd_commitment(iCompanyId, sSpecificItem, iPercentageRevenue, iInitialInvestement, dStartDate, dEndDate, iTarget * 100);
sSuccessXML := sSuccessXML || uxml_commitment(sSession, sSchema, iVersion, iCommitmentId);
--return success (username and email unique already checked in this transaction)
sSuccessXML := sSuccessXML || '</success>';
end if;
sXML := '<root>' || sSuccessXML || sFormXML || '</root>';
return sXML;
end;
-
ppp_societycard_business_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_societycard_business_delete
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCompanyId alias for $4;
begin
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator for this screen</security_denied></root>'; end if;
delete from tentity where entityid = (
select entityid from tlcompany where companyid = sCompanyId
);
return '<root/>';
end;
-
ppp_societycard_business_managepns
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSubmit alias for $4;
sPnS alias for $5;
iUserId tuser.userid%TYPE;
iCompanyId tlcompany.companyid%TYPE;
bSubmission boolean;
bOk boolean;
sXML text;
aPnS integer[];
iLen integer;
i integer;
iPns tlproducttype.producttypeid%TYPE;
sName text;
sLetter char(1);
sLastletter char(1);
rcd record;
begin
iUserId := usession_userid(sSession);
select into iCompanyId businessownerid from tuser where userid = iUserId;
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sXML := '<root>';
--submission
if bSubmission then
aPns := '{' || sPnS || '}';
delete from tcompany_producttype where companyid = iCompanyId;
--place in according to the order in the array
iLen := array_upper(aPns, 1);
for i in 1..iLen loop
iPns := aPns[i];
insert into tcompany_producttype(companyid, producttypeid)
select iCompanyId, producttypeid
from tlproducttype
where producttypeid = iPns
and not exists(select * from tcompany_producttype where companyid = iCompanyId and producttypeid = iPns);
end loop;
/* cannot do this because looses the order
insert into tcompany_producttype(companyid, producttypeid)
select distinct iCompanyId, producttypeid from tlproducttype where anyof(producttypeid, aPns);
*/
end if;
--common product types
sXML := sXML || '<common>';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, sign(coalesce(max(cpt2.producttypeid), 0)) as selected, count(*), pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
left join tcompany_producttype cpt2 on pt.producttypeid = cpt2.producttypeid and cpt2.companyid = iCompanyId
group by pt.producttypeid, te.entityid, qs.phrase, pt.icon
order by count(*) desc
limit 20
loop
sName := rcd.phrase;
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '" selected="' || rcd.selected || '">
<name><![CDATA[' || uxml_escapefor_cdata(sName) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
sXML := sXML || '</common>';
--all product types
sXML := sXML || '<producttypes companyid="' || iCompanyId || '">';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, sign(coalesce(cpt2.producttypeid, 0)) as selected, coalesce(cpt2."order", 0) as "order", pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left join tcompany_producttype cpt2 on pt.producttypeid = cpt2.producttypeid and cpt2.companyid = iCompanyId
order by qs.phrase
loop
sName := rcd.phrase;
sLetter := substring(sName from 1 for 1);
if sLastletter is null or not sLetter = sLastletter then
if not sLastletter is null then sXML := sXML || '</letter>'; end if;
sXML := sXML || '<letter char="' || sLetter || '">';
sLastletter := sLetter;
end if;
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" selected="' || rcd.selected || '" order="' || rcd.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(sName) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
sXML := sXML || '</letter></producttypes></root>';
return sXML;
end;
-
ppp_societycard_business_printvouchers
(
25, 25, 23, 23, 25, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iBookId alias for $4;
sStyle alias for $5;
iAmount1 alias for $6;
iValue1 alias for $7;
iAmount2 alias for $8;
iValue2 alias for $9;
iAmount3 alias for $10;
iValue3 alias for $11;
iAmount4 alias for $12;
iValue4 alias for $13;
iAmount5 alias for $14;
iValue5 alias for $15;
iAmount6 alias for $16;
iValue6 alias for $17;
iAmount7 alias for $18;
iValue7 alias for $19;
iAmount8 alias for $20;
iValue8 alias for $21;
iAmount9 alias for $22;
iValue9 alias for $23;
iAmount10 alias for $24;
iValue10 alias for $25;
sSubmit alias for $26;
bSubmission boolean;
bOk boolean;
sXML text;
iMaxVoucherId tvoucher.voucherid%TYPE;
iResultantBookId tvoucherbook.voucherbookid%TYPE;
rcd record;
begin
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sXML := '<root>';
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator to print vouchers</security_denied></root>'; end if;
if bSubmission then
if iBookId = 0 then
insert into tvoucherbook(voucherbookid) values(default);
iResultantBookId := currval('seqvoucherbookid');
else
iResultantBookId := iBookId;
end if;
sXML := sXML || '<vouchers bookid="' || iResultantBookId || '"><' || sStyle || '>';
--maximums
select into iMaxVoucherId max(voucherid) from tvoucher;
if iMaxVoucherId is null then iMaxVoucherId := 0; end if;--no vouchers at all situation
--reserve vouchers (word plus 2 digits)
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue1, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount1;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue2, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount2;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue3, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount3;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue4, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount4;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue5, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount5;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue6, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount6;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue7, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount7;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue8, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount8;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue9, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount9;
insert into tvoucher(voucherbookid, value, code)
select iResultantBookId, iValue10, word || (wordid % 89 + 10) from tword
where not exists(select code from tvoucher where code = word || (wordid % 89 + 10))
and char_length(word) > 2 and char_length(word) < 15
order by wordid limit iAmount10;
--return new vouchers
for rcd in select value, code, voucherid
from tvoucher tv
where voucherid > iMaxVoucherId
loop
sXML := sXML || '<voucher id="' || rcd.voucherid || '" code="' || rcd.code || '" value="' || rcd.value || '"/>';
end loop;
sXML := sXML || '</' || sStyle || '></vouchers>';
end if;
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_business_setbook
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCompanyId alias for $4;
sBookId alias for $5;
sXML text;
begin
--security check
if not usession_isadmin(sSession) then return '<root><security_denied>you must be an administrator for this screen</security_denied></root>'; end if;
update tlcompany set voucherbookid = sBookId::integer where companyid = sCompanyId;
return '<root/>';
end;
-
ppp_societycard_cms_addedit
(
25, 25, 23, 25, 25, 25, 25, 25
)
select ppp_easyethical_cms_addedit($1, $2, $3, $4, $5, $6, $7, $8);
-
ppp_societycard_cms_managepages
(
25, 25, 23, 25, 25, 25, 25, 25
)
select ppp_easyethical_cms_managepages($1, $2, $3, $4, $5, $6, $7, $8)
-
ppp_societycard_cms_templates_basic
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select uxml_cms_url($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27, $28)
-
ppp_societycard_consumer_account_register
(
25, 25, 23, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(location analysis is always put first by the system although it appears elsewhere in the form)
iGoogleStatus alias for $4;
iPointCount alias for $5;
sFirstPoint alias for $6;
--form parameters in order
sEmailAddress alias for $7; --cannot be the screen name
sUserName alias for $8; --often the screen name, so cannot be the email address
iUsernameGenerator alias for $9; --0 - use the username, 1 means use the sUsername as a stem for an auto-username (user should be informed via email of this username), 2 - use email 1st part with auto-generator
sPassword alias for $10;
iPasswordGenerator alias for $11; --0 - use the password, 1 generate password
sArea alias for $12; --input to fuel the location analysis
sLocationDetails alias for $13; --often filled out on second validation if there are options
sSubmit alias for $14; --standard submit button to indicate whether form data has been sent or not
sXML text;
iUserId tuser.userid%TYPE;
iLatestUserId tuser.userid%TYPE;
sFirstname text;
sMiddlename text;
sLastName text;
begin
sFirstname := 'anonymous';
sMiddlename := '';
sLastName := '';
iLatestUserId := nextval('sequserid');
--attempt registration
sXML := ppp_easyethical_account_register(sSession, sSchema, iVersion, true, '', iGoogleStatus, iPointCount, sFirstPoint,
sFirstname, sMiddlename, sLastName,
sEmailAddress, sUserName, iUsernameGenerator, sPassword, iPasswordGenerator,
sArea, sLocationDetails, '', '', sSubmit);
--auto login
iUserId := currval('sequserid');
if not iLatestUserId = iUserId then
perform usession_login(sSession, sUserName, sPassword);
update tuser set system = 'CM' where userid = iUserId;
end if;
return sXML;
end;
-
ppp_societycard_consumer_company_all
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCompanyId alias for $4;
sXML text;
rcd record;
begin
select into sXML '<business id="' || te.entityid || '" companyid="' || tc.companyid || '" userid="' || coalesce(tu.userid, 0) || '" voucherbookid="' || coalesce(tc.voucherbookid, 0) || '">'
|| '<name><![CDATA[' || uxml_escapefor_cdata(qs.phrase) || '</name>'
|| case tu.flickr_photoid when null then '' else
'<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(tu.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(tu.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(tu.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(tu.flickr_photoid[4]) || '</secret>
</photo>'
end
|| case tu.youtube_videoid when '' then '' else '<video><![CDATA[' || uxml_escapefor_cdata(tu.youtube_videoid) || '</video>' end
|| coalesce('<point latitude="' || te.latitude || '" longitude="' || te.longitude || '"><![CDATA[' || uxml_escapefor_cdata(te.location) || '</point>', '')
|| '<messages>'
|| coalesce('<short>' || uxml_parsexml(tu.message_short) || '</short>', '')
|| coalesce('<medium>' || uxml_parsexml(tu.message_medium) || '</medium>', '')
|| coalesce('<long>' || uxml_parsexml(tu.message_long) || '</long>', '')
|| '</messages>'
|| coalesce('<progress target="' || vi.target || '" startdate="' || vi.startdate || '" invested="' || vi.invested || '" recieved="' || vi.recieved || '"/>', '')
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
left outer join tuser tu on tc.companyid = tu.businessownerid
left outer join vinvestmentprogress vi on tc.companyid = vi.companyid
where tc.companyid = sCompanyId;
--products and services
sXML := sXML || '<pnss>';
for rcd in select te.entityid, pt.producttypeid, qs.phrase
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where cpt.companyid = sCompanyId
order by cpt.createdate
loop
sXML := sXML ||
'<pns id="' || rcd.entityid || '" producttypeid="' || rcd.producttypeid || '">
<![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '
</pns>';
end loop;
sXML := sXML || '</pnss>';
--commitments
sXML := sXML || '<commitments>';
for rcd in select * from tcommitment com
where companyid = sCompanyId
order by commitmentid desc --latest first
loop
sXML := sXML ||
'<commitment id="' || rcd.commitmentid || '" percentage="' || rcd.percentage || '" target="' || coalesce(rcd.target, 0) || '">
<![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd.specific, '\n\r', ' ')), '') || '
</commitment>';
end loop;
sXML := sXML || '</commitments>';
sXML := sXML || '</business>';
sXML := '<root>' || coalesce(sXML, '') || '</root>';
return sXML;
end;
-
ppp_societycard_consumer_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_societycard_consumer_entervouchers
(
25, 25, 23, 16, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(recaptcha analysis is always put first by the system although it appears elsewhere in the form)
bRecaptchaOk alias for $4; --can be faked to true by wrapper proc
sRecaptchaError alias for $5;
sBookId alias for $6; --a unique bookid for a company (1 - 1)
sTotalAmount alias for $7;
sTransactionDate alias for $8;
sTillReceiptNumber alias for $9;
sCode1 alias for $10;
sCode2 alias for $11;
sCode3 alias for $12;
sCode4 alias for $13;
sCode5 alias for $14;
sCode6 alias for $15;
sCode7 alias for $16;
sCode8 alias for $17;
sCode9 alias for $18;
sCode10 alias for $19;
sCode11 alias for $20;
sCode12 alias for $21;
sCode13 alias for $22;
sCode14 alias for $23;
sCode15 alias for $24;
sCode16 alias for $25;
sCode17 alias for $26;
sCode18 alias for $27;
sCode19 alias for $28;
sCode20 alias for $29;
sRecaptchaRequest alias for $30;
sRecaptchaResponse alias for $31;
sSubmit alias for $32; --standard submit button to indicate whether form data has been sent or not
bSubmission boolean;
bOk boolean;
sXML text;
--dTransactionDate ttransaction.transactiondate%TYPE;
iCompanyId integer;
sValidationError text;
iTotal integer;
--standard validation regex
sOptional text;
sEmailAddressRequired text;
sEmailAddressOptional text;
sTelephoneOptional text;
sNumeric text;
sNumericOptional text;
sDateOptional text;
sDate text;
begin
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sXML := '<form_requirements submission="' || bSubmission || '">';
--standard validation regex
sOptional := '^$|';
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sNumeric := '^[0-9]+$';
sEmailAddressOptional := sOptional || sEmailAddressRequired;
sTelephoneOptional := sOptional || '^[+]?[0-9 ()]+$';
sNumericOptional := sOptional || '^[0-9]+$';
sDate := '^[0-9][0-9]/[a-zA-Z]{3}/[0-9]{4}$';
sDateOptional := sOptional || sDate;
--companybookid (voucher book)
sXML := sXML || '<book_id required=".+" help="written on the voucher">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sBookId) || '</value>';
if bSubmission then
if not sBookId ~ '.+' then
bOk := false;
sXML := sXML || '<validation_error><![CDATA[book id is required</validation_error>';
else
--if exists(select * from tuser where emailaddress = sEmailAddress) then bOk := false; sXML := sXML || \'<validation_error><![CDATA[email address already exists</validation_error>\'; end if;
end if;
end if;
sXML := sXML || '</book_id>';
--total amount
sXML := sXML || '<total_amount required="' || sNumeric || '" help="the sum of all the values of the vouchers" hide4now="1">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sTotalAmount) || '</value>';
/*
if bSubmission then
if not sTotalAmount ~ sNumeric then
bOk := false;
sXML := sXML || '<validation_error><![CDATA[total amount is required and must be numeric</validation_error>';
else
--if exists(select * from tuser where emailaddress = sEmailAddress) then bOk := false; sXML := sXML || \'<validation_error><![CDATA[email address already exists</validation_error>\'; end if;
end if;
end if;
*/
sXML := sXML || '</total_amount>';
--transaction date
sXML := sXML || '<transaction_date help="don''t worry if you can''t remember" required="' || sDateOptional || '" type="date">
<value><![CDATA[' || sTransactionDate || '</value>';
if bSubmission then
if sTransactionDate = '' then
--dTransactionDate := now();
else
--dTransactionDate := uto_timestamp(sTransactionDate || ' GMT', 'DD/Mon/YYYY');
--if dTransactionDate is null then bOk := false; sFormXML := sFormXML || '<validation_error><![CDATA[invalid transaction date</validation_error>'; end if;
end if;
end if;
sXML := sXML || '</transaction_date>';
--till_receipt_number
sXML := sXML || '<till_receipt_number help="don''t worry if you can''t remember"><value><![CDATA[' || uxml_escapefor_cdata(sTillReceiptNumber) || '</value></till_receipt_number>';
--check each voucher codes for validation errors first
sValidationError := '<validation_error><![CDATA[code does not exist</validation_error>';
sXML := sXML || '<code1><value><![CDATA[' || uxml_escapefor_cdata(sCode1) || '</value>';
if bSubmission and not sCode1 = '' and not exists(select * from tvoucher where code = sCode1 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code1>';
sXML := sXML || '<code2><value><![CDATA[' || uxml_escapefor_cdata(sCode2) || '</value>';
if bSubmission and not sCode2 = '' and not exists(select * from tvoucher where code = sCode2 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code2>';
sXML := sXML || '<code3><value><![CDATA[' || uxml_escapefor_cdata(sCode3) || '</value>';
if bSubmission and not sCode3 = '' and not exists(select * from tvoucher where code = sCode3 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code3>';
sXML := sXML || '<code4><value><![CDATA[' || uxml_escapefor_cdata(sCode4) || '</value>';
if bSubmission and not sCode4 = '' and not exists(select * from tvoucher where code = sCode4 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code4>';
sXML := sXML || '<code5><value><![CDATA[' || uxml_escapefor_cdata(sCode5) || '</value>';
if bSubmission and not sCode5 = '' and not exists(select * from tvoucher where code = sCode5 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code5>';
sXML := sXML || '<code6><value><![CDATA[' || uxml_escapefor_cdata(sCode6) || '</value>';
if bSubmission and not sCode6 = '' and not exists(select * from tvoucher where code = sCode6 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code6>';
sXML := sXML || '<code7><value><![CDATA[' || uxml_escapefor_cdata(sCode7) || '</value>';
if bSubmission and not sCode7 = '' and not exists(select * from tvoucher where code = sCode7 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code7>';
sXML := sXML || '<code8><value><![CDATA[' || uxml_escapefor_cdata(sCode8) || '</value>';
if bSubmission and not sCode8 = '' and not exists(select * from tvoucher where code = sCode8 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code8>';
sXML := sXML || '<code9><value><![CDATA[' || uxml_escapefor_cdata(sCode9) || '</value>';
if bSubmission and not sCode9 = '' and not exists(select * from tvoucher where code = sCode9 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code9>';
sXML := sXML || '<code10><value><![CDATA[' || uxml_escapefor_cdata(sCode10) || '</value>';
if bSubmission and not sCode10 = '' and not exists(select * from tvoucher where code = sCode10 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code10>';
sXML := sXML || '<code11><value><![CDATA[' || uxml_escapefor_cdata(sCode11) || '</value>';
if bSubmission and not sCode11 = '' and not exists(select * from tvoucher where code = sCode11 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code11>';
sXML := sXML || '<code12><value><![CDATA[' || uxml_escapefor_cdata(sCode12) || '</value>';
if bSubmission and not sCode12 = '' and not exists(select * from tvoucher where code = sCode12 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code12>';
sXML := sXML || '<code13><value><![CDATA[' || uxml_escapefor_cdata(sCode13) || '</value>';
if bSubmission and not sCode13 = '' and not exists(select * from tvoucher where code = sCode13 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code13>';
sXML := sXML || '<code14><value><![CDATA[' || uxml_escapefor_cdata(sCode14) || '</value>';
if bSubmission and not sCode14 = '' and not exists(select * from tvoucher where code = sCode14 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code14>';
sXML := sXML || '<code15><value><![CDATA[' || uxml_escapefor_cdata(sCode15) || '</value>';
if bSubmission and not sCode15 = '' and not exists(select * from tvoucher where code = sCode15 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code15>';
sXML := sXML || '<code16><value><![CDATA[' || uxml_escapefor_cdata(sCode16) || '</value>';
if bSubmission and not sCode16 = '' and not exists(select * from tvoucher where code = sCode16 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code16>';
sXML := sXML || '<code17><value><![CDATA[' || uxml_escapefor_cdata(sCode17) || '</value>';
if bSubmission and not sCode17 = '' and not exists(select * from tvoucher where code = sCode17 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code17>';
sXML := sXML || '<code18><value><![CDATA[' || uxml_escapefor_cdata(sCode18) || '</value>';
if bSubmission and not sCode18 = '' and not exists(select * from tvoucher where code = sCode18 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code18>';
sXML := sXML || '<code19><value><![CDATA[' || uxml_escapefor_cdata(sCode19) || '</value>';
if bSubmission and not sCode19 = '' and not exists(select * from tvoucher where code = sCode19 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code19>';
sXML := sXML || '<code20><value><![CDATA[' || uxml_escapefor_cdata(sCode20) || '</value>';
if bSubmission and not sCode20 = '' and not exists(select * from tvoucher where code = sCode20 and voucherbookid = sBookId) then bOk := false; sXML := sXML || sValidationError; end if;
sXML := sXML || '</code20>';
--check the total if all the vouchers are ok so far
/*
if bSubmission and bOk then
select into iTotal sum(value) from tvoucher where voucherbookid = sBookId and code in(sCode1, sCode2, sCode3, sCode4, sCode5, sCode6, sCode7, sCode8, sCode9, sCode10,
sCode11, sCode12, sCode13, sCode14, sCode15, sCode16, sCode17, sCode18, sCode19, sCode20);
if not iTotal = sTotalAmount then
bOk := false;
sXML := sXML || '<validation_error><![CDATA[total does not match, please re-sum all the vouchers</validation_error>';
end if;
end if;
*/
--recaptcha (recaptcha analysis is always put first by the system although it appears elsewhere in the form)
sXML := sXML || '<recaptcha>';
if bSubmission and not bRecaptchaOk then bOk := false; sXML := sXML || '<validation_error><![CDATA[recaptcha did not match</validation_error>'; end if;
sXML := sXML || '</recaptcha>';
sXML := sXML || '</form_requirements>';
--######################################## action ##############################################
if bSubmission and bOk then
sXML := '<success>';
insert into ttransaction(transactionid) values(default);
insert into ttransaction_voucher(transactionid, voucherid)
select currval('seqtransactionid'), voucherid from tvoucher where voucherbookid = sBookId and code in(sCode1, sCode2, sCode3, sCode4, sCode5, sCode6, sCode7, sCode8, sCode9, sCode10,
sCode11, sCode12, sCode13, sCode14, sCode15, sCode16, sCode17, sCode18, sCode19, sCode20);
sXML := sXML || '</success>';
end if;
sXML := '<root>' || sXML || '</root>';
return sXML;
end;
-
ppp_societycard_consumer_pns_addeditcategory
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--sFileList alias for $4;
sCategoryId alias for $4;
sName alias for $5;
sIcon alias for $6;
sSubmit alias for $7;
sOriginalName text;
sOriginalIcon text;
sOptional text;
sEmailAddressRequired text;
sNumeric text;
sEmailAddressOptional text;
sTelephoneOptional text;
sNumericOptional text;
sDateOptional text;
sDate text;
aFileListArray text[];
iLen integer;
sElement text;
sXML text;
bOk boolean;
bIsAdmin boolean;
bSubmission boolean;
begin
sXML := '';
bOk := true;
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bIsAdmin := usession_isadmin(sSession);
--standard validation regex
sOptional := '^$|';
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sNumeric := '^[0-9]+$';
sDate := '^[0-9][0-9]/[a-zA-Z]{3}/[0-9]{4}$';
sEmailAddressOptional := sOptional || sEmailAddressRequired;
sTelephoneOptional := sOptional || '^[+]?[0-9 ()]+$';
sNumericOptional := sOptional || '^[0-9]+$';
sDateOptional := sOptional || sDate;
--######################################## original ##############################################
if sCategoryId ~ sNumeric then
select into sOriginalName, sOriginalIcon qs.phrase, pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where producttypeid = sCategoryId::integer;
end if;
--######################################## form fields ##############################################
sXML := sXML || '<form_requirements submission="' || bSubmission || '">';
sXML := sXML || '<producttypeid hide="1">
<value><![CDATA[' || uxml_escapefor_cdata(sCategoryId) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sCategoryId) || '</original>
</producttypeid>';
sXML := sXML || '<name>
<value><![CDATA[' || uxml_escapefor_cdata(sName) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalName) || '</original>
</name>';
sXML := sXML || '<icon>
<value><![CDATA[' || uxml_escapefor_cdata(sIcon) || '</value>
<original><![CDATA[' || uxml_escapefor_cdata(sOriginalIcon) || '</original>';
/* aFileListArray := sFileList;
iLen := array_upper(aFileListArray, 1);
sXML := sXML || '<options>
<option code="">-- none --</option>';
if not iLen is null then
for i in 1..iLen loop
sElement := aFileListArray[i];
if not sElement is null then
sXML := sXML || '<file><![CDATA[' || uxml_escapefor_cdata(substring(sElement from '^[^.]*')) || '</file>';
end if;
end loop;
end if;
sXML := sXML || '</options>';
*/
sXML := sXML || '</icon>';
sXML := sXML || '</form_requirements>';
--######################################## action ##############################################
if bSubmission and bOk then
if sIcon = '' then update tlproducttype set icon = null where producttypeid = sCategoryId::integer;
else update tlproducttype set icon = sIcon where producttypeid = sCategoryId::integer;
end if;
sXML := '<success/>';
end if;
sXML := '<root>' || sXML || '</root>';
return sXML;
end;
-
ppp_societycard_consumer_pns_all
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_societycard_consumer_pns_index($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
-
ppp_societycard_consumer_pns_index
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sTopLevelProductTypeCategory alias for $4;
sSubmit alias for $5;
sNewParentCategory alias for $6;
sNewRelevance alias for $7;
sPnS alias for $8;
sXML text;
iTopLevelProductTypeCategoryId integer;
sTopLevelProductTypeCategory_normalised text;
bIsAdmin boolean;
bSubmission boolean;
aPnS integer[];
sName text;
sLetter char(1);
sLastletter char(1);
rcd record;
begin
--figure out the pns name, may be an id
if sTopLevelProductTypeCategory ~ '^[0-9]+$' then
select into iTopLevelProductTypeCategoryId producttype_categoryid
from tlproducttype_category
where producttype_categoryid = sTopLevelProductTypeCategory;
else
sTopLevelProductTypeCategory_normalised = lower(sTopLevelProductTypeCategory);
select into iTopLevelProductTypeCategoryId producttype_categoryid
from tlproducttype_category
where lower(name) = sTopLevelProductTypeCategory_normalised;
end if;
sXML := '<root topLevelProductTypeCategoryId="' || coalesce(iTopLevelProductTypeCategoryId, 0) || '" >';
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bIsAdmin := usession_isadmin(sSession);
--submission (admin and no necessary verification)
if bSubmission then
aPns := '{' || sPnS || '}';
if sSubmit = 'set category' then
--clear categories for the selected
if sNewParentCategory = 0 then
delete from tproducttype_producttype_category where anyof(producttypeid, aPns);
else
delete from tproducttype_producttype_category where anyof(producttypeid, aPns) and producttype_categoryid = sNewParentCategory::integer;
--add to this category for the selected
insert into tproducttype_producttype_category(producttypeid, producttype_categoryid)
select producttypeid, sNewParentCategory::integer
from tlproducttype
where anyof(producttypeid, aPns);
end if;
end if;
if sSubmit = 'toggle active' then
update tlproducttype set relevance9c = 100 - sign(relevance9c)*100 where anyof(producttypeid, aPns);
end if;
if sSubmit = 'set relevance' then
update tlproducttype set relevance9c = sNewRelevance::integer where anyof(producttypeid, aPns);
end if;
end if;
--top level product type categories
sXML := sXML || '<producttype_categories>';
for rcd in select pc.producttype_categoryid, pc.name, pc.description, pc.colour, count(pt.producttypeid)
from tlproducttype_category pc
left outer join tproducttype_producttype_category pcp on pc.producttype_categoryid = pcp.producttype_categoryid
left outer join tlproducttype pt on pt.producttypeid = pcp.producttypeid
where pc.parentcategoryid = -1 --only the top level here (other levels are not shown to the user)
and not(pc.relevance9c = 0) --elements, and thus whole sub-trees can be ignored
group by pc.producttype_categoryid, pc.name, pc.description, pc.colour
order by name
loop
sXML := sXML || '<producttype_category id="' || rcd.producttype_categoryid || '" count="' || rcd.count || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>';
if not rcd.colour is null and not rcd.colour = '' then sXML := sXML || '<colour><![CDATA[' || uxml_escapefor_cdata(rcd.colour) || '</colour>'; end if;
sXML := sXML || '</producttype_category>';
end loop;
sXML := sXML || '</producttype_categories>';
--common product types
sXML := sXML || '<common>';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, count(*), pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
group by pt.producttypeid, te.entityid, qs.phrase, pt.icon
order by count(*) desc
limit 20
loop
sName := rcd.phrase;
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '">
<name><![CDATA[' || uxml_escapefor_cdata(sName) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
sXML := sXML || '</common>';
--all product types
sXML := sXML || '<producttypes>';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, pt.relevance9c, pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where (bIsAdmin = true or not pt.relevance9c = 0) --relevance
and (
--no category sent - return everything
(sTopLevelProductTypeCategory = '' or sTopLevelProductTypeCategory = 'index')
--category found, return its members
or (not iTopLevelProductTypeCategoryId is null and exists(select * from tproducttype_producttype_category pcp where pcp.producttypeid = pt.producttypeid and pcp.producttype_categoryid = iTopLevelProductTypeCategoryId))
--special administrator unassigned category requested
or (sTopLevelProductTypeCategory = 'unassigned' and not exists(select * from tproducttype_producttype_category pcp where pcp.producttypeid = pt.producttypeid) and not pt.relevance9c = 0)
--special administrator top priority
or (sTopLevelProductTypeCategory = 'priority' and pt.relevance9c = 100)
)
order by qs.phrase
loop
sName := rcd.phrase;
sLetter := substring(sName from 1 for 1);
if sLastletter is null or not sLetter = sLastletter then
if not sLastletter is null then sXML := sXML || '</letter>'; end if;
sXML := sXML || '<letter char="' || sLetter || '">';
sLastletter := sLetter;
end if;
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" relevance9c="' || rcd.relevance9c || '">
<name><![CDATA[' || uxml_escapefor_cdata(sName) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
if not sLetter is null then sXML := sXML || '</letter>'; end if;
sXML := sXML || '</producttypes></root>';
return sXML;
end;
-
ppp_societycard_consumer_search
(
25, 25, 23, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSearchTerm alias for $4;
sLocation alias for $5;
sOffer alias for $6;
sOrderBy alias for $7;
sSubmit alias for $8;
iLastTLC tlproducttype_category.producttype_categoryid%TYPE;
iThisTLC tlproducttype_category.producttype_categoryid%TYPE;
iCompanyId tlcompany.companyid%TYPE;
sEndDefinition char(1);
sXML text;
bIsAdmin boolean;
bSubmission boolean;
rcd record;
rcd_com record;
begin
sXML := '<root>';
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bIsAdmin := usession_isadmin(sSession);
--register search term
if bSubmission then
if not sSearchTerm = '' then
update tsearches set amount = amount + 1, lastused = now() where term = sSearchTerm;
if found = false then insert into tsearches(term) values(sSearchTerm); end if;
end if;
end if;
--######################################################## search form ########################################################
sXML := sXML || '<form_requirements>';
--a distinct set of producttypes that are in use
sXML := sXML || '<producttypes_available caption="product type" type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<producttype id="0" code="0"><![CDATA[all</producttype>';
for rcd in select pt.producttypeid, qs.phrase, count(*)
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
group by pt.producttypeid, qs.phrase
loop
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '" code="' || rcd.producttypeid || '">
<![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || ' (' || rcd.count || ')
</producttype>';
end loop;
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sSearchTerm) || '</value>';
sXML := sXML || '</producttypes_available>';
--location
sXML := sXML || '<location type="radio" help="controls the initial zoom level">';
sXML := sXML || '<options>';
sXML := sXML || '<location id="0" code="0"><![CDATA[anywhere</location>';
sXML := sXML || '<location id="1" code="1"><![CDATA[in my city</location>';
sXML := sXML || '<location id="2" code="2"><![CDATA[within 20 miles</location>';
sXML := sXML || '<location id="3" code="3"><![CDATA[within 5 miles</location>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sLocation) || '</value>';
sXML := sXML || '</location>';
--offer
sXML := sXML || '<offer type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<offer id="0" code="0"><![CDATA[all</offer>';
sXML := sXML || '<offer id="1" code="1"><![CDATA[more than 20%</offer>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOffer) || '</value>';
sXML := sXML || '</offer>';
--order
sXML := sXML || '<order type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<order id="0" code="0"><![CDATA[vicinity</order>';
sXML := sXML || '<order id="1" code="1"><![CDATA[offer</order>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOrderBy) || '</value>';
sXML := sXML || '</order>';
--google results
sXML := sXML || '<include_google_results help="not fully developed yet" type="checkbox" disable4now="1">';
--sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOffer) || '</value>';
sXML := sXML || '<value><![CDATA[1</value>';
sXML := sXML || '</include_google_results>';
sXML := sXML || '</form_requirements>';
--######################################################## categories hierarchy ########################################################
--top level product type categories
sXML := sXML || '<producttype_hierarchy>';
for rcd in select pc.producttype_categoryid, pc.name as tlcname, pc.description, pc.colour, pc.icon as tlcicon, --category
te.entityid, qs.phrase as ptname, pt.icon --product type
from tlproducttype_category pc
inner join tproducttype_producttype_category pcp on pc.producttype_categoryid = pcp.producttype_categoryid --many to many
inner join tlproducttype pt on pt.producttypeid = pcp.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
where pc.parentcategoryid = -1
group by pc.producttype_categoryid, pc.name, pc.description, pc.colour, pc.icon, te.entityid, qs.phrase, pt.icon
order by pc.name, qs.phrase
loop
--TLC
iThisTLC := rcd.producttype_categoryid;
if iLastTLC is null or not iLastTLC = iThisTLC then
if not iLastTLC is null then sXML := sXML || '</producttypes></category>'; end if;
sXML := sXML || '<category id="' || rcd.producttype_categoryid || '">';
if not rcd.colour is null and not rcd.colour = '' then sXML := sXML || '<colour><![CDATA[' || uxml_escapefor_cdata(rcd.colour) || '</colour>'; end if;
if not rcd.tlcicon is null and not rcd.tlcicon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.tlcicon) || '</icon>'; end if;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.tlcname) || '</name>';
sXML := sXML || '<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>';
sXML := sXML || '<producttypes>';
iLastTLC := iThisTLC;
end if;
--PT
sXML := sXML || '<producttype id="' || rcd.entityid || '">';
if not rcd.icon is null and not rcd.icon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.ptname) || '</name>
</producttype>';
end loop;
sXML := sXML || '</producttypes></category></producttype_hierarchy>';
--######################################################## businesses ########################################################
--cycle through all the companies that have or had a commitment
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[9carrots.org businesses</rss:title>
<rss:description><![CDATA[business searched for</rss:description>
<rss:relativelinkroot><![CDATA[/consumer/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<businesses>';
for rcd in select tc.companyid, te.entityid, te.subtype, qs.phrase, te.longitude, te.latitude, te.location, tc.voucherbookid, tu.userid, vi.*, tc.businesstypequalifier, tc.website, te.createdate,
tc.icon,
tu.flickr_photoid, tu.youtube_videoid,
tu.message_short, tu.message_medium, tu.message_long,
tu.emailaddress, tu.blackballed
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
inner join tuser tu on tc.companyid = tu.businessownerid
inner join vinvestmentprogress vi on tc.companyid = vi.companyid
where exists (select * from tcommitment where companyid = tc.companyid)
--or exists (select * from tinvestement where companyid = tc.companyid)
loop
iCompanyId := rcd.companyid;
sXML := sXML || '<business id="' || rcd.entityid || '" companyid="' || iCompanyId || '" userid="' || rcd.userid|| '" blackballed="' || rcd.blackballed || '" voucherbookid="' || coalesce(rcd.voucherbookid, 0) || '" subtype="' || coalesce(rcd.subtype, '') || '">
<businesstypequalifier><![CDATA[' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</businesstypequalifier>';
--rss fields
sXML := sXML || '<rss:id><![CDATA[' || uxml_escapefor_cdata(iCompanyId) || '</rss:id>';
sXML := sXML || '<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || ' ' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</rss:title>';
sXML := sXML || '<rss:description><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</rss:description>';
sXML := sXML || '<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</rss:pubdate>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
if not rcd.youtube_videoid is null and not rcd.youtube_videoid = '' then
sXML := sXML || '<video><![CDATA[' || uxml_escapefor_cdata(rcd.youtube_videoid) || '</video>';
end if;
if not rcd.flickr_photoid is null and not rcd.flickr_photoid = '{}' then
sXML := sXML || '<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[4]) || '</secret>
</photo>';
end if;
if not rcd.website is null and not rcd.website = '' then sXML := sXML || '<website><![CDATA[' || uxml_escapefor_cdata(rcd.website) || '</website>'; end if; --don't include node if not available
sXML := sXML || '<point latitude="' || rcd.latitude || '" longitude="' || rcd.longitude || '"><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</point>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
sXML := sXML || '<emailaddress><![CDATA[' || uxml_escapefor_cdata(rcd.emailaddress) || '</emailaddress>';
if not rcd.message_short is null and not rcd.message_short = '' then sXML := sXML || '<short>' || uxml_parsexml(rcd.message_short) || '</short>'; end if;
--progress
sXML := sXML || '<progress target="' || rcd.target || '" startdate="' || rcd.startdate || '" invested="' || rcd.invested || '" recieved="' || rcd.recieved || '"/>';
--commitments
sXML := sXML || '<commitments>';
for rcd_com in select *
from tcommitment com
where companyid = iCompanyId
order by commitmentid desc --latest first
loop
if rcd_com.enddate is null then sEndDefinition = 'T';
elsif rcd_com.enddate = rcd_com.startdate then sEndDefinition = 'F';
else sEndDefinition = 'E';
end if;
sXML := sXML || '<commitment id="' || rcd_com.commitmentid || '" enddefinition="' || sEndDefinition || '" report="' || (rcd_com.specific = '') || '" percentage="' || rcd_com.percentage || '" target="' || coalesce(rcd_com.target, 0) || '">';
if not rcd_com.startdate is null then sXML := sXML || '<startdate><![CDATA[' || uxml_escapefor_cdata(rcd_com.startdate) || '</startdate>'; end if;
if not rcd_com.enddate is null then sXML := sXML || '<enddate><![CDATA[' || uxml_escapefor_cdata(rcd_com.enddate) || '</enddate>'; end if;
if not rcd_com.specific is null and not rcd_com.specific = '' then sXML := sXML || '<specific><![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd_com.specific, '\n\r', ' ')), '') || '</specific>'; end if;
sXML := sXML || '</commitment>';
end loop;
sXML := sXML || '</commitments>';
--products and services
sXML := sXML || '<pnss>';
for rcd_com in select te.entityid, pt.producttypeid, qs.phrase, cpt."order", pt.icon,
pc.producttype_categoryid, pc.name, pc.icon as tlcicon, pc.colour
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left outer join tproducttype_producttype_category pcp on pt.producttypeid = pcp.producttypeid --many to many
left outer join tlproducttype_category pc on pcp.producttype_categoryid = pc.producttype_categoryid
where cpt.companyid = iCompanyId
order by cpt.createdate
loop
sXML := sXML || '<pns id="' || rcd_com.entityid || '" producttypeid="' || rcd_com.producttypeid || '" order="' || rcd_com.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.phrase) || '</name>';
if not rcd_com.producttype_categoryid is null then
sXML := sXML || '<tlc id="' || rcd_com.producttype_categoryid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.name) || '</name>';
if not rcd_com.tlcicon is null and not rcd_com.tlcicon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.tlcicon) || '</icon>'; end if;
if not rcd_com.colour is null and not rcd_com.colour = '' then sXML := sXML || '<colour><![CDATA[' || uxml_escapefor_cdata(rcd_com.colour) || '</colour>'; end if;
sXML := sXML || '</tlc>';
end if;
if not rcd_com.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</pns>';
end loop;
sXML := sXML || '</pnss>';
sXML := sXML || '</business>';
end loop;
sXML := sXML || '</businesses>
</rss:items>
</rss:feed>';
--######################################################## common ########################################################
--common product types
sXML := sXML || '<common>';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, count(*), pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
group by pt.producttypeid, te.entityid, qs.phrase, pt.icon
order by count(*) desc
limit 20
loop
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
sXML := sXML || '</common>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_consumer_search
(
25, 25, 23, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sContracts alias for $4;
sSearchTerm alias for $5;
sLocation alias for $6;
sOffer alias for $7;
sOrderBy alias for $8;
sSubmit alias for $9;
aContracts text[];
bHasContract boolean;
iLastTLC tlproducttype_category.producttype_categoryid%TYPE;
iThisTLC tlproducttype_category.producttype_categoryid%TYPE;
iCompanyId tlcompany.companyid%TYPE;
sEndDefinition char(1);
sXML text;
bIsAdmin boolean;
bSubmission boolean;
rcd record;
rcd_com record;
begin
sXML := '<root>';
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bIsAdmin := usession_isadmin(sSession);
aContracts := sContracts;
--register search term
if bSubmission then
if not sSearchTerm = '' then
update tsearches set amount = amount + 1, lastused = now() where term = sSearchTerm;
if found = false then insert into tsearches(term) values(sSearchTerm); end if;
end if;
end if;
--######################################################## search form ########################################################
sXML := sXML || '<form_requirements>';
--a distinct set of producttypes that are in use
sXML := sXML || '<producttypes_available caption="product type" type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<producttype id="0" code="0"><![CDATA[all</producttype>';
for rcd in select pt.producttypeid, qs.phrase, count(*)
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
group by pt.producttypeid, qs.phrase
loop
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '" code="' || rcd.producttypeid || '">
<![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || ' (' || rcd.count || ')
</producttype>';
end loop;
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sSearchTerm) || '</value>';
sXML := sXML || '</producttypes_available>';
--location
sXML := sXML || '<location type="radio" help="controls the initial zoom level">';
sXML := sXML || '<options>';
sXML := sXML || '<location id="0" code="0"><![CDATA[anywhere</location>';
sXML := sXML || '<location id="1" code="1"><![CDATA[in my city</location>';
sXML := sXML || '<location id="2" code="2"><![CDATA[within 20 miles</location>';
sXML := sXML || '<location id="3" code="3"><![CDATA[within 5 miles</location>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sLocation) || '</value>';
sXML := sXML || '</location>';
--offer
sXML := sXML || '<offer type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<offer id="0" code="0"><![CDATA[all</offer>';
sXML := sXML || '<offer id="1" code="1"><![CDATA[more than 20%</offer>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOffer) || '</value>';
sXML := sXML || '</offer>';
--order
sXML := sXML || '<order type="select">';
sXML := sXML || '<options>';
sXML := sXML || '<order id="0" code="0"><![CDATA[vicinity</order>';
sXML := sXML || '<order id="1" code="1"><![CDATA[offer</order>';
sXML := sXML || '</options>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOrderBy) || '</value>';
sXML := sXML || '</order>';
--google results
sXML := sXML || '<include_google_results help="not fully developed yet" type="checkbox" disable4now="1">';
--sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sOffer) || '</value>';
sXML := sXML || '<value><![CDATA[1</value>';
sXML := sXML || '</include_google_results>';
sXML := sXML || '</form_requirements>';
--######################################################## categories hierarchy ########################################################
--top level product type categories
sXML := sXML || '<producttype_hierarchy>';
for rcd in select pc.producttype_categoryid, pc.name as tlcname, pc.description, pc.colour, pc.icon as tlcicon, --category
te.entityid, qs.phrase as ptname, pt.icon --product type
from tlproducttype_category pc
inner join tproducttype_producttype_category pcp on pc.producttype_categoryid = pcp.producttype_categoryid --many to many
inner join tlproducttype pt on pt.producttypeid = pcp.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
where pc.parentcategoryid = -1
group by pc.producttype_categoryid, pc.name, pc.description, pc.colour, pc.icon, te.entityid, qs.phrase, pt.icon
order by pc.name, qs.phrase
loop
--TLC
iThisTLC := rcd.producttype_categoryid;
if iLastTLC is null or not iLastTLC = iThisTLC then
if not iLastTLC is null then sXML := sXML || '</producttypes></category>'; end if;
sXML := sXML || '<category id="' || rcd.producttype_categoryid || '">';
if not rcd.colour is null and not rcd.colour = '' then sXML := sXML || '<colour><![CDATA[' || uxml_escapefor_cdata(rcd.colour) || '</colour>'; end if;
if not rcd.tlcicon is null and not rcd.tlcicon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.tlcicon) || '</icon>'; end if;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.tlcname) || '</name>';
sXML := sXML || '<description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</description>';
sXML := sXML || '<producttypes>';
iLastTLC := iThisTLC;
end if;
--PT
sXML := sXML || '<producttype id="' || rcd.entityid || '">';
if not rcd.icon is null and not rcd.icon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.ptname) || '</name>
</producttype>';
end loop;
sXML := sXML || '</producttypes></category></producttype_hierarchy>';
--######################################################## businesses ########################################################
--cycle through all the companies that have or had a commitment
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[9carrots.org businesses</rss:title>
<rss:description><![CDATA[business searched for</rss:description>
<rss:relativelinkroot><![CDATA[/consumer/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<businesses>';
for rcd in select tc.companyid, te.entityid, te.status, te.subtype, qs.phrase, te.longitude, te.latitude, te.location, tu.userid, tc.businesstypequalifier, tc.website, te.createdate,
vi.*,
tc.icon,
tu.flickr_photoid, tu.youtube_videoid,
tu.message_short, tu.message_medium, tu.message_long,
tu.emailaddress, tu.blackballed
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
inner join tuser tu on tc.companyid = tu.businessownerid
inner join vinvestmentprogress vi on tc.companyid = vi.companyid
where exists (select * from tcommitment where companyid = tc.companyid)
--or exists (select * from tinvestement where companyid = tc.companyid)
and not coalesce(te.status, '') = 'RT'
loop
iCompanyId := rcd.companyid;
bHasContract := (rcd.phrase || '.pdf' = any(aContracts)); --contract?
sXML := sXML || '<business id="' || rcd.entityid || '" companyid="' || iCompanyId || '" userid="' || rcd.userid|| '" status="' || coalesce(rcd.status, '') || '" blackballed="' || rcd.blackballed || '" contract="' || bHasContract || '" subtype="' || coalesce(rcd.subtype, '') || '">
<businesstypequalifier><![CDATA[' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</businesstypequalifier>';
--rss fields
sXML := sXML || '<rss:id><![CDATA[' || uxml_escapefor_cdata(iCompanyId) || '</rss:id>';
sXML := sXML || '<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || ' ' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</rss:title>';
sXML := sXML || '<rss:description><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</rss:description>';
sXML := sXML || '<rss:pubdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate, 2)) || '</rss:pubdate>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
if not rcd.youtube_videoid is null and not rcd.youtube_videoid = '' then
sXML := sXML || '<video><![CDATA[' || uxml_escapefor_cdata(rcd.youtube_videoid) || '</video>';
end if;
if not rcd.flickr_photoid is null and not rcd.flickr_photoid = '{}' then
sXML := sXML || '<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[4]) || '</secret>
</photo>';
end if;
if not rcd.website is null and not rcd.website = '' then sXML := sXML || '<website><![CDATA[' || uxml_escapefor_cdata(rcd.website) || '</website>'; end if; --don't include node if not available
sXML := sXML || '<point latitude="' || rcd.latitude || '" longitude="' || rcd.longitude || '"><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</point>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
sXML := sXML || '<emailaddress><![CDATA[' || uxml_escapefor_cdata(rcd.emailaddress) || '</emailaddress>';
if not rcd.message_short is null and not rcd.message_short = '' then sXML := sXML || '<short>' || uxml_parsexml(rcd.message_short) || '</short>'; end if;
--progress
sXML := sXML || '<progress target="' || rcd.target || '" startdate="' || rcd.startdate || '" invested="' || rcd.invested || '" recieved="' || rcd.recieved || '"/>';
--commitments
sXML := sXML || '<commitments>';
for rcd_com in select *
from tcommitment com
where companyid = iCompanyId
order by commitmentid desc --latest first
loop
if rcd_com.enddate is null then sEndDefinition = 'T';
elsif rcd_com.enddate = rcd_com.startdate then sEndDefinition = 'F';
else sEndDefinition = 'E';
end if;
sXML := sXML || '<commitment id="' || rcd_com.commitmentid || '" enddefinition="' || sEndDefinition || '" report="' || (rcd_com.specific = '') || '" percentage="' || rcd_com.percentage || '" target="' || coalesce(rcd_com.target, 0) || '">';
if not rcd_com.startdate is null then sXML := sXML || '<startdate><![CDATA[' || uxml_escapefor_cdata(rcd_com.startdate) || '</startdate>'; end if;
if not rcd_com.enddate is null then sXML := sXML || '<enddate><![CDATA[' || uxml_escapefor_cdata(rcd_com.enddate) || '</enddate>'; end if;
if not rcd_com.specific is null and not rcd_com.specific = '' then sXML := sXML || '<specific><![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd_com.specific, '\n\r', ' ')), '') || '</specific>'; end if;
sXML := sXML || '</commitment>';
end loop;
sXML := sXML || '</commitments>';
--products and services
sXML := sXML || '<pnss>';
for rcd_com in select te.entityid, pt.producttypeid, qs.phrase, cpt."order", pt.icon,
pc.producttype_categoryid, pc.name, pc.icon as tlcicon, pc.colour
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left outer join tproducttype_producttype_category pcp on pt.producttypeid = pcp.producttypeid --many to many
left outer join tlproducttype_category pc on pcp.producttype_categoryid = pc.producttype_categoryid
where cpt.companyid = iCompanyId
order by cpt.createdate
loop
sXML := sXML || '<pns id="' || rcd_com.entityid || '" producttypeid="' || rcd_com.producttypeid || '" order="' || rcd_com.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.phrase) || '</name>';
if not rcd_com.producttype_categoryid is null then
sXML := sXML || '<tlc id="' || rcd_com.producttype_categoryid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.name) || '</name>';
if not rcd_com.tlcicon is null and not rcd_com.tlcicon = '' then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.tlcicon) || '</icon>'; end if;
if not rcd_com.colour is null and not rcd_com.colour = '' then sXML := sXML || '<colour><![CDATA[' || uxml_escapefor_cdata(rcd_com.colour) || '</colour>'; end if;
sXML := sXML || '</tlc>';
end if;
if not rcd_com.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</pns>';
end loop;
sXML := sXML || '</pnss>';
sXML := sXML || '</business>';
end loop;
sXML := sXML || '</businesses>
</rss:items>
</rss:feed>';
--######################################################## common ########################################################
--common product types
sXML := sXML || '<common>';
for rcd in select pt.producttypeid, te.entityid, qs.phrase, count(*), pt.icon
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
inner join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
group by pt.producttypeid, te.entityid, qs.phrase, pt.icon
order by count(*) desc
limit 20
loop
sXML := sXML || '<producttype id="' || rcd.producttypeid || '" count="' || rcd.count || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</producttype>';
end loop;
sXML := sXML || '</common>';
sXML := sXML || '</root>';
return sXML;
end;
-
ppp_societycard_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_societycard_docontactus
()
select ppp_easyethical_docontactus($1, $2, $3, $4, $5, $6)
-
ppp_societycard_dojoinemaillist
()
select ppp_easyethical_dojoinemaillist($1, $2, $3, $4, $5);
-
ppp_societycard_homepage
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
rcd_com record;
sEndDefinition char(1);
iCompanyId integer;
begin
sXML := '<root>';
sXML := sXML || uxml_cms_values(sSessionId, sSchema, iVersion, '{societycard_index_newsfeed, societycard_index_strapline, societycard_index_start, societycard_index_find_pns, societycard_index_buying_something, societycard_index_register_transaction, societycard_index_see_progress, societycard_index_save_world}');
--cycle through all the companies that have or had a commitment
sXML := sXML || '<businesses>';
for rcd in select tc.companyid, te.entityid, te.createdate, qs.phrase, te.longitude, te.latitude, te.location, tc.voucherbookid, tu.userid, vi.*, tc.businesstypequalifier,
(
select pc.name from tcompany_producttype cpt
inner join tproducttype_producttype_category ppc on cpt.producttypeid = ppc.producttypeid
inner join tlproducttype_category pc on ppc.producttype_categoryid = pc.producttype_categoryid
where cpt.companyid = tc.companyid
limit 1
) as tlc, tc.icon,
tu.flickr_photoid, tu.youtube_videoid,
tu.message_short, tu.message_medium, tu.message_long,
tu.emailaddress, tu.blackballed
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
inner join tuser tu on tc.companyid = tu.businessownerid
inner join vinvestmentprogress vi on tc.companyid = vi.companyid
where exists (select * from tcommitment where companyid = tc.companyid)
--or exists (select * from tinvestement where companyid = tc.companyid)
order by te.createdate desc, tc.companyid desc
loop
iCompanyId := rcd.companyid;
sXML := sXML || '<business id="' || rcd.entityid || '" companyid="' || iCompanyId || '" userid="' || rcd.userid || '" blackballed="' || rcd.blackballed || '" voucherbookid="' || coalesce(rcd.voucherbookid, 0) || '">
<businesstypequalifier><![CDATA[' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</businesstypequalifier>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate)) || '</createdate>';
if not rcd.tlc is null then sXML := sXML || '<tlc><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.tlc, '')) || '</tlc>'; end if;
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
if not rcd.youtube_videoid is null and not rcd.youtube_videoid = '' then
sXML := sXML || '<video><![CDATA[' || uxml_escapefor_cdata(rcd.youtube_videoid) || '</video>';
end if;
if not rcd.flickr_photoid is null and not rcd.flickr_photoid = '{}' then
sXML := sXML || '<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[4]) || '</secret>
</photo>';
end if;
sXML := sXML || '<point latitude="' || rcd.latitude || '" longitude="' || rcd.longitude || '"><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</point>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
sXML := sXML || '<emailaddress><![CDATA[' || uxml_escapefor_cdata(rcd.emailaddress) || '</emailaddress>';
sXML := sXML || '<messages>'
|| coalesce('<short>' || uxml_parsexml(rcd.message_short) || '</short>', '')
|| coalesce('<medium>' || uxml_parsexml(rcd.message_medium) || '</medium>', '')
|| coalesce('<long>' || uxml_parsexml(rcd.message_long) || '</long>', '')
|| '</messages>';
--progress
sXML := sXML || '<progress target="' || rcd.target || '" startdate="' || rcd.startdate || '" invested="' || rcd.invested || '" recieved="' || rcd.recieved || '"/>';
--commitments
sXML := sXML || '<commitments>';
for rcd_com in select * from tcommitment com
where companyid = iCompanyId
order by commitmentid desc --latest first
loop
if rcd_com.enddate is null then sEndDefinition = 'T';
elsif rcd_com.enddate = rcd_com.startdate then sEndDefinition = 'F';
else sEndDefinition = 'E';
end if;
sXML := sXML ||
'<commitment id="' || rcd_com.commitmentid || '" enddefinition="' || sEndDefinition || '" report="' || (rcd_com.specific = '') || '" percentage="' || rcd_com.percentage || '" target="' || coalesce(rcd_com.target, 0) || '">
<startdate><![CDATA[' || coalesce(uxml_escapefor_cdata(rcd_com.startdate), '') || '</startdate>
<enddate><![CDATA[' || coalesce(uxml_escapefor_cdata(rcd_com.enddate), '') || '</enddate>
<specific><![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd_com.specific, '\n\r', ' ')), '') || '</specific>
</commitment>';
end loop;
sXML := sXML || '</commitments>';
--products and services
sXML := sXML || '<pnss>';
for rcd_com in select te.entityid, pt.producttypeid, qs.phrase, pt.icon, cpt."order"
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where cpt.companyid = iCompanyId
order by cpt."order", cpt.createdate
loop
sXML := sXML ||
'<pns id="' || rcd_com.entityid || '" producttypeid="' || rcd_com.producttypeid || '" order="' || rcd_com.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.phrase) || '</name>';
if not rcd_com.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</pns>';
end loop;
sXML := sXML || '</pnss>';
sXML := sXML || '</business>';
end loop;
sXML := sXML || '</businesses></root>';
return sXML;
end;
-
ppp_societycard_includes_register
(
25, 25, 23, 16, 25, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
--(recaptcha analysis is always put first by the system although it appears elsewhere in the form)
bRecaptchaOk alias for $4; --can be faked to true by wrapper proc
sRecaptchaError alias for $5;
--(location analysis is always put first by the system although it appears elsewhere in the form)
iGoogleStatus alias for $6;
iPointCount alias for $7;
sFirstPoint alias for $8;
--form parameters in order
sEmailAddress alias for $9; --cannot be the screen name
sUserName alias for $10; --often the screen name, so cannot be the email address
iUsernameGenerator alias for $11; --0 - use the username, 1 means use the sUsername as a stem for an auto-username (user should be informed via email of this username), 2 - use email 1st part with auto-generator
sPassword alias for $12;
iPasswordGenerator alias for $13; --0 - use the password, 1 generate password
sBusinessName alias for $14;
sBusinessTypeQualifier alias for $15;
sWebsite alias for $16;
sPnS_Email alias for $17;
sPnSTelephone alias for $18;
sArea alias for $19; --input to fuel the location analysis
sNearestStation alias for $20;
sAddressNotes alias for $21;
sLocationDetails alias for $22; --often filled out on second validation if there are options
sRecaptchaRequest alias for $23;
sRecaptchaResponse alias for $24;
sType9c alias for $25;
sSubmit alias for $26; --standard submit button to indicate whether form data has been sent or not
--inputs generated from the sLocationDetails parsing (a,b,c d)
iLongitude tuser.longitude%TYPE;
iLatitude tuser.latitude%TYPE;
sLocation tuser.location%TYPE;
bSubmission boolean;
bOk boolean;
sFinalLocationDetails text;
sStem text;
sFinalUsername text;
sNormalised text;
sXML text;
iEntityId tentity.entityid%TYPE;
iCompanyId tlcompany.companyid%TYPE;
iUserId tuser.userid%TYPE;
--standard validation regex
sOptional text;
sEmailAddressRequired text;
sEmailAddressOptional text;
sTelephoneOptional text;
sNumeric text;
sNumericOptional text;
begin
bSubmission := not sSubmit = ''; --date sent through (data itself might be blank and valid)
bOk := true; --validation errors?
sXML := '<form_requirements submission="' || bSubmission || '">';
--standard validation regex
sOptional := '^$|';
sEmailAddressRequired := '^[^@]+@.+\\.[^.]+$';
sNumeric := '^[0-9]+$';
sEmailAddressOptional := sOptional || sEmailAddressRequired;
sTelephoneOptional := sOptional || '^[+]?[0-9 ()]+$';
sNumericOptional := sOptional || '^[0-9]+$';
--######################################## form fields ##############################################
--with optional validation
--in order
--email address
sXML := sXML || '<emailaddress caption="email address" required="' || sEmailAddressRequired || '" help="will be kept private" validation_error="email address not the right format, e.g. a@b.com">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sEmailAddress) || '</value>';
if bSubmission then
if not sEmailAddress ~ sEmailAddressRequired then bOk := false; sXML := sXML || '<validation_error><![CDATA[email address not the right format, e.g. a@b.com</validation_error>'; end if;
if exists(select * from tuser where emailaddress = lower(sEmailAddress)) then bOk := false; sXML := sXML || '<validation_error><![CDATA[email address already exists</validation_error>'; end if;
end if;
sXML := sXML || '</emailaddress>';
--username
sXML := sXML || '<username required=".+" help="will appear on the site">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sUserName) || '</value>';
if bSubmission then
if iUsernameGenerator = 0 then
--use the username field as is
if not sUserName ~ '.+' then bOk := false; sXML := sXML || '<validation_error><![CDATA[username required</validation_error>'; end if;
if exists(select * from tuser where username = sUserName) then bOk := false; sXML := sXML || '<validation_error><![CDATA[username already exists</validation_error>'; end if;
sFinalUsername := sUserName;
elsif iUsernameGenerator = 1 then
--use the username field as a stem for a generated username
sStem := sUserName;
sFinalUsername := unext_username(sStem);
elsif iUsernameGenerator = 2 then
--generate a username from the email address
sStem := substring(sEmailAddress from '[^@]+');
sFinalUsername := unext_username(sStem);
end if;
end if;
sXML := sXML || '</username>';
sXML := sXML || '<username_generator hide="1"><value><![CDATA[' || iUsernameGenerator || '</value></username_generator>';
--password
sXML := sXML || '<password required=".+">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sPassword) || '</value>';
if bSubmission and not sPassword ~ '.+' then bOk := false; sXML := sXML || '<validation_error><![CDATA[password required</validation_error>'; end if;
sXML := sXML || '</password>';
sXML := sXML || '<password_generator hide="1"><value><![CDATA[' || iPasswordGenerator || '</value></password_generator>';
--business name
sXML := sXML || '<businessname required=".+" caption="business name">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sBusinessName) || '</value>';
if bSubmission then
if not sBusinessName ~ '.+' then bOk := false; sXML := sXML || '<validation_error><![CDATA[business name required</validation_error>'; end if;
sNormalised := unormalise_companyname(sBusinessName);
if exists (select * from uexists_company_nameoralias(sNormalised)) then bOk := false; sXML := sXML || '<validation_error><![CDATA[business already exists</validation_error>'; end if;
end if;
sXML := sXML || '</businessname>';
--business type qualifier, e.g. restaurant
sXML := sXML || '<businesstypequalifier caption="business type qualifier" help="e.g. restaurant, bathroom fittings, pizza delivery, estate agents">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sBusinessTypeQualifier) || '</value>';
sXML := sXML || '</businesstypequalifier>';
--website (optional)
sXML := sXML || '<website help="e.g. example.com, will be made public">
<value><![CDATA[' || uxml_escapefor_cdata(sWebsite) || '</value>
</website>';
--pns_email (not required but needs validation if sent)
sXML := sXML || '<pns_email caption="products and services email address" required="' || sEmailAddressOptional || '" help="will be made public" validation_error="products and services email address not the right format, e.g. a@b.com">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sPnS_Email) || '</value>';
if bSubmission then
if not sPnS_Email ~ sEmailAddressOptional then bOk := false; sXML := sXML || '<validation_error><![CDATA[products and services email address sent but not the right format, e.g. a@b.com</validation_error>'; end if;
--if exists(select * from tuser where emailaddress = sPnS_Email) then bOk := false; sXML := sXML || '<validation_error><![CDATA[email address already exists</validation_error>'; end if;
end if;
sXML := sXML || '</pns_email>';
--pns_telephone (not required but needs validation if sent)
sXML := sXML || '<pns_telephone caption="products and services telephone number" required="' || sTelephoneOptional || '" help="will be made public" validation_error="products and services telephone must be numbers, spaces and an optionl plus only">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sPnSTelephone) || '</value>';
if bSubmission and not sPnSTelephone ~ sTelephoneOptional then bOk := false; sXML := sXML || '<validation_error><![CDATA[products and services telephone must be numbers, spaces and an optionl plus only</validation_error>'; end if;
sXML := sXML || '</pns_telephone>';
--geo
--user enters search location term in the area and then selects a location (2 part forced validation failure sequence)
sXML := sXML || '<area required=".+" default="London, Greater London" help="examples: N22 6QP, Brixton, London, City road, Hyde Park (all locations postpended with UK)" keep="1">';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sArea) || '</value>';
sXML := sXML || '</area>';
--if an area has been entered but a location is not selected then we have a validation issue
--if there is no area or location then the user has opted to not include it
sXML := sXML || '<location>';
sXML := sXML || '<value><![CDATA[' || uxml_escapefor_cdata(sLocationDetails) || '</value>';
if bSubmission then
sFinalLocationDetails := sLocationDetails;
if not (sArea = '') then --location search is optional
if sLocationDetails = '' then
--iGoogleStatus ignored here because we just use the points system
--however, 200 = Ok, 602 = not found
if iPointCount = 0 then bOk := false; sXML := sXML || '<validation_error><![CDATA[location not found</validation_error>'; end if;
if iPointCount = 1 then sFinalLocationDetails := sFirstPoint; end if;
if iPointCount > 1 then bOk := false; sXML := sXML || '<validation_error><![CDATA[please select a location</validation_error>'; end if;
end if;
end if;
end if;
sXML := sXML || '</location>';
--geo misc (optional)
sXML := sXML || '<neareststation caption="nearest station"><value><![CDATA[' || uxml_escapefor_cdata(sNearestStation) || '</value></neareststation>';
sXML := sXML || '<addressnotes caption="address notes"><value><![CDATA[' || uxml_escapefor_cdata(sAddressNotes) || '</value></addressnotes>';
--recaptcha (recaptcha analysis is always put first by the system although it appears elsewhere in the form)
sXML := sXML || '<recaptcha>';
if bSubmission and not bRecaptchaOk then bOk := false; sXML := sXML || '<validation_error><![CDATA[recaptcha did not match</validation_error>'; end if;
sXML := sXML || '</recaptcha>';
sXML := sXML || '</form_requirements>';
--######################################## action ##############################################
if bSubmission and bOk then
sXML := '<success>';
--geo
if not sFinalLocationDetails = '' then
iLongitude := substring(sFinalLocationDetails from '[-.0-9]+');
iLatitude := substring(sFinalLocationDetails from '[-.0-9]+ *, *([-.0-9]+)');
sLocation := substring(sFinalLocationDetails from '[-.0-9]+ *, *[-.0-9]+ *, *0 (.*)');
end if;
--create the account(s)
iEntityId := uadd_company(sNormalised, iLongitude, iLatitude, sLocation);
select into iCompanyId companyid from tlcompany where entityid = iEntityId;
iUserId := uadd_user('anonymous', '', '', sFinalUsername, sPassword, sEmailAddress, sSession, iLongitude, iLatitude, sLocation);
update tuser set type9c = sType9c, businessownerid = iCompanyId, system = 'SC' where userid = iUserId;
update tlcompany set businesstypequalifier = sBusinessTypeQualifier, website = regexp_replace(sWebsite, 'http://', '') where companyid = iCompanyId;
--return success (username and email unique already checked in this transaction)
sXML := sXML || uxml_user(iUserId);
sXML := sXML || uxml_company(sSession, sSchema, iVersion, iCompanyId, 0, 0);
--details for sending the email (not fields exactly: goes through an additional XSLT)
--user is advised of their username, password and verification code in the email
sXML := sXML || '<sendmail:email>
<sendmail:to><![CDATA[' || sFinalUsername || ' <' || uxml_escapefor_cdata(sEmailAddress) || '></sendmail:to>
<sendmail:guid><![CDATA[' || uxml_escapefor_cdata(sSession) || '</sendmail:guid>
<sendmail:username><![CDATA[' || uxml_escapefor_cdata(sFinalUsername) || '</sendmail:username>
<sendmail:password><![CDATA[' || uxml_escapefor_cdata(sPassword) || '</sendmail:password>
</sendmail:email>';
sXML := sXML || '</success>';
end if;
sXML := '<root>' || sXML || '</root>';
return sXML;
end;
-
ppp_societycard_index
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
rcd record;
rcd_com record;
sEndDefinition char(1);
iCompanyId integer;
begin
sXML := '<root>';
sXML := sXML || uxml_cms_values(sSessionId, sSchema, iVersion, '{
societycard_index_newsfeed,
societycard_index_strapline,
societycard_index_start,
societycard_index_find_pns,
societycard_index_buying_something,
societycard_index_register_transaction,
societycard_index_see_progress,
societycard_index_save_world,
societycard_index_browse_local_area,
societycard_index_specific_pns
}');
--cycle through all the companies that have or had a commitment
sXML := sXML || '<businesses>';
for rcd in select tc.companyid, te.entityid, te.createdate, qs.phrase, te.longitude, te.latitude, te.location, tc.voucherbookid, tu.userid, vi.*, tc.businesstypequalifier,
(
select pc.name from tcompany_producttype cpt
inner join tproducttype_producttype_category ppc on cpt.producttypeid = ppc.producttypeid
inner join tlproducttype_category pc on ppc.producttype_categoryid = pc.producttype_categoryid
where cpt.companyid = tc.companyid
limit 1
) as tlc, tc.icon,
tu.flickr_photoid, tu.youtube_videoid,
tu.message_short, tu.message_medium, tu.message_long,
tu.emailaddress, tu.blackballed
from tlcompany tc
inner join tentity te on tc.entityid = te.entityid
inner join tqualifierset qs on qs.qualifiersetid = te.namequalifiersetid
inner join tuser tu on tc.companyid = tu.businessownerid
inner join vinvestmentprogress vi on tc.companyid = vi.companyid
where exists (select * from tcommitment where companyid = tc.companyid)
--or exists (select * from tinvestement where companyid = tc.companyid)
order by te.createdate desc, tc.companyid desc
loop
iCompanyId := rcd.companyid;
sXML := sXML || '<business id="' || rcd.entityid || '" companyid="' || iCompanyId || '" userid="' || rcd.userid|| '" blackballed="' || rcd.blackballed || '" voucherbookid="' || coalesce(rcd.voucherbookid, 0) || '">
<businesstypequalifier><![CDATA[' || uxml_escapefor_cdata(rcd.businesstypequalifier) || '</businesstypequalifier>
<createdate><![CDATA[' || uxml_escapefor_cdata(uformatdate(rcd.createdate)) || '</createdate>';
if not rcd.tlc is null then sXML := sXML || '<tlc><![CDATA[' || uxml_escapefor_cdata(coalesce(rcd.tlc, '')) || '</tlc>'; end if;
if not rcd.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd.icon) || '</icon>'; end if; --don't include node if not available
if not rcd.youtube_videoid is null and not rcd.youtube_videoid = '' then
sXML := sXML || '<video><![CDATA[' || uxml_escapefor_cdata(rcd.youtube_videoid) || '</video>';
end if;
if not rcd.flickr_photoid is null and not rcd.flickr_photoid = '{}' then
sXML := sXML || '<photo>
<farm><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[1]) || '</farm>
<server><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[2]) || '</server>
<id><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[3]) || '</id>
<secret><![CDATA[' || uxml_escapefor_cdata(rcd.flickr_photoid[4]) || '</secret>
</photo>';
end if;
sXML := sXML || '<point latitude="' || rcd.latitude || '" longitude="' || rcd.longitude || '"><![CDATA[' || uxml_escapefor_cdata(rcd.location) || '</point>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</name>';
sXML := sXML || '<emailaddress><![CDATA[' || uxml_escapefor_cdata(rcd.emailaddress) || '</emailaddress>';
sXML := sXML || '<messages>'
|| coalesce('<short>' || uxml_parsexml(rcd.message_short) || '</short>', '')
|| coalesce('<medium>' || uxml_parsexml(rcd.message_medium) || '</medium>', '')
|| coalesce('<long>' || uxml_parsexml(rcd.message_long) || '</long>', '')
|| '</messages>';
--progress
sXML := sXML || '<progress target="' || rcd.target || '" startdate="' || rcd.startdate || '" invested="' || rcd.invested || '" recieved="' || rcd.recieved || '"/>';
--commitments
sXML := sXML || '<commitments>';
for rcd_com in select * from tcommitment com
where companyid = iCompanyId
order by commitmentid desc --latest first
loop
if rcd_com.enddate is null then sEndDefinition = 'T';
elsif rcd_com.enddate = rcd_com.startdate then sEndDefinition = 'F';
else sEndDefinition = 'E';
end if;
sXML := sXML ||
'<commitment id="' || rcd_com.commitmentid || '" enddefinition="' || sEndDefinition || '" report="' || (rcd_com.specific = '') || '" percentage="' || rcd_com.percentage || '" target="' || coalesce(rcd_com.target, 0) || '">
<startdate><![CDATA[' || coalesce(uxml_escapefor_cdata(rcd_com.startdate), '') || '</startdate>
<enddate><![CDATA[' || coalesce(uxml_escapefor_cdata(rcd_com.enddate), '') || '</enddate>
<specific><![CDATA[' || coalesce(uxml_escapefor_cdata(translate(rcd_com.specific, '\n\r', ' ')), '') || '</specific>
</commitment>';
end loop;
sXML := sXML || '</commitments>';
--products and services
sXML := sXML || '<pnss>';
for rcd_com in select te.entityid, pt.producttypeid, qs.phrase, pt.icon, cpt."order"
from tcompany_producttype cpt
inner join tlproducttype pt on cpt.producttypeid = pt.producttypeid
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
where cpt.companyid = iCompanyId
order by cpt."order", cpt.createdate
loop
sXML := sXML ||
'<pns id="' || rcd_com.entityid || '" producttypeid="' || rcd_com.producttypeid || '" order="' || rcd_com.order || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd_com.phrase) || '</name>';
if not rcd_com.icon is null then sXML := sXML || '<icon><![CDATA[' || uxml_escapefor_cdata(rcd_com.icon) || '</icon>'; end if; --don't include node if not available
sXML := sXML || '</pns>';
end loop;
sXML := sXML || '</pnss>';
sXML := sXML || '</business>';
end loop;
sXML := sXML || '</businesses></root>';
return sXML;
end;
-
ppp_societycard_session
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sSiteroot alias for $4;
sUserAgent alias for $5;
iSessionId integer;
bExists boolean;
iUserId integer;
iCompanyId integer;
iEntityId integer;
sXML text;
begin
bExists := usession_exists(sSessionId);
iSessionId := usession_autocreate(sSessionId, sSiteroot, sUserAgent); --will auto-create linked to the domain if necessary
if sSchema = 'bare' then
select into sXML '<session>' from tsession where sessionid = iSessionId;
else
select into sXML '<session
id="' || sessionid || '"
string="' || sessionstring || '"
new="' || (not bExists) || '"
autosaveentities="' || autosaveentities || '"
autosavearticles="' || autosavearticles || '">'
from tsession where sessionid = iSessionId;
end if;
sXML := sXML || '<authentication>';
iUserId := usession_userid(sSessionId);
if iUserId is null then
sXML := sXML || '<nouser/>';
else
if sSchema = 'bare' then sXML := sXML || '<user />';
else sXML := sXML || uxml_user(iUserId);
end if;
--see if business user
select into iCompanyId, iEntityId businessownerid, entityid
from tuser tu
inner join tlcompany tc on tu.businessownerid = tc.companyid
where tu.userid = iUserId;
if not iCompanyId is null then
sXML := sXML || '<business id="' || iEntityId || '" companyid="' || iCompanyId || '"/>';
end if;
end if;
sXML := sXML || '</authentication>';
sXML:= sXML || '</session>';
return sXML;
end;
-
ppp_societycard_supplier_account_register
(
25, 25, 23, 16, 25, 23, 23, 25, 25, 25, 23, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_societycard_includes_register($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, 'SUP', $25);
-
ppp_societycard_supplier_contactus
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
select ppp_easyethical_contactus($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25);
-
ppp_societycard_typeahead_pns_search
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sText alias for $4;
sXML text;
rcd record;
begin
sXML := '<root><options>';
--will be auto-converted into a javascript array []
for rcd in select 1 as entrytype, ptc.producttype_categoryid as id, ptc.name, 0 as count
from tlproducttype_category ptc
where lower(ptc.name) like('%' || lower(sText) || '%')
union all
select 2 as entrytype, pt.producttypeid as id, qs.phrase, count(cpt.producttypeid)
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left outer join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
where lower(qs.phrase) like('%' || lower(sText) || '%')
group by entrytype, pt.producttypeid, qs.phrase
order by count desc
limit 50
loop
sXML := sXML || '<option type="' || rcd.entrytype || '" id="' || rcd.id || '" count="' || rcd.count || '"><![CDATA[' || uxml_escapefor_cdata(rcd.name) || ' (' || rcd.count || ')</option>';
end loop;
sXML := sXML || '</options></root>';
return sXML;
end;
-
ppp_societycard_typeahead_website_search
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sText alias for $4;
sXML text;
rcd record;
begin
sXML := '<root><options>';
sXML := sXML || '<categories_top>';
for rcd in select ptc.producttype_categoryid as id, ptc.name, 0 as count
from tlproducttype_category ptc
where lower(ptc.name) like('%' || lower(sText) || '%')
and ptc.producttype_categoryid > 0
limit 50
loop
sXML := sXML || '<option id="' || rcd.id || '" count="' || rcd.count || '"><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</option>';
end loop;
sXML := sXML || '</categories_top>';
sXML := sXML || '<categories_full>';
for rcd in select pt.producttypeid as id, qs.phrase as name, count(cpt.producttypeid)
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left outer join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
where lower(qs.phrase) like('%' || lower(sText) || '%')
group by pt.producttypeid, qs.phrase
having count(cpt.producttypeid) > 0
order by count desc
limit 50
loop
sXML := sXML || '<option id="' || rcd.id || '" count="' || rcd.count || '"><![CDATA[' || uxml_escapefor_cdata(rcd.name) || ' (' || rcd.count || ')</option>';
end loop;
sXML := sXML || '</categories_full>';
sXML := sXML || '<categories_empty>';
for rcd in select pt.producttypeid as id, qs.phrase as name, count(cpt.producttypeid)
from tlproducttype pt
inner join tentity te on pt.entityid = te.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
left outer join tcompany_producttype cpt on pt.producttypeid = cpt.producttypeid
where lower(qs.phrase) like('%' || lower(sText) || '%')
group by pt.producttypeid, qs.phrase
having count(cpt.producttypeid) = 0
order by count desc
limit 50
loop
sXML := sXML || '<option id="' || rcd.id || '" count="' || rcd.count || '"><![CDATA[' || uxml_escapefor_cdata(rcd.name) || ' (' || rcd.count || ')</option>';
end loop;
sXML := sXML || '</categories_empty>';
sXML := sXML || '</options></root>';
return sXML;
end;
-
pqualifierset_entities
()
select
te.entityid,
uentitytype(te.entityid),
uqualifierset_name(tqs.qualifiersetid, 0, 0),
uiscommonsingleword(tqs.qualifiersetid)
from tentity_qualifierset tqs inner join tentity te on tqs.entityid = te.entityid
where te.moderation = 'M'
order by uqualifierset_name(qualifiersetid, 0, 1),
(select count(*) from tqualifierword tqw where tqw.qualifiersetid = tqs.qualifiersetid) desc
-
pregisterfeeder
()
declare
sName alias for $1;
iMajorversion alias for $2;
iMinorversion alias for $3;
iBuildid alias for $4;
sVersionname alias for $5;
iFeederid tfeederprogram.feederid%TYPE;
begin
select into iFeederid feederid from tfeederprogram where
name = sName
and majorversion = iMajorversion
and minorversion = iMinorversion
and buildid = iBuildid
and versionname = sVersionname;
if not found then
insert into tfeederprogram(name, majorversion, minorversion, buildid, versionname)
values(sName, iMajorversion, iMinorversion, iBuildid, sVersionname);
select into iFeederid currval('seqfeederid');
end if;
return iFeederid;
end;
-
ptagfilters
()
select filterid, filterid, filter, exceptions, ''::text, uqualifierset_name(tagqualifiersetid, 0, 0), 1, false
from txtagfilter tf inner join ttag tt on tf.tagid = tt.tagid
where enable=true
-
pxadd_tagfilter
()
declare
iFeederId alias for $1;
sTag alias for $2;
sFilter alias for $3;
sExceptions alias for $4;
iRelevancyId alias for $5;
iNegativity alias for $6;
iTagQualifierSetId tarticle_tag.tagqualifiersetid%TYPE;
begin
--check to see if the qualifier set exists yet
iTagQualifierSetId := uexists_qualifierset(sTag);
if iTagQualifierSetId is null then
--make a new one
iTagQualifierSetId := uadd_qualifierset(iFeederId, sTag);
end if;
insert into txtagfilter(tagqualifiersetid, filter, exceptions, relevancyid, negativity)
values(iTagQualifierSetId, sFilter, sExceptions, iRelevancyId, iNegativity);
return 0;
end;
-
pxml_adminword
()
declare
iWordId alias for $1;
rcdMeaning record;
sMeaning text;
sXML text;
begin
select into sXML '<word uniqueId="' || iWordId || '" markupPolicy="0" stopword="' || tw.stopword || '"><![CDATA[' || uxml_escapefor_cdata(tw.word) || ''
from tword tw
where tw.wordid = iWordId;
--meanings
sXML := sXML || '<meanings>';
for rcdMeaning in select twns.name, twn.special, twn.definition, twn.wordcount, twn.commonality
from twordnet twn, twordnetsense twns
where twn.senseid = twns.senseid
and wordid = iWordId loop
sMeaning = rcdMeaning.name;
sXML := sXML || '<' || sMeaning || ' wordCount="' || rcdMeaning.wordcount || '" special="' || rcdMeaning.special || '" commonality="' || rcdMeaning.commonality || '">
<![CDATA[' || uxml_escapefor_cdata(rcdMeaning.definition) || '
</' || sMeaning || '>';
end loop;
sXML := sXML || '</meanings>';
sXML := sXML || '</word>';
return sXML;
end;
-
pxml_adminword
()
select pxml_adminword(wordid) from tword where word = lower(cast($1 as text))
-
pxobjectparsersettings
()
select * from txobjectparsersetting where pagegroupid = $1
order by propertyid
-
pxpagegroup
()
select pagegroupid,
pagegroupfilter,
externalsourceid,
cleanerfilter_header,
sectionfilter,
outputfilter,
"enable",
description,
parsertype,
headingfilter_level1,
headingfilter_level2,
exceptionsregxx,
typeid,
cleanerfilter_footer,
cleanerfilter_other
from txpagegroup
where externalsourceid = $1 and enable
order by pagegroupid
-
regexp_replace
()
select regexp_replace($1, $2, '');
-
regexp_replace
()
select regexp_replace($1, $2, $3, 1) --default to case insensitive
-
regexp_replace
()
DECLARE
sSource alias for $1;
sPattern alias for $2;
sReplacement alias for $3;
iFlags alias for $4;
--substring(...) finds the *1st* match in the string so we need
--to loop through all of them to properly replace everything
sFlagPattern text;
bMultipass boolean; --whether to loop running the replacement until there are none more to do
sNewstring text; --the current body that is having replacements found and done
sFound text; --the string found in the body that needs replacing
sBackRefReplace text; --the replacement with back refs to put in each time
begin
sNewstring := sSource;
sFlagPattern := sPattern;
if version_major() > 7.3 then --7.4 onwards supports flags in patterns
if iFlags & 1 then sFlagPattern := '(?i)' || sFlagPattern; end if; --flags 1 indicates case insensitive
end if;
--if the pattern matches the replacement then we should not loop because it will constantly find the replacement
--if the pattern does not match then null is returned, pattern can correctly return a match of an empty string eg(.*)eg
bMultipass := (substring(sReplacement from sFlagPattern) is null) or (substring(sReplacement from sFlagPattern) = '');
loop
sFound := substring(sNewstring from sFlagPattern); --get the \\0 (or \\1 if there are brackets) found
exit when sFound is null or sFound = ''; --we have to exit on null or '' because of infinite looping (we cannot replace '')
sBackRefReplace := replace(sReplacement, '\\1', sFound); --this allows \\1 back references
sNewstring := replace(sNewstring, sFound, sBackRefReplace); --replace the \\1 substitution
exit when not bMultipass;
end loop;
return sNewstring;
end;
-
uacronym
()
declare
sName alias for $1;
sAcronym text;
begin
sAcronym := uacronym_dot(sName);
sAcronym := regexp_replace(sAcronym, '\\.');
return sAcronym;
end;
-
uacronym_ampersand
()
declare
sName alias for $1;
sAcronym text;
begin
sAcronym := sName;
if not uisacronym(sAcronym) then
sAcronym := initcap(sAcronym);
--convert and to ampersand
sAcronym := regexp_replace(sAcronym, ' And ', ' & ');
--replace anything that is not a capital letter or an ampersand
sAcronym := regexp_replace(sAcronym, '[^A-Z&]+');
end if;
return sAcronym;
end;
-
uacronym_dot
()
declare
sName alias for $1;
sAcronym text;
begin
sAcronym := sName;
if not uisacronym(sAcronym) then
sAcronym := initcap(sAcronym);
--ignore certain common words
sAcronym := regexp_replace(sAcronym, ' And ');
--replace anything that is not a capital letter or a number
sAcronym := regexp_replace(sAcronym, '[^A-Z.]+', '.');
sAcronym := regexp_replace(sAcronym, '\\.{2,}', '.');
end if;
return sAcronym;
end;
-
uadd_commitment
(
23, 25, 23, 23, 1184, 1184, 23
)
declare
iCompanyId alias for $1;
sSpecificItem alias for $2;
iPercentageRevenue alias for $3;
iInitialInvestement alias for $4;
dStartDate alias for $5;
dEndDate alias for $6;
iTarget alias for $7;
iCommitmentId tcommitment.commitmentid%TYPE;
begin
insert into tcommitment(companyid, specific, percentage, initial, startdate, enddate, target)
values(iCompanyId, sSpecificItem, iPercentageRevenue, iInitialInvestement, dStartDate, dEndDate, iTarget);
iCommitmentId := currval('seqcommitmentid');
return iCommitmentId;
end;
-
uadd_company
()
declare
sName alias for $1;
iLongitude alias for $2;
iLatitiude alias for $3;
sLocation alias for $4;
sNormalised text;
iEntityId integer;
begin
sNormalised := unormalise_companyname(sName);
if not exists (select * from uexists_company_nameoralias(sNormalised)) then
select into iEntityId uadd_entity(sNormalised, 'SC');
update tentity set longitude = iLongitude, latitude = iLatitiude, location = sLocation where entityid = iEntityId;
insert into tlcompany(entityid) values(iEntityId);
end if;
return iEntityId;
end;
-
uadd_entity
()
select uadd_entity($1, $2, 'M')
-
uadd_entity
()
declare
sName alias for $1;
sSystem alias for $2;
iEntityId tentity.entityid%TYPE;
begin
iEntityId := uadd_entity(0, 0, sName, 'M');
update tentity set system = sSystem where entityid = iEntityId;
return iEntityId;
end;
-
uadd_entity
()
declare
iMarkupPolicyId alias for $1;
iNameQualifierSetId alias for $2;
iFeederId alias for $3;
iEntityId tentity.entityid%TYPE;
begin
--qualifier set already exists, just link to it
insert into tentity(markupPolicyid, namequalifiersetid, feederid) values(iMarkupPolicyId, iNameQualifierSetId, iFeederId);
select into iEntityId currval('seqentityid');
insert into tentity_qualifierset(entityid, qualifiersetid) values(iEntityId, iNameQualifierSetId);
return iEntityId;
end;
-
uadd_entity
()
select uadd_entity($1, $2, $3, 'M')
-
uadd_entity
()
declare
iFeederId alias for $1;
iMarkupPolicyId alias for $2;
sModeration alias for $3;
begin
insert into tentity(markupPolicyid, feederid, moderation) values(iMarkupPolicyId, iFeederId, sModeration);
return currval('seqentityid');
end;
-
uadd_entity
()
declare
iMarkupPolicyId alias for $1;
sName alias for $2;
iFeederId alias for $3;
iEntityId tentity.entityid%TYPE;
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
begin
insert into iEntityId uadd_entity(iMarkupPolicyId, iFeederId);
select into iQualifierSetId uset_entityname(iEntityId, sName);
return iEntityId;
end;
-
uadd_entity
()
declare
iFeederId alias for $1;
iMarkupPolicyId alias for $2;
sName alias for $3;
sModeration alias for $4;
iEntityId tentity.entityid%TYPE;
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
begin
iEntityId := uadd_entity(iFeederId, iMarkupPolicyId, sModeration);
select into iQualifierSetId uset_entityname(iFeederId, iEntityId, sName);
return iEntityId;
end;
-
uadd_qualifierset
()
DECLARE
iFeederId alias for $1;
sWords alias for $2; --text (dirty: normalise this prior to calling this function)
sLower text;
aWords text[]; --text[] version (clean)
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
iWordId tword.wordid%TYPE;
sElement text;
iLen int4;
iPosition int4;
begin
--create qualifierset with dirty version of the phrase
insert into tqualifierset(phrase) values(sWords);
select into iQualifierSetId currval('seqqualifiersetid');
--now index the words for the clean fast version
sLower := lower(sWords); --tword is all lowercase (CHECK Constraint)
aWords := array_fromtext(sLower, 3); --space and grammar delimited e.g. Tesco-Ltd = {Tesco,Ltd}
iLen := array_upper(aWords, 1);
iPosition := 1;
if not iLen is null then
for i in 1..iLen loop
sElement := aWords[i];
--ignore blank words {,,}
if not sElement is Null and not sElement = '' then
iWordId := uexists_word(sElement);
if iWordId is null then
iWordId := padd_word(iFeederId, sElement);
end if;
--if the word has numbers or grammar it can be refused
if not iWordId is null then
insert into tqualifierword(qualifiersetid, wordid, position)
values(iQualifierSetId, iWordId, iPosition);
iPosition := iPosition + 1;
end if;
end if;
end loop;
end if;
return iQualifierSetId;
end;
-
uadd_tag
()
select uadd_tag($1, $2, $3, $4, 0)
-
uadd_tag
()
DECLARE
iFeederId alias for $1;
iArticleId alias for $2;
sTag alias for $3;
cType alias for $4;
iPosition alias for $5;
sNormalised text;
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
iTagId ttag.tagid%TYPE;
iTagGroupId ttaggroup.taggroupid%TYPE;
begin
sNormalised := unormalise_tag(sTag); --lower and grammar
--add the qualifierset if it doesn't already exist
if not sNormalised is null and not sNormalised = '' then
select into iTagId uexists_tag from uexists_tag(sNormalised); --tags should be unique so this can only ever return 1 record
if iTagId is null then
--it is a new tag with no auto-taggroup so add one for it
select into iTagGroupId uexists_taggroup from uexists_taggroup(sNormalised);
if iTagGroupId is null then
insert into ttaggroup(tag) values(sNormalised);
iTagGroupId := currval('seqtaggroupid');
end if;
select into iQualifierSetId uadd_qualifierset(iFeederId, sNormalised);
insert into ttag(taggroupid, tagqualifiersetid, tagtype) values(iTagGroupId, iQualifierSetId, cType);
iTagId := currval('seqtagid');
end if;
--avoid duplicates
if not exists(select * from tarticle_tag where articleid = iArticleId and tagid = iTagId) then
insert into tarticle_tag(articleid, tagid, feederid, "position")
values(iArticleId, iTagId, iFeederId, iPosition);
end if;
end if;
return iTagId;
end;
-
uadd_tags
()
declare
iFeederId alias for $1;
iArticleId alias for $2;
aTags alias for $3; --text[] array of dirty texts
cType alias for $4;
iTags integer;
sTag text; --dirty text
begin
iTags := array_upper(aTags, 1);
if not iTags is null then
for i in 1..iTags loop
sTag := aTags[i];
perform uadd_tag(iFeederId, iArticleId, sTag, cType, i);
end loop;
end if;
return iTags;
end;
-
uadd_to_emaillist
()
declare
sListID alias for $1;
sEmailAddress alias for $2;
begin
if not exists (select * from temaillist where listid = sListID and emailaddress = sEmailAddress) then
insert into temaillist(listid, emailaddress) values(sListID, sEmailAddress);
end if;
return 0;
end;
-
uadd_user
(
25, 25, 25, 25, 25, 25, 25, 701, 701, 25
)
declare
sFirstName alias for $1;
sMiddleName alias for $2;
sLastName alias for $3;
sUserName alias for $4;
sPassword alias for $5;
sEmailAddress alias for $6;
sVerificationId alias for $7;
iLongitude alias for $8;
iLatitude alias for $9;
sLocation alias for $10;
sXML text;
iUserId tuser.userid%TYPE;
begin
if not exists (select * from tuser where username = sUserName or emailaddress = sEmailAddress) then
insert into tuser(firstname, middlename, lastname, username, encryptedpassword, emailaddress, verificationid, longitude, latitude, location, area)
values(sFirstName, sMiddleName, sLastName, sUserName, md5(sPassword), lower(sEmailAddress), sVerificationId, iLongitude, iLatitude, sLocation, sLocation);
iUserId := currval('sequserid');
end if;
return iUserId;
end;
-
uanalysedoc
()
declare
sDoc alias for $1;
sNormalisedDoc text;
sSentence text;
sWord text;
iSentence integer;
iWord integer;
cFirstLetter character(1);
iWordId tword.wordid%TYPE;
iQualifierSetId integer;
bMatched boolean;
rQSs record; --limited set of QSs that satisfy the first word
rQS record; --specific QS being checked
begin
--this is done in the database because there is much looking up to be done
--a C++/SPI function would be better but we are on a shared hosted server...
--performance is everything (plsql does not help though!)
--we only really care about sentences and words in this analysis
--so replace everything that we consider a sentence end with a . to make things simpler
sNormalisedDoc := unormalise_article(sDoc);
--now we have a normalised document of words, numbers, spaces, dashes and full stops
--loop through the sentences
iSentence := 1;
sSentence := unormalise_whitespace(split_part(sNormalisedDoc, '.', iSentence));
while not sSentence = '' loop
--loop through the words (index 1 is the first word in the sentence and is thus special in terms of capital first letter)
iWord := 1;
sWord := split_part(sSentence, ' ', iWord);
while not sWord = '' loop
cFirstLetter := substring(sWord from 1 for 1);
if upper(cFirstLetter) = cFirstLetter then
--ok, we have a name word
--look for this in the word DB (if it is part of an entity name then it will be there)
iWordId := uexists_word(sWord);
if not iWordId is null then
--use a select to find a subset of QSs that have the right first word (fast and limiting)
--use the cursor to loop through the QSs checking the remaining words (slow but on limited results)
for rQSs in select qw.qualifiersetid, (select max(position) from tqualifierword where qualifiersetid = qw.qualifiersetid) as maxposition
from tqualifierword qw
inner join tentity_qualifierset eq on qw.qualifiersetid = eq.qualifiersetid
where qw.position = 1
and qw.wordid = iWordId
order by maxposition desc
loop
--cursor to loop through the limited set of QSs to check their remaining words
iQualifierSetId := rQSs.qualifiersetid; --current qualifierset to analyse
bMatched := true; --if the QS only has one word
for rQS in select word, position from tqualifierword qw
inner join tword tw on qw.wordid = tw.wordid
where qw.qualifiersetid = iQualifierSetId
and position > 1
loop
sWord := split_part(sSentence, ' ', iWord + rQS.position - 1);
bMatched := false; --loop exit will have a false
exit when not lower(sWord) = rQS.word; --exit if any of the words do not match
bMatched := true; --loop finish (only when all words satisfied) will have a true
end loop;
--check if all the words matched
if bMatched then
return next iQualifierSetId; --return this set
iWord := iWord + rQSs.maxposition - 1; --jump qualifier set in sentence
exit; --matching qualifier set found, don't want to return shorter ones...
end if;
end loop;
end if;
end if;
iWord := iWord + 1;
sWord := split_part(sSentence, ' ', iWord);
end loop;
iSentence := iSentence + 1;
sSentence := unormalise_whitespace(split_part(sNormalisedDoc, '.', iSentence));
end loop;
return;
end;
-
uautocompanyaliases
()
select * from uautocompanyaliases(uentityname($1))
-
uautocompanyaliases
()
declare
sName alias for $1;
rcd record;
begin
if not uisacronym(sName) then
for rcd in select distinct uautocompanyaliases_names from uautocompanyaliases_names(sName) loop
return next rcd.uautocompanyaliases_names;
end loop;
for rcd in select distinct uautocompanyaliases_acronyms from uautocompanyaliases_acronyms(sName) loop
return next rcd.uautocompanyaliases_acronyms;
end loop;
end if;
return;
end;
-
uautocompanyaliases_acronyms
()
declare
sName alias for $1;
sLower text;
sAlias text;
sAcronym text;
begin
if not uisacronym(sName) then
sLower := lower(sName);
--remove non-acronym type stuff
sAlias := regexp_replace(sLower, ' (ltd )| ltd$');
sAlias := regexp_replace(sAlias, ' (plc )| plc$');
--sAlias := regexp_replace(sAlias, ' (corporation )| corporation$');
--sAlias := regexp_replace(sAlias, ' (stores )| stores$');
--sAlias := regexp_replace(sAlias, ' (bank )| bank$');
--acronyms (minimum 3 letters): the acronym function will remove 'And's
sAcronym := uacronym(sAlias);
if char_length(sAcronym) > 2 then return next sAcronym; end if;
sAcronym := uacronym_dot(sAlias);
if char_length(sAcronym) > 4 then return next sAcronym; end if;
sAcronym := uacronym_ampersand(sAlias);
if char_length(sAcronym) > 2 then return next sAcronym; end if;
end if;
return;
end;
-
uautocompanyaliases_names
()
declare
sName alias for $1;
sCapitals text;
sLower text;
sAlias text;
sAlias1 text;
sAlias2 text;
sAlias3 text;
rcdCountry record;
sCountryName text;
sCountryPattern text;
begin
if not uisacronym(sName) then
sLower := lower(sName);
--dual names name1/name2 format
if position('/' in sName) then
sAlias1 := substring(sName from '([^/]+)/');
sAlias2 := substring(sName from '/(.*)$');
if not sAlias1 = '' then return next sAlias1; end if;
if not sAlias2 = '' then return next sAlias2; end if;
end if;
--camel case to spaced (McDonalds -> Mc Donalds)
sAlias := sName;
sAlias := regexp_replace(sAlias, '[A-Z][a-z]+([A-Z][a-z]+)', ' \\1');
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--camel case to dashed (McDonalds -> Mc-Donalds)
sAlias := sName;
sAlias := regexp_replace(sAlias, '[A-Z][a-z]+([A-Z][a-z]+)', '-\\1');
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--Mc -> Mc.
sAlias := sName;
sAlias := regexp_replace(sAlias, 'Mc(\\.)[A-Z]');
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--Mc. -> Mc
sAlias := sName;
sAlias := regexp_replace(sAlias, '(Mc)[A-Z]', 'Mc.');
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--Co-op -> coop
sAlias := sLower;
sAlias := regexp_replace(sAlias, 'co-op', 'coop');
if not sAlias = sLower and not sAlias = '' then return next initcap(sAlias); end if;
--Coop -> co-op
sAlias := sLower;
sAlias := regexp_replace(sAlias, 'coop', 'co-op');
if not sAlias = sLower and not sAlias = '' then return next initcap(sAlias); end if;
--Co-?op -> cooperative
sAlias := sLower;
sAlias := regexp_replace(sAlias, ' (co-?op )| co-?op$', ' cooperative');
if not sAlias = sLower and not sAlias = '' then return next initcap(sAlias); end if;
--Bros -> brothers
sAlias := sLower;
sAlias := regexp_replace(sAlias, ' (bros )| bros$', ' brothers');
if not sAlias = sLower and not sAlias = '' then return next initcap(sAlias); end if;
sAlias := sLower;
--common latin extension mistakes Nestle instead of Nestlé
sAlias := sLower;
sAlias := regexp_replace(sAlias, 'é', 'e');
if not sAlias = sLower and not sAlias = '' then return next initcap(sAlias); end if;
--change existing capitals, put dots in between e.g. EH Industries -> E.H. Industries
sCapitals := substring(sName from '[A-Z]{2,}');
sAlias := replace(sName, sCapitals, regexp_replace(sCapitals, '([A-Z])[^.]|[A-Z]$', '\\1.'));
sAlias := unormalise_whitespace(sAlias);
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--change existing capitals, put dots in between e.g. EH Industries -> E.H. Industries
sCapitals := substring(sName from '[A-Z]\\.[A-Z]\\.|[A-Z]\\.[A-Z]\\.[A-Z]\\.|[A-Z]\\.[A-Z]\\.[A-Z]\\.[A-Z]\\.');
sAlias := replace(sName, sCapitals, replace(sCapitals, '.', ''));
sAlias := unormalise_whitespace(sAlias);
if not sAlias = sName and not sAlias = '' then return next sAlias; end if;
--alias without Ltd, Plc, Corp (dots already removed)
sAlias1 := sLower;
sAlias1 := regexp_replace(sAlias1, ' (ltd )| ltd$');
sAlias1 := regexp_replace(sAlias1, ' (plc )| plc$');
sAlias1 := regexp_replace(sAlias1, ' (corporation )| corporation$');
sAlias1 := unormalise_whitespace(sAlias1);
if not sAlias1 = sLower and not sAlias1 = '' then return next initcap(sAlias1); end if;
--and drop common name parts
sAlias2 := regexp_replace(sAlias1, ' (stores )| stores$');
sAlias2 := regexp_replace(sAlias2, ' (bank )| bank$');
sAlias2 := unormalise_whitespace(sAlias2);
if not sAlias2 = sAlias1 and not sAlias2 = '' then return next initcap(sAlias2); end if;
--without country names
sAlias3 := sAlias2;
for rcdCountry in select uqualifierset_name(teq.qualifiersetid,0,0) as countryname
from tlcountry tc inner join tentity te on tc.entityid = te.entityid
inner join tentity_qualifierset teq on te.entityid = teq.entityid
loop
sCountryName := lower(rcdCountry.countryname);
sCountryPattern := ' (' || sCountryName || ' )| ' || sCountryName || '$';
sAlias3 := regexp_replace(sAlias3, sCountryPattern);
end loop;
if not sAlias3 = sAlias2 and not sAlias3 = '' then return next initcap(sAlias3); end if;
end if;
return;
end;
-
ucms_add
()
select ucms_add($1, $2, $3, $4, $5, '')
-
ucms_add
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sKey alias for $4;
sValue alias for $5;
sParentPage alias for $6;
iMaxVersion tcmsvalue.version%TYPE;
iID integer;
begin
--create if not already there
--add a new version if already there
select into iID cmsid
from tcms c
inner join tsession s on c.domainid = s.domainid and s.sessionstring = sSessionId
where cmskey = sKey;
if not found then
insert into tcms(domainid, cmskey, parentpage)
select domainid, sKey, sParentPage
from tsession where sessionstring = sSessionId;
if found then iID := currval('seqcmsid'); end if; --currval needs to be defined first
end if;
iID := ucms_addversion(sSessionId, sSchema, iVersion, iID, sValue, sParentPage);
return iID;
end;
-
ucms_addversion
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iID alias for $4;
sValue alias for $5;
sParentPage alias for $6;
iUserId tuser.userid%TYPE;
iMaxVersion tcmsvalue.version%TYPE;
begin
--add a new version
--assumes that the key exists
iUserId := usession_userid(sSessionId);
if not iUserId is null then
select into iMaxVersion max(version)
from tcmsvalue
where cmsid = iID;
insert into tcmsvalue(cmsid, version, value, userid) values(iID, coalesce(iMaxVersion, 0) + 1, sValue, iUserId);
end if;
return iID;
end;
-
ucms_query
()
select c.cmsid, c.cmskey, c.domainid, cv.value, c.template, c.proc, cv.userid
from tcms c
inner join tcmsvalue cv on c.cmsid = cv.cmsid
inner join tsession s on c.domainid = s.domainid and s.sessionstring = $1
where c.cmskey = 'CMS_' || $4
order by cv.version desc
limit 1
-
udistance
()
declare
long1 alias for $1;
lat1 alias for $2;
long2 alias for $3;
lat2 alias for $4;
DegToRad float8;
Ans float8;
Miles float8;
begin
DegToRad := 57.29577951;
Ans := 0;
Miles := 0;
Ans := sin(lat1 / DegToRad) * sin(lat2 / DegToRad) + cos(lat1 / DegToRad ) * cos( lat2 / DegToRad ) * cos(ABS(long2 - long1 )/DegToRad);
Miles := 3959 * atan(sqrt(1 - (Ans*Ans)) / Ans);
Miles := round(Miles::numeric, 2);
return Miles;
end;
-
uentity_phrase
()
select phrase from tqualifierset where qualifiersetid = (
select namequalifiersetid from tentity where entityid = $1
)
-
uentityname
()
select phrase from tqualifierset where qualifiersetid = (
select namequalifiersetid from tentity where entityid = $1
)
-
uentityname
()
select unormalise_entityname(uqualifierset_name(namequalifiersetid, $2, $3)) from tentity
where entityid = $1
-
uentityrequiresmoderation
()
select moderation = 'A' from tentity where entityid = $1
-
uentitytype
()
select (
sign(coalesce(t1.entityid, 0))*1
+ sign(coalesce(t2.entityid, 0))*2
+ sign(coalesce(t3.entityid, 0))*3
+ sign(coalesce(t4.entityid, 0))*4
+ sign(coalesce(t5.entityid, 0))*5
)::integer
from tentity te
left outer join tlcompany t1 on te.entityid = t1.entityid
left outer join tlcountry t2 on te.entityid = t2.entityid
left outer join tlperson t3 on te.entityid = t3.entityid
left outer join tlproduct t4 on te.entityid = t4.entityid
left outer join tlproducttype t5 on te.entityid = t5.entityid
where te.entityid = $1
-
uexists_carrotmob
()
declare
sName alias for $1;
begin
return;
end;
-
uexists_company
()
declare
sName alias for $1;
bCheckAliases alias for $2;
bCheckUniqueWords alias for $3;
sNormalised text;
rcd record;
begin
sNormalised := unormalise_companyname(sName); --grammar etc.
--direct entity qualifierset matches
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique (uexists_qualifierset run first before add)
for rcd in select distinct uexists_company_nameoralias from uexists_company_nameoralias(sNormalised) loop
return next rcd.uexists_company_nameoralias;
end loop;
--acronyms have no aliases or common matches
if not uisacronym(sNormalised) then
--check the aliases if we do not have a direct match
--e.g. Alliance, Technical and Testing = AT&T, or Tesco Stores = Tesco
if bCheckAliases then
for rcd in select distinct uexists_company_fromaliases from uexists_company_fromaliases(sNormalised) loop
return next rcd.uexists_company_fromaliases;
end loop;
end if;
--check for other entities sharing the same unique words
--e.g. Tesco = This Tesco Stores, because Tesco is not a common single word
if bCheckUniqueWords then
for rcd in select distinct uexists_company_uniquematches from uexists_company_uniquematches(sNormalised) loop
return next rcd.uexists_company_uniquematches;
end loop;
end if;
end if;
return;
end;
-
uexists_company_fromaliases
()
declare
sName alias for $1;
sNormalised text;
iEntityId integer;
rcd record;
rcd2 record;
begin
sNormalised := unormalise_companyname(sName); --grammar etc.
--acronyms have no aliases or common matches
if not uisacronym(sNormalised) then
--check the aliases if we do not have a direct match
--e.g. Alliance, Technical and Testing = AT&T, or Tesco Stores = Tesco
for rcd in select distinct uautocompanyaliases as alias from uautocompanyaliases(sNormalised) loop
for rcd2 in select uexists_qualifierset as qualifiersetid from uexists_qualifierset(rcd.alias) loop
select into iEntityId entityid
from tentity_qualifierset
where qualifiersetid = rcd2.qualifiersetid;
if not iEntityId is null then return next iEntityId; end if;
end loop;
end loop;
end if;
return;
end;
-
uexists_company_nameoralias
()
declare
sName alias for $1;
sNormalised text;
rcd record;
begin
sNormalised := unormalise_companyname(sName); --grammar etc.
--direct entity qualifierset matches on company
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique for companies (uexists_qualifierset run first before add)
--thus maximum only 1 match can be returned
for rcd in select distinct tc.entityid
from tlcompany tc inner join tentity_qualifierset eq on tc.entityid = eq.entityid
where qualifiersetid in(select uexists_qualifierset from uexists_qualifierset(sNormalised))
loop
return next rcd.entityid;
end loop;
return;
end;
-
uexists_company_uniquematches
()
declare
sName alias for $1;
sNormalised text;
iEntityId integer;
rcd record;
begin
sNormalised := unormalise_companyname(sName); --grammar etc.
--acronyms have no aliases or common matches
if not uisacronym(sNormalised) then
--check for other entities sharing the same unique words
--that are companies
--Note that uexists_uniquematches(...) tests *all* qualifiersets
--e.g. Tesco = This Tesco Stores, because Tesco is not a common single word
for rcd in select distinct uexists_uniquematches as entityid
from uexists_uniquematches(sNormalised)
inner join tlcompany tc on tc.entityid = uexists_uniquematches
loop
return next rcd.entityid;
end loop;
end if;
return;
end;
-
uexists_country
()
declare
sName alias for $1;
rcd record;
begin
--direct entity qualifierset matches
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique (uexists_qualifierset run first before add)
for rcd in select distinct tc.entityid
from tlcountry tc inner join tentity_qualifierset eq on tc.entityid = eq.entityid
where qualifiersetid in(select uexists_qualifierset from uexists_qualifierset(sName))
loop
return next rcd.entityid;
end loop;
return;
end;
-
uexists_externalsource
()
declare
sDomain alias for $1;
sNormalised text;
rcd record;
begin
sNormalised := unormalise_externalsource(sDomain); --grammar etc.
for rcd in select externalsourceid
from texternalsource
where not (position(sNormalised in lower(domain)) = 0 and position(sNormalised in lower(rootpagetitle)) = 0)
loop
return next rcd.externalsourceid;
end loop;
return;
end;
-
uexists_person
()
declare
sName alias for $1;
rcd record;
begin
--direct entity qualifierset matches
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique (uexists_qualifierset run first before add)
for rcd in select distinct tp.entityid
from tlperson tp inner join tentity_qualifierset eq on tp.entityid = eq.entityid
where qualifiersetid in(select uexists_qualifierset from uexists_qualifierset(sName))
loop
return next rcd.entityid;
end loop;
return;
end;
-
uexists_product
()
declare
sName alias for $1;
iCompanyId alias for $2;
rcd record;
begin
--direct entity qualifierset matches
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique (uexists_qualifierset run first before add)
for rcd in select distinct tp.entityid
from tlproduct tp inner join tentity_qualifierset eq on tp.entityid = eq.entityid
where qualifiersetid in(select uexists_qualifierset from uexists_qualifierset(sName))
and tp.maincompanyid = iCompanyId
loop
return next rcd.entityid;
end loop;
return;
end;
-
uexists_qualifierset
()
--lower case without grammar
select * from uexists_qualifierset(array_fromtext(lower($1), 3))
-
uexists_qualifierset
()
declare
aName alias for $1; --text[]
aLower text[];
sFirstName text; --aName[1]
iQualifierSetId tqualifierset.qualifiersetid%TYPE;
iWordId tword.wordid%TYPE;
rcd record;
begin
--words need to already have been cleaned (just [A-Za-z ])
--qualifiersets are not unique and are attached to companies, tags, etc.
--case insensitive
if not array_upper(aName, 1) is null then
aLower := lower(aName);
sFirstName := aLower[1];
--look for first word (word is always lower case)
select into iWordId wordid from tword where word = sFirstName; --index lookup
if not iWordId is null then
--check full match (uqualifierset_array results are always lower)
for rcd in select ts.qualifiersetid
from tqualifierset ts inner join tqualifierword tw
on ts.qualifiersetid = tw.qualifiersetid
where tw."position" = 1
and tw.wordid = iWordId
and uqualifierset_array(ts.qualifiersetid) = aLower
loop
return next rcd.qualifiersetid;
end loop;
end if;
end if;
return;
end;
-
uexists_tag
()
declare
sName alias for $1;
sNormalised text;
rcd record;
begin
sNormalised := unormalise_tag(sName); --grammar etc.
--direct entity qualifierset matches on company
--uexists_qualifierset() returns SETOF qualifiersetid
--entity qualifiersets should be unique for companies (uexists_qualifierset run first before add)
--thus maximum only 1 match can be returned
for rcd in select distinct tagid
from ttag where tagqualifiersetid in(select uexists_qualifierset from uexists_qualifierset(sNormalised))
loop
return next rcd.tagid;
end loop;
return;
end;
-
uexists_taggroup
()
declare
sName alias for $1;
rcd record;
begin
for rcd in select distinct taggroupid
from ttaggroup
where tag = sName
loop
return next rcd.taggroupid;
end loop;
return;
end;
-
uexists_uniquematches
()
declare
sName alias for $1;
aWords text[];
sWord text;
iLen integer;
iWordId tword.wordid%TYPE;
rcdQUalifierset record;
begin
aWords := array_fromtext(sName, 3);
iLen := array_upper(aWords, 1);
if not iLen is null then
--we have some words to test, loop through them
for i in 1..iLen loop
sWord := aWords[i];
if not sWord is null then
--valid word, test to see if it is in the system (if not then it is unique and not taken yet)
iWordId := uexists_word(sWord);
if not iWordId is null then
--word exists, so could be taken, see if it is common
if not exists (select * from twordnet where wordid = iWordId) then
--word is not common, but is already in the system: potential match
--add in all the entity qualifiersets that include this word
for rcdQUalifierset in select distinct teqs.entityid
from tentity_qualifierset teqs inner join tqualifierword tqw on teqs.qualifiersetid = tqw.qualifiersetid
where tqw.wordid = iWordId loop
return next rcdQUalifierset.entityid;
end loop;
end if;
end if;
end if;
end loop;
end if;
return;
end;
-
uexists_word
()
select wordid from tword where word = lower($1);
-
ufirst200words
()
select substring($1 from '^[ .,]*(([^ .,]*[ .,]+){0,200})')
-
ufirst45words
()
select substring($1 from '^[ .,]*(([^ .,]*[ .,]+){0,45})')
-
ufirstpara
()
select substring($1 from '<p>([^<]+)</p>')
-
uformatdate
()
select uformatdate($1, 1)
-
uformatdate
()
declare
dDate alias for $1;
iFormat alias for $2;
iInterval interval;
sText text;
begin
if iFormat = 1 then
--friendly date interval (for display only)
--e.g. 5 minutes ago
iInterval := age(now(), dDate);
if iInterval < '1 minute' then
sText := 'just now';
elsif iInterval < '5 minutes' then
sText := 'in the last 5 minutes';
elsif iInterval < '1 hour' then
sText := to_char(iInterval, 'FMMI') || ' minutes ago';
elsif iInterval < '5 hours' then
sText := 'at ' || to_char(dDate, 'HH:MI am') || ' today';
elsif iInterval < '1 day' then
sText := 'at ' || to_char(dDate, 'HH:MI am') || ' today';
elsif iInterval < '7 days' then
sText := 'last ' || to_char(dDate, 'day');
elsif iInterval < '1 month' then
sText := 'last ' || to_char(dDate, 'DD, mon');
elsif iInterval < '6 months' then
sText := 'last ' || to_char(dDate, 'DD, mon');
elsif iInterval < '1 year' then
sText := to_char(dDate, 'DD, mon, YYYY');
else
sText := to_char(dDate, 'mon, YYYY');
end if;
elsif iFormat = 2 then
--RFC 822 (rss standard: http://asg.web.cmu.edu/rfc/rfc822.html)
sText := to_char(dDate at time zone 'GMT', 'Dy, DD Mon YYYY HH:MI:SS GMT');
end if;
return sText;
end;
-
uisacronym
()
select $1 ~ '^[A-Z.]{3,}$'
-
uiscommonsingleword
()
declare
iQualifierSetId alias for $1;
iCount integer;
begin
--check if the name comprises only one word
if (select count(*) from tqualifierword where qualifiersetid = iQualifierSetId) = 1 then
--see if that word is in wordnet
if (select count(*)
from tqualifierword tqw
inner join tword tw on tqw.wordid = tw.wordid
inner join twordnet twn on tw.wordid = twn.wordid
where qualifiersetid = iQualifierSetId
and special = 0
) = 1 then
return true;
end if;
end if;
return false;
end;
-
unext_username
()
declare
sUsername alias for $1;
sStem text;
sMatch text;
iMax integer;
iLen integer;
sNextUsername text;
begin
--finds the next username
if not exists(select * from tuser where username = sUsername) then
sNextUsername := sUsername;
else
--uses the "stem" without numbers
sStem := regexp_replace(sUsername, '[0-9]+$');
sMatch := '^' || sStem || '[0-9]+$';
iLen := char_length(sStem);
select into iMax max(substring(username from iLen + 1)::integer)
from tuser
where username ~ sMatch;
sNextUsername := sStem || (coalesce(iMax, 0) + 1);
end if;
return sNextUsername;
end;
-
unormalise_article
()
--we can ignore grammar completely as we want only full single words and numbers e.g. 2nd chance
--full-stops are left as-is. They can have whitespace around them or not
--But there should not be repeat full-stops e.g. ....
--whitespace is NOT normalised
select replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(
$1, '<[^>]+>', '.'), --remove all HTML
'[:><,;()!?]', '.'), --change all sentence ends to full stops
'[^A-Za-z0-9. ''-]', ' '), --clear anything that is not words, spaces, a full stop or a single quote
'\\.[ .]+', '.'), --repeating sentence end with optional whitespace
'.', ' . ')
-
unormalise_companyname
()
declare
sName alias for $1;
sNormalised text;
begin
sNormalised := sName;
--note that this regexp_replace(...) makes only one pass and is not case sensitive
if not uisacronym(sNormalised) then
--company types (remove the dots) all case insensitive
sNormalised := regexp_replace(sNormalised, ' ltd\\.', ' ltd', 1);
sNormalised := regexp_replace(sNormalised, ' plc\\.', ' plc', 1);
sNormalised := regexp_replace(sNormalised, ' p\\.l\\.c\\.', ' plc', 1);
sNormalised := regexp_replace(sNormalised, ' corp\\.| corporation', ' corporation', 1);
sNormalised := unormalise_entityname(sNormalised);
end if;
return sNormalised;
end;
-
unormalise_companyname
()
declare
sName alias for $1;
sSpacedName text;
sNormalised text;
begin
--1 = space delimit
sSpacedName := array_totext(sName, 1); --space delimit
sNormalised := unormalise_companyname(sSpacedName); --normalised (ltd, stores, etc. removed)
return array_fromtext(sNormalised, 1); --back to an array
end;
-
unormalise_entityname
()
declare
sName alias for $1;
sNormalised text;
begin
sNormalised := sName;
if not uisacronym(sNormalised) then
--(...) qualifiers
sNormalised := regexp_replace(sNormalised, '\\([^)]*\\)');
sNormalised := regexp_replace(sNormalised, '[()]');
--grammar
sNormalised := unormalise_grammar(sNormalised);
end if;
return sNormalised;
end;
-
unormalise_entityname
()
declare
sName alias for $1;
sSpacedName text;
sNormalised text;
begin
--1 = space delimit
sSpacedName := array_totext(sName, 1); --space delimit
sNormalised := unormalise_entityname(sSpacedName); --normalised (ltd, stores, etc. removed)
return array_fromtext(sNormalised, 1); --back to an array
end;
-
unormalise_externalsource
()
declare
sDomain alias for $1;
sNormalised text;
begin
--removes all domain stuff from the name
sNormalised := lower(sDomain);
--note that this regexp_replace(...) makes only one pass and is not case sensitive
sNormalised := regexp_replace(sNormalised, '^.*://');
sNormalised := regexp_replace(sNormalised, '/.*');
sNormalised := replace(sNormalised, 'www.', '');
sNormalised := replace(sNormalised, '.com', '');
sNormalised := replace(sNormalised, '.co.uk', '');
sNormalised := replace(sNormalised, '.org.uk', '');
sNormalised := replace(sNormalised, '.org', '');
return sNormalised;
end;
-
unormalise_grammar
()
declare
sName alias for $1;
sNormalised text;
begin
--grammar
sNormalised := regexp_replace(sName, 'é', 'é'); --just in case of UTF-8 ISO8859 mistakes
sNormalised := regexp_replace(sNormalised, '&', ' and ');
sNormalised := unormalise_whitespace(sNormalised);
sNormalised := regexp_replace(sNormalised, '- ', '-');
sNormalised := regexp_replace(sNormalised, ' -', '-');
sNormalised := regexp_replace(sNormalised, '/ ', '/');
sNormalised := regexp_replace(sNormalised, ' /', '/');
sNormalised := regexp_replace(sNormalised, ' ,', ','); --remove spaces before commas
sNormalised := regexp_replace(sNormalised, '(,)[^ ]', ', '); --put a space after the comma
return sNormalised;
end;
-
unormalise_tag
()
declare
sName alias for $1;
sNormalised text;
begin
sNormalised := lower(sName); --tags are always lower case
sNormalised := unormalise_grammar(sNormalised);
--note that this regexp_replace(...) makes only one pass and is not case sensitive
return sNormalised;
end;
-
unormalise_whitespace
()
select trim(regexp_replace($1, '[
]{2,}', ' '))
-
uqualifierset_array
()
declare
iQualifierSetId alias for $1;
rWordRow record;
sWord tword.word%TYPE;
sName varchar := '{';
begin
for rWordRow in select tw.word from tqualifierword tqw, tword tw
where tqw.qualifiersetid = iQualifierSetId
and tqw.wordid = tw.wordid
order by tqw.position loop
sWord := rWordRow.word;
sName := sName || replace(replace(replace(sWord,'\\','\\\\'),',','\\,'),'\'','\\\'') || ',';
end loop;
if sName = '{' then
sName := '{0';
else
sName := substring(sName from 1 for char_length(sName)-1);
end if;
sName := sName || '}';
return sName;
end;
-
uqualifierset_idarray
()
declare
iQualifierSetId alias for $1;
rWordRow record;
iWordId tword.word%TYPE;
sName varchar := '{';
begin
for rWordRow in select wordid from tqualifierword
where qualifiersetid = iQualifierSetId
order by position loop
iWordId := rWordRow.wordid;
sName := sName || iWordId || ',';
end loop;
if sName = '{' then
sName := '{0';
else
sName := substring(sName from 1 for char_length(sName)-1);
end if;
sName := sName || '}';
return sName;
end;
-
uqualifierset_name
()
select uqualifierset_name($1,0,0)
-
uqualifierset_name
()
declare
iQualifierSetId alias for $1;
iMinPosition alias for $2;
iMaxPosition alias for $3; --0 indicates all of the text
rWordRow record;
sWord tword.word%TYPE;
sName text := '';
begin
for rWordRow in select tw.word from tqualifierWord tqw, tword tw
where tqw.qualifiersetid = iQualifierSetId
and tqw.wordid = tw.wordid
and tqw.position >= iMinPosition
and (iMaxPosition = 0 or tqw.position <= iMaxPosition)
order by tqw.position
loop
sWord := rWordRow.word;
sName := sName || sWord || ' ';
end loop;
--remove trailing space
if sName != '' then
sName := substring(sName from 1 for char_length(sName)-1);
end if;
return sName;
end;
-
uqualifierset_phrase
()
select phrase from tqualifierset where qualifiersetid = $1
-
userialise_article
()
DECLARE
iFeederId alias for $1;
iArticleId alias for $2;
sNormalise text; --text version (clean)
aWords text[]; --text[] version (clean)
iWordId tword.wordid%TYPE;
bStopword tword.stopword%TYPE;
sElement text;
iLen int4;
iPosition int4;
begin
--space and grammar delimited e.g. Tesco-Ltd = {Tesco,Ltd} with full-stops
--except the full-top: everything needs to pay attention to a sentence end
--e.g. Me in Rio. Tinto the dog played ball != Rio Tinto iLen := array_upper(aWords, 1);
select into aWords '{' || regexp_replace(replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(
lower(body), '<[^>]+>', '.'), --remove all HTML
'[:><,;()!?]', '.'), --change all sentence ends to full stops
'[^A-Za-z0-9. ''-]', ' '), --clear anything that is not words, spaces, a full stop or a single quote
'\\.[ .]+', '.'), --repeating sentence end with optional whitespace
'.', ' . '),
' +', ',')
|| '}'
from tarticle where articleid = iArticleId;
iLen := array_upper(aWords, 1);
iPosition := 1;
--clear existing serialisation
--note that for an entire re-serialisation you should truncate this table to reduce vacuum times
--delete from tarticle_word where articleid = iArticleId;
--insert new words
if not iLen is null then
for i in 1..iLen loop
sElement := aWords[i];
--ignore blank words {,,} short words and numbers. Full-stops are allowed
--position is updated anyway so that they cause a break
if not (sElement is Null or sElement = '' or sElement ~ '^[0-9]+$' or char_length(sElement) < 3 or sElement = '.') then
select into iWordId, bStopword wordid, stopword from tword where word = sElement;
if iWordId is null then
iWordId := padd_word(iFeederId, sElement);
bStopword := false;
end if;
--if the word has numbers or grammar it can be refused. Position will be updated anyway
--do not put stop words in because they are not needed. The position update will cause a gap
if not iWordId is null and bStopword = false then
insert into tarticle_word(articleid, wordid, position) values(iArticleId, iWordId, iPosition);
end if;
end if;
iPosition := iPosition + 1;
end loop;
end if;
return iPosition;
end;
-
usession_autocreate
()
declare
sSessionId alias for $1;
sSiteroot alias for $2;
sUserAgent alias for $3;
iSessionId integer;
begin
iSessionId := usession_id(sSessionId);
if iSessionId is null then
insert into tsession(domainid, sessionstring, useragent)
select domainid, sSessionId, sUserAgent from tdomain where sSiteroot in(name, siteroot);
iSessionId := currval('seqsessionid');
end if;
return iSessionId;
end;
-
usession_domainid
()
select domainid from tsession where sessionstring = $1;
-
usession_exists
()
select not(count(*) = 0) from tsession where sessionstring = $1;
-
usession_id
()
select sessionid from tsession where sessionstring = $1;
-
usession_isadmin
()
select usession_isingroup($1, 1)
-
usession_isingroup
()
select exists(
select * from tsession ts
inner join tusergroup_user tu on ts.userid = tu.userid
where sessionstring = $1
and tu.usergroupid = $2
)
-
usession_isloggedin
()
select count(*) = 1 from tsession where sessionstring = $1 and userid is not null
-
usession_login
()
declare
sSessionId alias for $1;
sUsername alias for $2;
sPassword alias for $3;
iUserId tuser.userid%TYPE;
begin
select into iUserId userid
from tuser
where username = sUsername
and encryptedpassword = md5(sPassword);
if found then
update tsession set userid = iUserId
where sessionstring = sSessionId;
end if;
return iUserId;
end;
-
usession_logout
()
declare
sSessionstring alias for $1;
begin
update tsession set userid = null where sessionstring = sSessionstring;
return 0;
end;
-
usession_userid
()
select userid from tsession where sessionstring = $1
-
uset_entityname
()
declare
iEntityID alias for $1;
iQualifierSetId alias for $2;
begin
update tentity set namequalifiersetid = iQualifierSetId;
return iQualifierSetId;
end;
-
uset_entityname
()
declare
iFeederId alias for $1;
iEntityID alias for $2;
sName alias for $3;
iNameQualifierSetId tqualifierset.qualifiersetid%TYPE;
begin
select into iNameQualifierSetId uadd_qualifierset(iFeederId, sName);
update tentity set namequalifiersetid = iNameQualifierSetId where entityid = iEntityID;
if not exists(select * from tentity_qualifierset where entityid = iEntityID and qualifiersetid = iNameQualifierSetId) then
insert into tentity_qualifierset(entityid, qualifiersetid) values(iEntityID, iNameQualifierSetId);
end if;
return iNameQualifierSetId;
end;
-
usetwordascommon
()
declare
iFeederId alias for $1;
sWord alias for $2;
iWordId tword.wordid%TYPE;
begin
iWordId := uexists_word(sWord);
if not iWordId is null then
if not exists (select * from twordnet where wordid = iWordId) then
insert into twordnet(wordid, senseid, definition, feederid) values(iWordId, 0, 'common word', iFeederId);
end if;
end if;
return iWordId;
end;
-
utag_phrase
()
select phrase
from ttag tt
inner join tqualifierset qs on tt.tagqualifiersetid = qs.qualifiersetid
where tagid = $1
-
uto_timestamp
()
declare
sTimeStamp alias for $1;
sFormat alias for $2;
dTimeStamp timestamptz;
begin
dTimeStamp := to_date(sTimeStamp, sFormat);
return dTimeStamp;
end;
-
uxml_blogpost
()
select '<post id="' || blogpostid || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(title) || '</rss:title>
<rss:pubdate><![CDATA[' || uformatdate(createdate, 2) || '</rss:pubdate>
<date><![CDATA[' || uformatdate(createdate) || '</date>
<rss:description><![CDATA[' || uxml_escapefor_cdata(description) || '</rss:description>
<rss:body>' || uxml_parsexml(body) || '</rss:body>
<rss:tags><![CDATA[' || uxml_escapefor_cdata(tags) || '</rss:tags>
</post>'
from tblogpost where blogpostid = $4;
-
uxml_blogpost
()
select uxml_blogpost($1, $2, $3, blogpostid) from tblogpost
where regexp_replace(lower(title), '[^a-z0-9 ]', ' ') = regexp_replace(lower($5), '[^a-z0-9 ]', ' ') or blogpostid = $5
and userid = $4;
-
uxml_blogposts
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iUserId alias for $4;
iBlogCategoryId alias for $5;
sXML text;
rcd record;
begin
sXML := '';
for rcd in select uxml_blogpost(sSession, sSchema, iVersion, blogpostid) from tblogpost
where blogcategoryid = iBlogCategoryId
and userid = iUserId
order by blogpostid desc
loop
sXML := sXML || rcd.uxml_blogpost;
end loop;
return sXML;
end;
-
uxml_blogtitles
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iUserId alias for $4;
iBlogCategoryId alias for $5;
sXML text;
rcd record;
begin
sXML := '';
for rcd in select blogpostid, title, description, createdate from tblogpost
where blogcategoryid = iBlogCategoryId
and userid = iUserId
order by blogpostid desc
loop
sXML := sXML || '<post id="' || rcd.blogpostid || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.title) || '</rss:title>
<rss:pubdate><![CDATA[' || uformatdate(rcd.createdate, 2) || '</rss:pubdate>
<date><![CDATA[' || uformatdate(rcd.createdate) || '</date>
<rss:description><![CDATA[' || uxml_escapefor_cdata(rcd.description) || '</rss:description>
</post>';
end loop;
return sXML;
end;
-
uxml_cms_currentvalue
()
select distinct on (cv.cmsid) '<' || uxml_escapefor_elementname(c.cmskey) || ' id="' || c.cmsid || '">
<key><![CDATA[' || uxml_escapefor_cdata(c.cmskey) || '</key>
<parentpage><![CDATA[' || uxml_escapefor_cdata(coalesce(c.parentpage, '')) || '</parentpage>
' || coalesce(uxml_user(cv.userid), '') || '
<value>' || coalesce(cv.value, '') || '</value>
</' || uxml_escapefor_elementname(c.cmskey) || '>'
from tcms c
--left outer join in case there is no version at the moment
left outer join tcmsvalue cv on c.cmsid = cv.cmsid
left outer join tuser u on cv.userid = u.userid
inner join tsession s on s.domainid = c.domainid and s.sessionstring = $1
where c.cmsid= $4
order by cv.cmsid, version desc
-
uxml_cms_currentvalue
()
select uxml_cms_currentvalue($1, $2, $3, c.cmsid)
from tcms c
inner join tcmsvalue cv on c.cmsid = cv.cmsid
inner join tsession s on c.domainid = s.domainid and s.sessionstring = $1
where c.cmskey = $4
-
uxml_cms_url
(
25, 25, 23, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25
)
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sURI_Request alias for $4; --e.g. /test
sKey text;
iID integer;
sXML text;
begin
sKey := 'CMS_' || sURI_Request;
sXML := '<root>';
--output the standard cms schema so that it auto-displays
select into sXML '<root>
<cms><' || uxml_escapefor_elementname(c.cmskey) || ' id="' || c.cmsid || '">
<key><![CDATA[' || uxml_escapefor_cdata(c.cmskey) || '</key>
<parentpage><![CDATA[' || uxml_escapefor_cdata(coalesce(c.parentpage, '')) || '</parentpage>
' || coalesce(uxml_user(cv.userid), '') || '
<value>' || coalesce(cv.value, '') || '</value>
</' || uxml_escapefor_elementname(c.cmskey) || '></cms>
</root>'
from tcms c
inner join tcmsvalue cv on c.cmsid = cv.cmsid
inner join tsession s on s.domainid = c.domainid and s.sessionstring = sSessionId
where c.cmskey = sKey
order by version desc
limit 1;
if not found then
sXML := '<root>
<pagenotfound>
<urirequest><![CDATA[' || uxml_escapefor_cdata(sURI_Request) || '</urirequest>
</pagenotfound>
</root>';
end if;
return sXML;
end;
-
uxml_cms_values
()
declare
sSessionId alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sCMSKeys alias for $4;
sXML text;
sNewXML text;
iLen integer;
i integer;
iCMSId integer;
sKey tcms.cmskey%TYPE;
begin
sXML := '<cms>';
iLen := array_upper(sCMSKeys, 1);
for i in 1..iLen loop
--auto create if not there
sKey := sCMSKeys[i];
sNewXML := uxml_cms_currentvalue(sSessionId, sSchema, iVersion, sKey);
if sNewXML is null then
iCMSId := ucms_add(sSessionId, sSchema, iVersion, sKey, '<p id="new page">new page</p>');
sNewXML := uxml_cms_currentvalue(sSessionId, sSchema, iVersion, iCMSId);
end if;
sXML := sXML || coalesce(sNewXML, '');
end loop;
sXML := sXML || '</cms>';
return sXML;
end;
-
uxml_commitment
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCommitmentId alias for $4;
sXML text;
begin
sXML := '<commitment id="' || iCommitmentId || '"/>';
return sXML;
end;
-
uxml_company
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCompanyId alias for $4;
iExternalSourceId alias for $5;
iLimitDocs alias for $6;
sXML text;
s45 text;
bTruncated bool;
iLimitDocsR integer;
sEntityName text;
iEntityId tentity.entityid%TYPE;
iSessionId tsession.sessionid%TYPE;
iArticleId tarticle.articleid%TYPE;
rcd record;
rcd_doc record;
begin
--base details for the company
select into iEntityId, sEntityName entityid, uentityname(entityid)
from tlcompany where companyid = iCompanyId;
sXML := '<company id="' || iEntityId || '" companyid="' || iCompanyId || '">
<name><![CDATA[' || uxml_escapefor_cdata(sEntityName) || '</name>';
--mark the company as a primary interest company for the session
iSessionId := usession_id(sSession);
update tsession_entity set addsource = 'P'
where sessionid = iSessionId and entityid = iEntityId;
if not found then
insert into tsession_entity(sessionid, entityid, addsource) values(iSessionId, iEntityId, 'P');
end if;
--overall tags for the company
sXML := sXML || '<taggroups>';
for rcd in select tg.taggroupid, tg.tag, count(*)
from tentity_article tea
inner join tarticle_tag tat on tea.entityid = iEntityId and tea.articleid = tat.articleid
inner join tarticle ta on tea.articleid = ta.articleid
inner join ttag tt on tat.tagid = tt.tagid
inner join ttaggroup tg on tt.taggroupid = tg.taggroupid
where (iExternalSourceId = 0 or ta.externalsourceid = iExternalSourceId)
group by tg.taggroupid, tg.tag
order by count(*) desc
limit 100
loop
sXML := sXML || '<taggroup id="' || rcd.taggroupid || '" count="' || rcd.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</rss:title>
</taggroup>';
end loop;
sXML := sXML || '</taggroups>';
--related entities to this main company
sXML := sXML || '<related><entities>';
for rcd in select relatedentityid, uentityname(relatedentityid) as name, inarticles
from vrelatedentities
where entityid = iEntityId
order by inarticles desc
limit 20
loop
sXML := sXML || '<company id="' || rcd.relatedentityid || '" inarticles="' || rcd.inarticles || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
</company>';
end loop;
sXML := sXML || '</entities></related>';
--aliases of this company
sXML := sXML || '<aliases>';
for rcd in select eqs.qualifiersetid, qs.phrase as alias
from tentity_qualifierset eqs
inner join tqualifierset qs on eqs.qualifiersetid = qs.qualifiersetid
where eqs.entityid = iEntityId
loop
sXML := sXML || '<alias id="' || rcd.qualifiersetid || '"><![CDATA[' || uxml_escapefor_cdata(rcd.alias) || '</alias>';
end loop;
sXML := sXML || '</aliases>';
-- ##################################### articles #####################################
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[articles about ' || uxml_escapefor_cdata(sEntityName) || '</rss:title>
<rss:description><![CDATA[articles bought into the database from journalistic archives around the web</rss:description>
<rss:relativelinkroot><![CDATA[/article/</rss:relativelinkroot>
</rss:details>
<rss:items>';
select into sXML sXML || '<articles count="' || count(*) || '" externalsourceid="' || iExternalSourceId || '">'
from tentity_article where entityid = iEntityId;
for rcd_doc in select ta.articleid, ta.createdate, ta.title, ta.body, xs.externalsourceid, xs.domain, xs.rootpagetitle
from tentity_article ea
inner join tarticle ta on ea.articleid = ta.articleid
inner join texternalsource xs on ta.externalsourceid = xs.externalsourceid
where entityid = iEntityId
and (iExternalSourceId = 0 or xs.externalsourceid = iExternalSourceId)
order by ta.title
limit iLimitDocsR
loop
iArticleId := rcd_doc.articleid;
sXML := sXML || '<article id="' || iArticleId || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd_doc.title) || '</rss:title>
<source id="' || rcd_doc.externalsourceid || '">
<domain><![CDATA[' || uxml_escapefor_cdata(rcd_doc.domain) || '</domain>
<rootpagetitle><![CDATA[' || uxml_escapefor_cdata(rcd_doc.rootpagetitle) || '</rootpagetitle>
</source>
<date>' || uformatdate(rcd_doc.createdate) || '</date>
<rss:pubdate>' || uformatdate(rcd_doc.createdate, 2) || '</rss:pubdate>
<rss:description link="summary">link</rss:description>';
sXML := sXML || '<descriptions>';
--first para
s45 := substring(rcd_doc.body from '<p>([^<]+)</p>');
if not (s45 is null or char_length(s45) = 0) then
if char_length(s45) > 500 then
s45 := substring(s45 from '^[ .,]*(([^ .,]*[ .,]+){0,45})');
bTruncated := true;
else
bTruncated := false;
end if;
sXML := sXML || '<firstpara truncated="' || bTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</firstpara>';
end if;
--summaries
sXML := sXML || '<summaries>';
for rcd in select ts.summaryid, ts.title, ts.body, ts.createdate
from tsummary ts
where ts.articleid = iArticleId
loop
if char_length(rcd.body) > 500 then
s45 := substring(rcd.body from '^[ .,]*(([^ .,]*[ .,]+){0,45})');
bTruncated := true;
else
s45 := rcd.body;
bTruncated := false;
end if;
sXML := sXML || '<summary id="' || rcd.summaryid || '" truncated="' || bTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</summary>';
end loop;
sXML := sXML || '</summaries>';
--key sentences
sXML := sXML || '<sentences>';
sXML := sXML || '<sentence><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '[^.!?:<>]*' || sEntityName || '[^.!?:<>]*')) || '</sentence>';
sXML := sXML || '</sentences>';
sXML := sXML || '</descriptions>';
--tags
sXML := sXML || '<tags>';
for rcd in select tt.tagid, qs.phrase as tag, tt.tagtype
from tarticle_tag at
inner join ttag tt on at.tagid = tt.tagid
inner join tqualifierset qs on tt.tagqualifiersetid = qs.qualifiersetid
where at.articleid = iArticleId
order by tag
loop
sXML := sXML || '<tag id="' || rcd.tagid || '" type="' || rcd.tagtype || '"><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</tag>';
end loop;
sXML := sXML || '</tags>';
sXML := sXML || '</article>';
end loop;
sXML := sXML || '</articles>';
sXML := sXML || '</rss:items>';
sXML := sXML || '</rss:feed>';
sXML := sXML || '</company>';
return sXML;
end;
-
uxml_country
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iCountryId alias for $4;
iLimitDocs alias for $5;
sXML text;
iLimitDocsR integer;
sEntityName text;
iEntityId tentity.entityid%TYPE;
rcd_alias record;
rcd_doc record;
rcd_tag record;
begin
--base details
sXML := '<country id="' || iCountryId || '">';
select into iEntityId, sEntityName entityid, uentityname(entityid)
from tlcountry where countryid = iCountryId;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(sEntityName) || '</name>';
--aliases
sXML := sXML || '<aliases>';
for rcd_alias in select eqs.qualifiersetid, qs.phrase as alias
from tentity_qualifierset eqs
inner join tqualifierset qs on eqs.qualifiersetid = qs.qualifiersetid
where eqs.entityid = iEntityId
loop
sXML := sXML || '<alias id="' || rcd_alias.qualifiersetid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_alias.alias) || '</alias>';
end loop;
sXML := sXML || '</aliases>';
--documents
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
select into sXML sXML || '<articles count="' || count(*) || '">'
from tentity_article where entityid = iEntityId;
for rcd_doc in select ta.articleid, ta.title, ta.body, xs.externalsourceid, xs.domain
from tentity_article ea
inner join tarticle ta on ea.articleid = ta.articleid
inner join texternalsource xs on ta.externalsourceid = xs.externalsourceid
where entityid = iEntityId
order by ta.title
limit iLimitDocsR
loop
sXML := sXML || '<article id="' || rcd_doc.articleid || '">
<title><![CDATA[' || uxml_escapefor_cdata(rcd_doc.title) || '</title>
<source id="' || rcd_doc.externalsourceid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_doc.domain) || '</source>';
sXML := sXML || '<firstpara><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '<p>([^<]+)</p>')) || '</firstpara>';
--key sentences
sXML := sXML || '<sentences>';
sXML := sXML || '<sentence><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '[^.!?:<>]*' || sEntityName || '[^.!?:<>]*')) || '</sentence>';
sXML := sXML || '</sentences>';
--tags
sXML := sXML || '<tags>';
for rcd_tag in select tt.tagid, qs.phrase as tag, tt.tagtype
from tarticle_tag at
inner join ttag tt on at.tagid = tt.tagid
inner join tqualifierset qs on tt.tagqualifiersetid = qs.qualifiersetid
where at.articleid = rcd_doc.articleid
order by tag
loop
sXML := sXML || '<tag id="' || rcd_tag.tagid || '" type="' || rcd_tag.tagtype || '"><![CDATA[' || uxml_escapefor_cdata(rcd_tag.tag) || '</tag>';
end loop;
sXML := sXML || '</tags>';
sXML := sXML || '</article>';
end loop;
sXML := sXML || '</articles>';
sXML := sXML || '</country>';
return sXML;
end;
-
uxml_escapefor_cdata
()
select replace(replace(cast(coalesce($1, '') as text)
, '&', '&amp;')
, '', '')
-
uxml_escapefor_elementname
()
select replace(regexp_replace($1, '[^a-zA-Z]'), '/', '')
-
uxml_escapefor_textelement
()
select replace(replace(replace(uxml_escapefor_cdata(cast(coalesce($1, '') as text))
,'"', '&quot;')
, '<', '&lt;')
, '>', '&gt;')
-
uxml_externalsource
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iExternalSourceId alias for $4;
iLimitDocs alias for $5;
sXML text;
sRootpagetitle text;
rcd record;
begin
--base details
--including article counts
select into sRootpagetitle, sXML tx.rootpagetitle, '<externalsource id="' || tx.externalsourceid || '">
<rootpagetitle><![CDATA[' || uxml_escapefor_cdata(tx.rootpagetitle) || '</rootpagetitle>
<domain><![CDATA[' || uxml_escapefor_cdata(tx.domain) || '</domain>'
from texternalsource tx
where tx.externalsourceid = iExternalSourceId;
--taggroups (all of the areas that the source covers)
select into sXML sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[areas covered by external source ' || uxml_escapefor_cdata(sRootpagetitle) || '</rss:title>
<rss:description><![CDATA[areas of ethics covered by an external source</rss:description>
<rss:relativelinkroot><![CDATA[/tags/</rss:relativelinkroot>
</rss:details>
<rss:items>
<taggroups count="' || count(distinct tt.taggroupid) || '">'
from tarticle ta
inner join tarticle_tag tat on ta.articleid = tat.articleid and ta.externalsourceid = iExternalSourceId
inner join ttag tt on tat.tagid = tt.tagid;
for rcd in select tg.taggroupid, tg.tag, count(*)
from tarticle ta
inner join tarticle_tag tat on ta.articleid = tat.articleid and ta.externalsourceid = iExternalSourceId
inner join ttag tt on tat.tagid = tt.tagid
inner join ttaggroup tg on tt.taggroupid = tg.taggroupid
group by tg.taggroupid, tg.tag
order by count(*) desc
limit 100
loop
sXML := sXML || '<taggroup id="' || rcd.taggroupid || '" count="' || rcd.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</rss:title>
</taggroup>';
end loop;
sXML := sXML || '</taggroups>
</rss:items>
</rss:feed>';
--categories
sXML := sXML || '<categories>';
sXML := sXML || '</categories>';
--companies that the source covers
sXML := sXML || '<entities>';
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[companies covered by external source ' || uxml_escapefor_cdata(sRootpagetitle) || '</rss:title>
<rss:description><![CDATA[companies that this external source discusses</rss:description>
<rss:relativelinkroot><![CDATA[/company/</rss:relativelinkroot>
</rss:details>
<rss:items>
<companies count="' || count(distinct tc.entityid) || '">'
from tarticle ta
inner join tentity_article tea on ta.externalsourceid = iExternalSourceId and ta.articleid = tea.articleid
inner join tlcompany tc on tea.entityid = tc.entityid;
for rcd in select tea.entityid, tc.companyid, qs.phrase, count(*)
from tarticle ta
inner join tentity_article tea on ta.externalsourceid = iExternalSourceId and ta.articleid = tea.articleid
inner join tlcompany tc on tea.entityid = tc.entityid
inner join tentity te on te.entityid = tc.entityid
inner join tqualifierset qs on te.namequalifiersetid = qs.qualifiersetid
group by tea.entityid, tc.companyid, qs.phrase
order by count(*) desc
limit 100
loop
sXML := sXML || '<company id="' || rcd.companyid || '" entityid="' || rcd.entityid || '" count="' || rcd.count || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.phrase) || '</rss:title>
</company>';
end loop;
sXML := sXML || '</companies>
</rss:items>
</rss:feed>';
sXML := sXML || '</entities>';
sXML := sXML || '</externalsource>';
return sXML;
end;
-
uxml_parsexml
()
declare
begin
return $1;
end;
-
uxml_parsexmltotext
()
select regexp_replace($1, '<[^>]+>', ' ')
-
uxml_person
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iPersonId alias for $4;
iLimitDocs alias for $5;
sXML text;
iLimitDocsR integer;
sEntityName text;
iEntityId tentity.entityid%TYPE;
rcd_alias record;
rcd_doc record;
rcd_tag record;
begin
--base details
sXML := '<person id="' || iPersonId || '">';
select into iEntityId, sEntityName entityid, uentityname(entityid)
from tlperson where personid = iPersonId;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(sEntityName) || '</name>';
--aliases
sXML := sXML || '<aliases>';
for rcd_alias in select eqs.qualifiersetid, qs.phrase as alias
from tentity_qualifierset eqs
inner join tqualifierset qs on eqs.qualifiersetid = qs.qualifiersetid
where eqs.entityid = iEntityId
loop
sXML := sXML || '<alias id="' || rcd_alias.qualifiersetid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_alias.alias) || '</alias>';
end loop;
sXML := sXML || '</aliases>';
--documents
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
select into sXML sXML || '<articles count="' || count(*) || '">'
from tentity_article where entityid = iEntityId;
for rcd_doc in select ta.articleid, ta.title, ta.body, xs.externalsourceid, xs.domain
from tentity_article ea
inner join tarticle ta on ea.articleid = ta.articleid
inner join texternalsource xs on ta.externalsourceid = xs.externalsourceid
where entityid = iEntityId
order by ta.title
limit iLimitDocsR
loop
sXML := sXML || '<article id="' || rcd_doc.articleid || '">
<title><![CDATA[' || uxml_escapefor_cdata(rcd_doc.title) || '</title>
<source id="' || rcd_doc.externalsourceid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_doc.domain) || '</source>';
sXML := sXML || '<firstpara><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '<p>([^<]+)</p>')) || '</firstpara>';
--key sentences
sXML := sXML || '<sentences>';
sXML := sXML || '<sentence><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '[^.!?:<>]*' || sEntityName || '[^.!?:<>]*')) || '</sentence>';
sXML := sXML || '</sentences>';
--tags
sXML := sXML || '<tags>';
for rcd_tag in select tt.tagid, uqualifierset_name(tt.tagqualifiersetid, 0, 0) as tag, tt.tagtype
from tarticle_tag at inner join ttag tt on at.tagid = tt.tagid
where articleid = rcd_doc.articleid
order by tag
loop
sXML := sXML || '<tag id="' || rcd_tag.tagid || '" type="' || rcd_tag.tagtype || '"><![CDATA[' || uxml_escapefor_cdata(rcd_tag.tag) || '</tag>';
end loop;
sXML := sXML || '</tags>';
sXML := sXML || '</article>';
end loop;
sXML := sXML || '</articles>';
sXML := sXML || '</person>';
return sXML;
end;
-
uxml_product
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iProductId alias for $4;
iLimitDocs alias for $5;
sXML text;
s45 text;
sTruncated bool;
iLimitDocsR integer;
sEntityName text;
iEntityId tentity.entityid%TYPE;
iArticleId tarticle.articleid%TYPE;
rcd_alias record;
rcd_doc record;
rcd_tag record;
rcd_summary record;
begin
--base details
sXML := '<product id="' || iProductId || '">';
select into iEntityId, sEntityName entityid, uentityname(entityid)
from tlproduct where productid = iProductId;
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(sEntityName) || '</name>';
--aliases
sXML := sXML || '<aliases>';
for rcd_alias in select eqs.qualifiersetid, qs.phrase as alias
from tentity_qualifierset eqs
inner join tqualifierset qs on eqs.qualifiersetid = qs.qualifiersetid
where eqs.entityid = iEntityId
loop
sXML := sXML || '<alias id="' || rcd_alias.qualifiersetid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_alias.alias) || '</alias>';
end loop;
sXML := sXML || '</aliases>';
--articles
if iLimitDocs = 0 then iLimitDocsR = 10; else iLimitDocsR = iLimitDocs; end if;
select into sXML sXML || '<articles count="' || count(*) || '">'
from tentity_article where entityid = iEntityId;
for rcd_doc in select ta.articleid, ta.title, ta.body, xs.externalsourceid, xs.domain
from tentity_article ea
inner join tarticle ta on ea.articleid = ta.articleid
inner join texternalsource xs on ta.externalsourceid = xs.externalsourceid
where entityid = iEntityId
order by ta.title
limit iLimitDocsR
loop
iArticleId := rcd_doc.articleid;
sXML := sXML || '<article id="' || iArticleId || '">
<title><![CDATA[' || uxml_escapefor_cdata(rcd_doc.title) || '</title>
<source id="' || rcd_doc.externalsourceid || '"><![CDATA[' || uxml_escapefor_cdata(rcd_doc.domain) || '</source>';
sXML := sXML || '<descriptions>';
--first para
s45 := substring(substring(rcd_doc.body from '<p>([^<]+)</p>') from '^[ .,]*(([^ .,]*[ .,]+){0,45})');
sXML := sXML || '<firstpara><![CDATA[' || uxml_escapefor_cdata(s45) || '</firstpara>';
--summaries
sXML := sXML || '<summaries>';
for rcd_summary in select ts.summaryid, ts.title, ts.body, ts.createdate
from tsummary ts
where ts.articleid = iArticleId
loop
s45 := substring(rcd_summary.body from '^[ .,]*(([^ .,]*[ .,]+){0,45})');
sTruncated := (not s45 = rcd_summary.body);
sXML := sXML || '<summary id="' || rcd_summary.summaryid || '" truncated="' || sTruncated || '"><![CDATA[' || uxml_escapefor_cdata(s45) || '</summary>';
end loop;
sXML := sXML || '</summaries>';
--key sentences
sXML := sXML || '<sentences>';
sXML := sXML || '<sentence><![CDATA[' || uxml_escapefor_cdata(substring(rcd_doc.body from '[^.!?:<>]*' || sEntityName || '[^.!?:<>]*')) || '</sentence>';
sXML := sXML || '</sentences>';
sXML := sXML || '</descriptions>';
--tags
sXML := sXML || '<tags>';
for rcd_tag in select tt.tagid, qs.phrase as tag, tt.tagtype
from tarticle_tag at
inner join ttag tt on at.tagid = tt.tagid
inner join tqualifierset qs on tt.tagqualifiersetid = qs.qualifiersetid
where at.articleid = rcd_doc.articleid
order by tag
loop
sXML := sXML || '<tag id="' || rcd_tag.tagid || '" type="' || rcd_tag.tagtype || '"><![CDATA[' || uxml_escapefor_cdata(rcd_tag.tag) || '</tag>';
end loop;
sXML := sXML || '</tags>';
sXML := sXML || '</article>';
end loop;
sXML := sXML || '</articles>';
sXML := sXML || '</product>';
return sXML;
end;
-
uxml_session
()
/* SessionCompanies
XML for the company rating bar / screen
all the companies held by the current context (all sessions in last 48 hours)
with their community ratings, user adjustments and user knowledge
*/
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
sXML text;
iSessionId tsession.sessionid%TYPE;
rcd record;
begin
iSessionId := usession_id(sSession);
select into sXML '<session
id="' || sessionid || '"
string="' || sessionstring || '"
autosaveentities="' || autosaveentities || '"
autosavearticles="' || autosavearticles || '">'
from tsession where sessionid = iSessionId;
--companies that have appeared in the documents that the user has read about
sXML := sXML || '<collected><entities>';
for rcd in select se.entityid, se.rank as companyrank, se.addsource, se.touched,
qs.phrase as name,
vkr.count, vkr.groupcount, vkr.rank as knowledgerank
from tsession ts
inner join tsession_entity se on ts.sessionid = se.sessionid
inner join tentity e on se.entityid = e.entityid
inner join tlcompany tc on e.entityid = tc.entityid
inner join tqualifierset qs on e.namequalifiersetid = qs.qualifiersetid
left outer join vknowledge_rank vkr on e.entityid = vkr.entityid and vkr.userid = ts.userid
where ts.sessionid = iSessionId
order by se.addsource, se.rank asc
loop
sXML := sXML || '<company
id="' || rcd.entityid || '"
rank="' || rcd.companyrank || '"
addsource="' || rcd.addsource || '"
touched="' || rcd.touched || '"
>';
sXML := sXML || '<knowledge count="' || coalesce(rcd.count, 0) || '" groupcount="' || coalesce(rcd.groupcount, 0) || '" rank="' || coalesce(rcd.knowledgerank, 0) || '"/>';
sXML := sXML || '<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name></company>';
end loop;
sXML := sXML || '</entities></collected>';
sXML := sXML || '</session>';
return sXML;
end;
-
uxml_taggroup
()
declare
sSession alias for $1;
sSchema alias for $2;
iVersion alias for $3;
iTaggroupId alias for $4;
sXML text;
sTitle text;
rcd record;
begin
--base details
select into sTitle, sXML tag, '<taggroup id="' || taggroupid || '">
<tag><![CDATA[' || uxml_escapefor_cdata(tag) || '</tag>'
from ttaggroup where taggroupid = iTaggroupId;
--members
sXML := sXML || '<members>';
for rcd in select tt.tagid, uqualifierset_name(tt.tagqualifiersetid, 0, 0) as name
from ttag tt
where tt.taggroupid = iTaggroupId
order by uqualifierset_name(tt.tagqualifiersetid, 0, 0)
loop
sXML := sXML || '<tag id="' || rcd.tagid || '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
</tag>';
end loop;
sXML := sXML || '</members>';
--bigrams
sXML := sXML || '<bigrams>';
for rcd in select tb.bigramid, tw1.word as word1, tw2.word as word2, tcb.count
from ttaggroup_bigram tcb
inner join tbigram tb on tcb.bigramid = tb.bigramid
inner join tword tw1 on tb.word1 = tw1.wordid
inner join tword tw2 on tb.word2 = tw2.wordid
where tcb.taggroupid = iTaggroupId
order by count desc
limit 100
loop
sXML := sXML || '<bigram id="' || rcd.bigramid || '" count="' || rcd.count || '">
<word1><![CDATA[' || uxml_escapefor_cdata(rcd.word1) || '</word1>
<word2><![CDATA[' || uxml_escapefor_cdata(rcd.word2) || '</word2>
</bigram>';
end loop;
sXML := sXML || '</bigrams>';
--unigrams
sXML := sXML || '<unigrams>';
for rcd in select tw.wordid, tw.word, tcb.count
from ttaggroup_unigram tcb
inner join tword tw on tcb.wordid = tw.wordid
where tcb.taggroupid = iTaggroupId
order by count desc
limit 100
loop
sXML := sXML || '<unigram id="' || rcd.wordid || '" count="' || rcd.count || '">
<word><![CDATA[' || uxml_escapefor_cdata(rcd.word) || '</word>
</unigram>';
end loop;
sXML := sXML || '</unigrams>';
--unigrams
sXML := sXML || '<associatedtaggroups>';
for rcd in select ttg.taggroupid, ttg.tag, ttt.count
from ttaggroup_taggroup ttt
inner join ttaggroup ttg on ttt.associatedtaggroupid = ttg.taggroupid
where ttt.taggroupid = iTaggroupId
order by count desc
limit 100
loop
sXML := sXML || '<taggroup id="' || rcd.taggroupid || '" count="' || rcd.count || '">
<tag><![CDATA[' || uxml_escapefor_cdata(rcd.tag) || '</tag>
</taggroup>';
end loop;
sXML := sXML || '</associatedtaggroups>';
--articles
sXML := sXML || '<rss:feed>
<rss:details>
<rss:title><![CDATA[articles in the area of '' || uxml_escapefor_cdata(sTitle) || ''</rss:title>
<rss:description><![CDATA[articles bought into the database from journalistic archives around the web</rss:description>
<rss:relativelinkroot><![CDATA[/article/</rss:relativelinkroot>
</rss:details>
<rss:items>
<articles>';
for rcd in select distinct ta.articleid, substring(ta.title from '[A-Za-z0-9£$%].*') as title
from tarticle ta
inner join tarticle_tag tat on ta.articleid = tat.articleid
inner join ttag tt on tat.tagid = tt.tagid
where tt.taggroupid = iTaggroupId
order by substring(ta.title from '[A-Za-z0-9£$%].*')
limit 100
loop
sXML := sXML || '<article id="' || rcd.articleid || '">
<rss:title><![CDATA[' || uxml_escapefor_cdata(rcd.title) || '</rss:title>
</article>';
end loop;
sXML := sXML || '</articles>
</rss:items>
</rss:feed>';
sXML := sXML || '</taggroup>';
return sXML;
end;
-
uxml_user
()
declare
iUserId alias for $1;
sXML text;
sStatus text;
rcd record;
begin
select into sXML '<user id="' || userid || '">
<type9c><![CDATA[' || uxml_escapefor_cdata(type9c) || '</type9c>
<avatar><![CDATA[' || uxml_escapefor_cdata(avatar) || '</avatar>
<firstname><![CDATA[' || uxml_escapefor_cdata(firstname) || '</firstname>
<middlename><![CDATA[' || uxml_escapefor_cdata(middlename) || '</middlename>
<lastname><![CDATA[' || uxml_escapefor_cdata(lastname) || '</lastname>
<username><![CDATA[' || uxml_escapefor_cdata(username) || '</username>
<verified><![CDATA[' || verified || '</verified>
<location longitude="' || coalesce(longitude, 0) || '" latitude="' || coalesce(latitude, 0) || '"><![CDATA[' || coalesce(location, '') || '</location>'
from tuser
where userid = iUserId;
--<emailaddress><![CDATA[' || uxml_escapefor_cdata(emailaddress) || '</emailaddress>
if sXML is null then
sXML := '<nouser/>';
else
--status
select into sStatus status from vlaststatus where userid = iUserId;
if not sStatus is null then
sXML := sXML || '<status><![CDATA[' || uxml_escapefor_cdata(sStatus) || '</status>';
end if;
--users groups
sXML := sXML || '<usergroups>';
for rcd in select tug.usergroupid, tug.name
from tusergroup tug
inner join tusergroup_user tugu on tug.usergroupid = tugu.usergroupid
where tugu.userid = iUserId
loop
sXML := sXML || '<usergroup id="' || rcd.usergroupid|| '">
<name><![CDATA[' || uxml_escapefor_cdata(rcd.name) || '</name>
</usergroup>';
end loop;
sXML := sXML || '</usergroups>';
sXML := sXML || '</user>';
end if;
return sXML;
end;
-
version_major
()
select substring(version() from 'PostgreSQL ([0-9]+.[0-9]+)')::numeric(6, 1)
-
version_minor
()
select substring(version() from 'PostgreSQL [0-9]+\\.[0-9]+\\.([0-9]+)')::integer